From 781b1a6df324419c846c84ea983c18fc8362bfd3 Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Wed, 13 Dec 2017 11:19:06 -0800 Subject: Third part of onap rename This part of the commit changes the folder structure on all other folders of appc. Change-Id: I8acfa11cdfcdcd36be0e137245d1dd7324f1abd3 Signed-off-by: Patrick Brady Issue-ID: APPC-13 --- .../src/main/java/org/onap/appc/RPC.java | 37 + .../lcm/api/AppcClientServiceFactoryProvider.java | 43 + .../api/AppcLifeCycleManagerServiceFactory.java | 49 + .../appc/client/lcm/api/ApplicationContext.java | 50 + .../client/lcm/api/LifeCycleManagerStateful.java | 901 +++++++++++++++ .../onap/appc/client/lcm/api/ResponseHandler.java | 42 + .../exceptions/AppcClientBusinessException.java | 44 + .../client/lcm/exceptions/AppcClientException.java | 44 + .../exceptions/AppcClientInternalException.java | 44 + .../AppcLifeCycleManagerServiceFactoryImpl.java | 61 + .../business/CoreAsyncResponseHandlerImpl.java | 60 + .../lcm/impl/business/CoreResponseHandler.java | 108 ++ .../impl/business/CoreSyncResponseHandlerImpl.java | 51 + .../lcm/impl/business/LCMRequestProcessor.java | 120 ++ .../client/lcm/impl/business/RPCInvocator.java | 85 ++ .../org/onap/appc/client/lcm/model/Action.java | 85 ++ .../appc/client/lcm/model/ActionIdentifiers.java | 109 ++ .../org/onap/appc/client/lcm/model/AuditInput.java | 106 ++ .../onap/appc/client/lcm/model/AuditOutput.java | 89 ++ .../onap/appc/client/lcm/model/CheckLockInput.java | 89 ++ .../appc/client/lcm/model/CheckLockOutput.java | 94 ++ .../onap/appc/client/lcm/model/CommonHeader.java | 143 +++ .../client/lcm/model/ConfigBackupDeleteInput.java | 89 ++ .../client/lcm/model/ConfigBackupDeleteOutput.java | 89 ++ .../appc/client/lcm/model/ConfigBackupInput.java | 106 ++ .../appc/client/lcm/model/ConfigBackupOutput.java | 89 ++ .../appc/client/lcm/model/ConfigExportInput.java | 89 ++ .../appc/client/lcm/model/ConfigExportOutput.java | 72 ++ .../appc/client/lcm/model/ConfigModifyInput.java | 106 ++ .../appc/client/lcm/model/ConfigModifyOutput.java | 89 ++ .../appc/client/lcm/model/ConfigRestoreInput.java | 106 ++ .../appc/client/lcm/model/ConfigRestoreOutput.java | 89 ++ .../appc/client/lcm/model/ConfigScaleoutInput.java | 106 ++ .../client/lcm/model/ConfigScaleoutOutput.java | 89 ++ .../onap/appc/client/lcm/model/ConfigureInput.java | 106 ++ .../appc/client/lcm/model/ConfigureOutput.java | 89 ++ .../onap/appc/client/lcm/model/EvacuateInput.java | 106 ++ .../onap/appc/client/lcm/model/EvacuateOutput.java | 72 ++ .../java/org/onap/appc/client/lcm/model/Flags.java | 102 ++ .../appc/client/lcm/model/HealthCheckInput.java | 106 ++ .../appc/client/lcm/model/HealthCheckOutput.java | 72 ++ .../appc/client/lcm/model/LiveUpgradeInput.java | 106 ++ .../appc/client/lcm/model/LiveUpgradeOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/LockInput.java | 106 ++ .../org/onap/appc/client/lcm/model/LockOutput.java | 72 ++ .../onap/appc/client/lcm/model/MigrateInput.java | 106 ++ .../onap/appc/client/lcm/model/MigrateOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/Payload.java | 59 + .../onap/appc/client/lcm/model/RebuildInput.java | 106 ++ .../onap/appc/client/lcm/model/RebuildOutput.java | 72 ++ .../onap/appc/client/lcm/model/RestartInput.java | 106 ++ .../onap/appc/client/lcm/model/RestartOutput.java | 72 ++ .../onap/appc/client/lcm/model/RollbackInput.java | 128 +++ .../onap/appc/client/lcm/model/RollbackOutput.java | 72 ++ .../onap/appc/client/lcm/model/SnapshotInput.java | 117 ++ .../onap/appc/client/lcm/model/SnapshotOutput.java | 83 ++ .../appc/client/lcm/model/SoftwareUploadInput.java | 106 ++ .../client/lcm/model/SoftwareUploadOutput.java | 72 ++ .../client/lcm/model/StartApplicationInput.java | 106 ++ .../client/lcm/model/StartApplicationOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/StartInput.java | 106 ++ .../onap/appc/client/lcm/model/StartOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/Status.java | 75 ++ .../client/lcm/model/StopApplicationInput.java | 106 ++ .../client/lcm/model/StopApplicationOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/StopInput.java | 106 ++ .../org/onap/appc/client/lcm/model/StopOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/SyncInput.java | 106 ++ .../org/onap/appc/client/lcm/model/SyncOutput.java | 89 ++ .../onap/appc/client/lcm/model/TerminateInput.java | 106 ++ .../appc/client/lcm/model/TerminateOutput.java | 72 ++ .../org/onap/appc/client/lcm/model/TestInput.java | 106 ++ .../org/onap/appc/client/lcm/model/TestOutput.java | 72 ++ .../onap/appc/client/lcm/model/UnlockInput.java | 106 ++ .../onap/appc/client/lcm/model/UnlockOutput.java | 72 ++ .../java/org/onap/appc/client/lcm/model/ZULU.java | 59 + .../src/main/java/org/openecomp/appc/RPC.java | 37 - .../lcm/api/AppcClientServiceFactoryProvider.java | 43 - .../api/AppcLifeCycleManagerServiceFactory.java | 49 - .../appc/client/lcm/api/ApplicationContext.java | 50 - .../client/lcm/api/LifeCycleManagerStateful.java | 901 --------------- .../appc/client/lcm/api/ResponseHandler.java | 42 - .../exceptions/AppcClientBusinessException.java | 44 - .../client/lcm/exceptions/AppcClientException.java | 44 - .../exceptions/AppcClientInternalException.java | 44 - .../AppcLifeCycleManagerServiceFactoryImpl.java | 61 - .../business/CoreAsyncResponseHandlerImpl.java | 60 - .../lcm/impl/business/CoreResponseHandler.java | 108 -- .../impl/business/CoreSyncResponseHandlerImpl.java | 51 - .../lcm/impl/business/LCMRequestProcessor.java | 120 -- .../client/lcm/impl/business/RPCInvocator.java | 85 -- .../openecomp/appc/client/lcm/model/Action.java | 85 -- .../appc/client/lcm/model/ActionIdentifiers.java | 109 -- .../appc/client/lcm/model/AuditInput.java | 106 -- .../appc/client/lcm/model/AuditOutput.java | 89 -- .../appc/client/lcm/model/CheckLockInput.java | 89 -- .../appc/client/lcm/model/CheckLockOutput.java | 94 -- .../appc/client/lcm/model/CommonHeader.java | 143 --- .../client/lcm/model/ConfigBackupDeleteInput.java | 89 -- .../client/lcm/model/ConfigBackupDeleteOutput.java | 89 -- .../appc/client/lcm/model/ConfigBackupInput.java | 106 -- .../appc/client/lcm/model/ConfigBackupOutput.java | 89 -- .../appc/client/lcm/model/ConfigExportInput.java | 89 -- .../appc/client/lcm/model/ConfigExportOutput.java | 72 -- .../appc/client/lcm/model/ConfigModifyInput.java | 106 -- .../appc/client/lcm/model/ConfigModifyOutput.java | 89 -- .../appc/client/lcm/model/ConfigRestoreInput.java | 106 -- .../appc/client/lcm/model/ConfigRestoreOutput.java | 89 -- .../appc/client/lcm/model/ConfigScaleoutInput.java | 106 -- .../client/lcm/model/ConfigScaleoutOutput.java | 89 -- .../appc/client/lcm/model/ConfigureInput.java | 106 -- .../appc/client/lcm/model/ConfigureOutput.java | 89 -- .../appc/client/lcm/model/EvacuateInput.java | 106 -- .../appc/client/lcm/model/EvacuateOutput.java | 72 -- .../org/openecomp/appc/client/lcm/model/Flags.java | 102 -- .../appc/client/lcm/model/HealthCheckInput.java | 106 -- .../appc/client/lcm/model/HealthCheckOutput.java | 72 -- .../appc/client/lcm/model/LiveUpgradeInput.java | 106 -- .../appc/client/lcm/model/LiveUpgradeOutput.java | 72 -- .../openecomp/appc/client/lcm/model/LockInput.java | 106 -- .../appc/client/lcm/model/LockOutput.java | 72 -- .../appc/client/lcm/model/MigrateInput.java | 106 -- .../appc/client/lcm/model/MigrateOutput.java | 72 -- .../openecomp/appc/client/lcm/model/Payload.java | 59 - .../appc/client/lcm/model/RebuildInput.java | 106 -- .../appc/client/lcm/model/RebuildOutput.java | 72 -- .../appc/client/lcm/model/RestartInput.java | 106 -- .../appc/client/lcm/model/RestartOutput.java | 72 -- .../appc/client/lcm/model/RollbackInput.java | 128 --- .../appc/client/lcm/model/RollbackOutput.java | 72 -- .../appc/client/lcm/model/SnapshotInput.java | 117 -- .../appc/client/lcm/model/SnapshotOutput.java | 83 -- .../appc/client/lcm/model/SoftwareUploadInput.java | 106 -- .../client/lcm/model/SoftwareUploadOutput.java | 72 -- .../client/lcm/model/StartApplicationInput.java | 106 -- .../client/lcm/model/StartApplicationOutput.java | 72 -- .../appc/client/lcm/model/StartInput.java | 106 -- .../appc/client/lcm/model/StartOutput.java | 72 -- .../openecomp/appc/client/lcm/model/Status.java | 75 -- .../client/lcm/model/StopApplicationInput.java | 106 -- .../client/lcm/model/StopApplicationOutput.java | 72 -- .../openecomp/appc/client/lcm/model/StopInput.java | 106 -- .../appc/client/lcm/model/StopOutput.java | 72 -- .../openecomp/appc/client/lcm/model/SyncInput.java | 106 -- .../appc/client/lcm/model/SyncOutput.java | 89 -- .../appc/client/lcm/model/TerminateInput.java | 106 -- .../appc/client/lcm/model/TerminateOutput.java | 72 -- .../openecomp/appc/client/lcm/model/TestInput.java | 106 -- .../appc/client/lcm/model/TestOutput.java | 72 -- .../appc/client/lcm/model/UnlockInput.java | 106 -- .../appc/client/lcm/model/UnlockOutput.java | 72 -- .../org/openecomp/appc/client/lcm/model/ZULU.java | 59 - ...TestAppcLifeCycleManagerServiceFactoryImpl.java | 60 + .../onap/appc/client/lcm/model/TestModelPOJO.java | 144 +++ .../java/org/onap/appc/generator/JsonHelper.java | 93 ++ .../yang2json/Yang2JsonGeneratorTest.java | 140 +++ ...TestAppcLifeCycleManagerServiceFactoryImpl.java | 60 - .../appc/client/lcm/model/TestModelPOJO.java | 144 --- .../org/openecomp/appc/generator/JsonHelper.java | 93 -- .../yang2json/Yang2JsonGeneratorTest.java | 140 --- .../impl/core/AbstractRequestResponseHandler.java | 85 ++ .../impl/core/AsyncRequestResponseHandler.java | 76 ++ .../onap/appc/client/impl/core/CoreException.java | 45 + .../onap/appc/client/impl/core/CoreManager.java | 314 +++++ .../onap/appc/client/impl/core/CoreRegistry.java | 70 ++ .../impl/core/ICoreAsyncResponseHandler.java | 43 + .../client/impl/core/ICoreResponseHandler.java | 28 + .../client/impl/core/ICoreSyncResponseHandler.java | 36 + .../appc/client/impl/core/IInvocationManager.java | 68 ++ .../appc/client/impl/core/ITimeoutHandler.java | 33 + .../onap/appc/client/impl/core/ITimerService.java | 47 + .../appc/client/impl/core/InvocationManager.java | 69 ++ .../client/impl/core/InvocationManagerFactory.java | 36 + .../onap/appc/client/impl/core/MessageContext.java | 85 ++ .../client/impl/core/RequestResponseHandler.java | 50 + .../impl/core/SyncRequestResponseHandler.java | 107 ++ .../org/onap/appc/client/impl/core/TaskQueue.java | 65 ++ .../appc/client/impl/core/TaskQueueManager.java | 98 ++ .../appc/client/impl/core/TimerServiceImpl.java | 82 ++ .../impl/protocol/APPCMessageReaderWriter.java | 77 ++ .../appc/client/impl/protocol/AsyncProtocol.java | 40 + .../client/impl/protocol/AsyncProtocolImpl.java | 157 +++ .../onap/appc/client/impl/protocol/Consumer.java | 56 + .../appc/client/impl/protocol/ConsumerImpl.java | 125 ++ .../appc/client/impl/protocol/MessageReader.java | 39 + .../appc/client/impl/protocol/MessageWriter.java | 40 + .../client/impl/protocol/MessagingService.java | 61 + .../onap/appc/client/impl/protocol/Producer.java | 38 + .../appc/client/impl/protocol/ProducerImpl.java | 82 ++ .../onap/appc/client/impl/protocol/Protocol.java | 38 + .../client/impl/protocol/ProtocolException.java | 44 + .../appc/client/impl/protocol/ProtocolFactory.java | 79 ++ .../appc/client/impl/protocol/ProtocolMessage.java | 98 ++ .../appc/client/impl/protocol/ProtocolType.java | 30 + .../impl/protocol/RetrieveMessageCallback.java | 38 + .../client/impl/protocol/UEBMessagingService.java | 102 ++ .../client/impl/protocol/UEBPropertiesKeys.java | 36 + .../impl/core/AbstractRequestResponseHandler.java | 85 -- .../impl/core/AsyncRequestResponseHandler.java | 76 -- .../appc/client/impl/core/CoreException.java | 45 - .../appc/client/impl/core/CoreManager.java | 314 ----- .../appc/client/impl/core/CoreRegistry.java | 70 -- .../impl/core/ICoreAsyncResponseHandler.java | 43 - .../client/impl/core/ICoreResponseHandler.java | 28 - .../client/impl/core/ICoreSyncResponseHandler.java | 36 - .../appc/client/impl/core/IInvocationManager.java | 68 -- .../appc/client/impl/core/ITimeoutHandler.java | 33 - .../appc/client/impl/core/ITimerService.java | 47 - .../appc/client/impl/core/InvocationManager.java | 69 -- .../client/impl/core/InvocationManagerFactory.java | 36 - .../appc/client/impl/core/MessageContext.java | 85 -- .../client/impl/core/RequestResponseHandler.java | 50 - .../impl/core/SyncRequestResponseHandler.java | 107 -- .../openecomp/appc/client/impl/core/TaskQueue.java | 65 -- .../appc/client/impl/core/TaskQueueManager.java | 98 -- .../appc/client/impl/core/TimerServiceImpl.java | 82 -- .../impl/protocol/APPCMessageReaderWriter.java | 77 -- .../appc/client/impl/protocol/AsyncProtocol.java | 40 - .../client/impl/protocol/AsyncProtocolImpl.java | 157 --- .../appc/client/impl/protocol/Consumer.java | 56 - .../appc/client/impl/protocol/ConsumerImpl.java | 125 -- .../appc/client/impl/protocol/MessageReader.java | 39 - .../appc/client/impl/protocol/MessageWriter.java | 40 - .../client/impl/protocol/MessagingService.java | 61 - .../appc/client/impl/protocol/Producer.java | 38 - .../appc/client/impl/protocol/ProducerImpl.java | 82 -- .../appc/client/impl/protocol/Protocol.java | 38 - .../client/impl/protocol/ProtocolException.java | 44 - .../appc/client/impl/protocol/ProtocolFactory.java | 79 -- .../appc/client/impl/protocol/ProtocolMessage.java | 98 -- .../appc/client/impl/protocol/ProtocolType.java | 30 - .../impl/protocol/RetrieveMessageCallback.java | 38 - .../client/impl/protocol/UEBMessagingService.java | 102 -- .../client/impl/protocol/UEBPropertiesKeys.java | 36 - .../appc/client/impl/core/ResponseManagerTest.java | 163 +++ .../onap/appc/client/impl/core/SyncFlowTest.java | 151 +++ .../impl/protocol/APPCMessageReaderWriterTest.java | 104 ++ .../impl/protocol/TestAsyncProtocolImpl.java | 91 ++ .../TestAsyncProtocolImplMissingProps.java | 75 ++ .../TestAsyncProtocolImplNullCallback.java | 60 + .../impl/protocol/TestUEBMessagingService.java | 70 ++ .../appc/client/impl/core/ResponseManagerTest.java | 163 --- .../appc/client/impl/core/SyncFlowTest.java | 151 --- .../impl/protocol/APPCMessageReaderWriterTest.java | 104 -- .../impl/protocol/TestAsyncProtocolImpl.java | 91 -- .../TestAsyncProtocolImplMissingProps.java | 75 -- .../TestAsyncProtocolImplNullCallback.java | 60 - .../impl/protocol/TestUEBMessagingService.java | 70 -- .../onap/appc/simulator/client/RequestHandler.java | 33 + .../appc/simulator/client/ResponseHandler.java | 31 + .../simulator/client/impl/JsonRequestHandler.java | 275 +++++ .../simulator/client/impl/JsonResponseHandler.java | 147 +++ .../appc/simulator/client/main/ClientRunner.java | 100 ++ .../appc/simulator/client/RequestHandler.java | 33 - .../appc/simulator/client/ResponseHandler.java | 31 - .../simulator/client/impl/JsonRequestHandler.java | 275 ----- .../simulator/client/impl/JsonResponseHandler.java | 147 --- .../appc/simulator/client/main/ClientRunner.java | 100 -- .../client/impl/TestJsonRequestHandler.java | 53 + .../client/impl/TestJsonResponseHandler.java | 46 + .../simulator/client/main/TestClientRunner.java | 102 ++ .../client/impl/TestJsonRequestHandler.java | 53 - .../client/impl/TestJsonResponseHandler.java | 46 - .../simulator/client/main/TestClientRunner.java | 102 -- .../org/onap/appc/tools/generator/api/CLI.java | 66 ++ .../appc/tools/generator/api/ContextBuilder.java | 34 + .../onap/appc/tools/generator/api/MavenPlugin.java | 85 ++ .../extensions/JsonContextBuilderImpl.java | 67 ++ .../extensions/YangContextBuilderImpl.java | 97 ++ .../appc/tools/generator/impl/CodeGenWriter.java | 107 ++ .../appc/tools/generator/impl/ModelGenerator.java | 71 ++ .../openecomp/appc/tools/generator/api/CLI.java | 66 -- .../appc/tools/generator/api/ContextBuilder.java | 34 - .../appc/tools/generator/api/MavenPlugin.java | 85 -- .../extensions/JsonContextBuilderImpl.java | 67 -- .../extensions/YangContextBuilderImpl.java | 97 -- .../appc/tools/generator/impl/CodeGenWriter.java | 107 -- .../appc/tools/generator/impl/ModelGenerator.java | 71 -- .../org/onap/appc/tools/generator/api/CLITest.java | 57 + .../tools/generator/impl/CodeGenWriterTest.java | 22 + .../appc/tools/generator/api/CLITest.java | 57 - .../tools/generator/impl/CodeGenWriterTest.java | 22 - .../src/main/java/org/onap/appc/CmdLine.java | 60 + .../src/main/java/org/onap/appc/Constants.java | 212 ++++ .../java/org/onap/appc/cache/CacheStrategies.java | 32 + .../java/org/onap/appc/cache/CacheStrategy.java | 46 + .../java/org/onap/appc/cache/MetadataCache.java | 46 + .../java/org/onap/appc/cache/impl/LRUCache.java | 59 + .../onap/appc/cache/impl/MetadataCacheFactory.java | 66 ++ .../onap/appc/cache/impl/MetadataCacheImpl.java | 69 ++ .../main/java/org/onap/appc/concurrent/Signal.java | 231 ++++ .../org/onap/appc/configuration/Configuration.java | 243 ++++ .../appc/configuration/ConfigurationFactory.java | 421 +++++++ .../appc/configuration/DefaultConfiguration.java | 557 +++++++++ .../java/org/onap/appc/configuration/package.html | 174 +++ .../onap/appc/encryption/EncryptionException.java | 38 + .../org/onap/appc/encryption/EncryptionTool.java | 215 ++++ .../java/org/onap/appc/encryption/HexHelper.java | 152 +++ .../org/onap/appc/exceptions/APPCException.java | 106 ++ .../appc/exceptions/InvalidInputException.java | 31 + .../appc/exceptions/InvalidStateException.java | 31 + .../appc/exceptions/UnknownProviderException.java | 108 ++ .../src/main/java/org/onap/appc/i18n/Msg.java | 824 +++++++++++++ .../org/onap/appc/logging/LoggingConstants.java | 110 ++ .../java/org/onap/appc/logging/LoggingUtils.java | 235 ++++ .../org/onap/appc/metadata/MetadataService.java | 32 + .../appc/metadata/impl/MetadataServiceImpl.java | 116 ++ .../objects/DependencyModelIdentifier.java | 98 ++ .../main/java/org/onap/appc/pool/Allocator.java | 48 + .../java/org/onap/appc/pool/CacheManagement.java | 35 + .../java/org/onap/appc/pool/CachedElement.java | 215 ++++ .../main/java/org/onap/appc/pool/Destructor.java | 47 + .../src/main/java/org/onap/appc/pool/Pool.java | 372 ++++++ .../org/onap/appc/pool/PoolDrainedException.java | 51 + .../java/org/onap/appc/pool/PoolException.java | 92 ++ .../org/onap/appc/pool/PoolExtensionException.java | 49 + .../onap/appc/pool/PoolSpecificationException.java | 50 + .../src/main/java/org/onap/appc/util/JsonUtil.java | 47 + .../java/org/onap/appc/util/MessageFormatter.java | 78 ++ .../main/java/org/onap/appc/util/ObjectMapper.java | 101 ++ .../main/java/org/onap/appc/util/PathContext.java | 103 ++ .../main/java/org/onap/appc/util/StringHelper.java | 595 ++++++++++ .../onap/appc/util/StructuredPropertyHelper.java | 260 +++++ .../src/main/java/org/onap/appc/util/Time.java | 611 ++++++++++ .../org/onap/appc/util/UnmodifiableProperties.java | 356 ++++++ .../main/java/org/onap/appc/util/httpClient.java | 210 ++++ .../src/main/java/org/openecomp/appc/CmdLine.java | 60 - .../main/java/org/openecomp/appc/Constants.java | 212 ---- .../org/openecomp/appc/cache/CacheStrategies.java | 32 - .../org/openecomp/appc/cache/CacheStrategy.java | 46 - .../org/openecomp/appc/cache/MetadataCache.java | 46 - .../org/openecomp/appc/cache/impl/LRUCache.java | 59 - .../appc/cache/impl/MetadataCacheFactory.java | 66 -- .../appc/cache/impl/MetadataCacheImpl.java | 69 -- .../java/org/openecomp/appc/concurrent/Signal.java | 231 ---- .../appc/configuration/Configuration.java | 243 ---- .../appc/configuration/ConfigurationFactory.java | 421 ------- .../appc/configuration/DefaultConfiguration.java | 557 --------- .../org/openecomp/appc/configuration/package.html | 174 --- .../appc/encryption/EncryptionException.java | 38 - .../openecomp/appc/encryption/EncryptionTool.java | 215 ---- .../org/openecomp/appc/encryption/HexHelper.java | 152 --- .../openecomp/appc/exceptions/APPCException.java | 106 -- .../appc/exceptions/InvalidInputException.java | 31 - .../appc/exceptions/InvalidStateException.java | 31 - .../appc/exceptions/UnknownProviderException.java | 108 -- .../src/main/java/org/openecomp/appc/i18n/Msg.java | 824 ------------- .../openecomp/appc/logging/LoggingConstants.java | 110 -- .../org/openecomp/appc/logging/LoggingUtils.java | 235 ---- .../openecomp/appc/metadata/MetadataService.java | 32 - .../appc/metadata/impl/MetadataServiceImpl.java | 116 -- .../objects/DependencyModelIdentifier.java | 98 -- .../java/org/openecomp/appc/pool/Allocator.java | 48 - .../org/openecomp/appc/pool/CacheManagement.java | 35 - .../org/openecomp/appc/pool/CachedElement.java | 215 ---- .../java/org/openecomp/appc/pool/Destructor.java | 47 - .../main/java/org/openecomp/appc/pool/Pool.java | 372 ------ .../openecomp/appc/pool/PoolDrainedException.java | 51 - .../org/openecomp/appc/pool/PoolException.java | 92 -- .../appc/pool/PoolExtensionException.java | 49 - .../appc/pool/PoolSpecificationException.java | 50 - .../java/org/openecomp/appc/util/JsonUtil.java | 47 - .../org/openecomp/appc/util/MessageFormatter.java | 78 -- .../java/org/openecomp/appc/util/ObjectMapper.java | 101 -- .../java/org/openecomp/appc/util/PathContext.java | 103 -- .../java/org/openecomp/appc/util/StringHelper.java | 595 ---------- .../appc/util/StructuredPropertyHelper.java | 260 ----- .../main/java/org/openecomp/appc/util/Time.java | 611 ---------- .../appc/util/UnmodifiableProperties.java | 356 ------ .../java/org/openecomp/appc/util/httpClient.java | 210 ---- .../org/onap/appc/i18n/MessageResources.properties | 1020 +++++++++++++++++ .../resources/org/onap/appc/i18n/auth.properties | 26 + .../org/onap/appc/org.ops4j.pax.logging.cfg | 149 +++ .../appc/i18n/MessageResources.properties | 1020 ----------------- .../org/openecomp/appc/i18n/auth.properties | 26 - .../org/openecomp/appc/org.ops4j.pax.logging.cfg | 149 --- .../org/onap/appc/cache/CacheStrategiesTest.java | 48 + .../org/onap/appc/cache/impl/LRUCacheTest.java | 61 + .../appc/cache/impl/MetadataCacheFactoryTest.java | 69 ++ .../appc/cache/impl/MetadataCacheImplTest.java | 64 ++ .../java/org/onap/appc/concurrent/TestSignal.java | 135 +++ .../configuration/DefaultConfigurationTest.java | 337 ++++++ .../org/onap/appc/encryption/TestEncryption.java | 46 + .../onap/appc/exceptions/APPCExceptionTest.java | 89 ++ .../appc/exceptions/InvalidInputExceptionTest.java | 39 + .../appc/exceptions/InvalidStateExceptionTest.java | 39 + .../exceptions/UnknownProviderExceptionTest.java | 93 ++ .../src/test/java/org/onap/appc/i18n/MsgTest.java | 771 +++++++++++++ .../onap/appc/logging/LoggingConstantsTest.java | 60 + .../onap/appc/metadata/TestMetadataService.java | 54 + .../objects/DependencyModelIdentifierTest.java | 105 ++ .../java/org/onap/appc/pool/CachedElementTest.java | 276 +++++ .../src/test/java/org/onap/appc/pool/Element.java | 78 ++ .../src/test/java/org/onap/appc/pool/PoolTest.java | 323 ++++++ .../src/test/java/org/onap/appc/pool/Testable.java | 35 + .../test/java/org/onap/appc/util/TestJsonUtil.java | 74 ++ .../java/org/onap/appc/util/TestStringHelper.java | 107 ++ .../appc/util/TestStructuredPropertyHelper.java | 236 ++++ .../openecomp/appc/cache/CacheStrategiesTest.java | 48 - .../openecomp/appc/cache/impl/LRUCacheTest.java | 61 - .../appc/cache/impl/MetadataCacheFactoryTest.java | 69 -- .../appc/cache/impl/MetadataCacheImplTest.java | 64 -- .../org/openecomp/appc/concurrent/TestSignal.java | 135 --- .../configuration/DefaultConfigurationTest.java | 337 ------ .../openecomp/appc/encryption/TestEncryption.java | 46 - .../appc/exceptions/APPCExceptionTest.java | 89 -- .../appc/exceptions/InvalidInputExceptionTest.java | 39 - .../appc/exceptions/InvalidStateExceptionTest.java | 39 - .../exceptions/UnknownProviderExceptionTest.java | 93 -- .../test/java/org/openecomp/appc/i18n/MsgTest.java | 771 ------------- .../appc/logging/LoggingConstantsTest.java | 60 - .../appc/metadata/TestMetadataService.java | 54 - .../objects/DependencyModelIdentifierTest.java | 105 -- .../org/openecomp/appc/pool/CachedElementTest.java | 276 ----- .../test/java/org/openecomp/appc/pool/Element.java | 78 -- .../java/org/openecomp/appc/pool/PoolTest.java | 323 ------ .../java/org/openecomp/appc/pool/Testable.java | 35 - .../java/org/openecomp/appc/util/TestJsonUtil.java | 74 -- .../org/openecomp/appc/util/TestStringHelper.java | 107 -- .../appc/util/TestStructuredPropertyHelper.java | 236 ---- .../appc/i18n/TestAdditionalResources.properties | 25 + .../org/onap/appc/i18n/TestResources_de.properties | 30 + .../onap/appc/i18n/TestResources_en_US.properties | 29 + .../appc/i18n/TestAdditionalResources.properties | 25 - .../appc/i18n/TestResources_de.properties | 30 - .../appc/i18n/TestResources_en_US.properties | 29 - .../org/onap/appc/dg/util/AppcDgUtilActivator.java | 58 + .../org/onap/appc/dg/util/ExecuteNodeAction.java | 43 + .../appc/dg/util/InputParameterValidation.java | 42 + .../org/onap/appc/dg/util/UpgradeStubNode.java | 36 + .../appc/dg/util/impl/ExecuteNodeActionImpl.java | 362 ++++++ .../dg/util/impl/InputParameterValidationImpl.java | 136 +++ .../appc/dg/util/impl/UpgradeStubNodeImpl.java | 50 + .../appc/dg/util/AppcDgUtilActivator.java | 58 - .../openecomp/appc/dg/util/ExecuteNodeAction.java | 43 - .../appc/dg/util/InputParameterValidation.java | 42 - .../openecomp/appc/dg/util/UpgradeStubNode.java | 36 - .../appc/dg/util/impl/ExecuteNodeActionImpl.java | 362 ------ .../dg/util/impl/InputParameterValidationImpl.java | 136 --- .../appc/dg/util/impl/UpgradeStubNodeImpl.java | 50 - .../resources/org/onap/appc/default.properties | 29 + .../org/openecomp/appc/default.properties | 29 - .../onap/appc/dg/util/AppcDgUtilActivatorTest.java | 59 + .../dg/util/impl/ExecuteNodeActionImplTest.java | 235 ++++ .../impl/InputParameterValidationImplTest.java | 165 +++ .../appc/dg/util/impl/UpgradeStubNodeImplTest.java | 63 + .../appc/dg/util/AppcDgUtilActivatorTest.java | 59 - .../dg/util/impl/ExecuteNodeActionImplTest.java | 235 ---- .../impl/InputParameterValidationImplTest.java | 165 --- .../appc/dg/util/impl/UpgradeStubNodeImplTest.java | 63 - .../main/java/org/onap/appc/dg/aai/AAIPlugin.java | 46 + .../appc/dg/aai/exception/AAIQueryException.java | 32 + .../org/onap/appc/dg/aai/impl/AAIPluginImpl.java | 401 +++++++ .../java/org/onap/appc/dg/aai/impl/Constants.java | 120 ++ .../onap/appc/dg/aai/objects/AAIQueryResult.java | 52 + .../org/onap/appc/dg/aai/objects/Relationship.java | 69 ++ .../java/org/openecomp/appc/dg/aai/AAIPlugin.java | 46 - .../appc/dg/aai/exception/AAIQueryException.java | 32 - .../openecomp/appc/dg/aai/impl/AAIPluginImpl.java | 401 ------- .../org/openecomp/appc/dg/aai/impl/Constants.java | 120 -- .../appc/dg/aai/objects/AAIQueryResult.java | 52 - .../appc/dg/aai/objects/Relationship.java | 69 -- .../org/onap/appc/dg/aai/impl/AAIClientMock.java | 547 +++++++++ .../onap/appc/dg/aai/impl/AAIPluginImplTest.java | 259 +++++ .../openecomp/appc/dg/aai/impl/AAIClientMock.java | 547 --------- .../appc/dg/aai/impl/AAIPluginImplTest.java | 259 ----- .../onap/appc/dg/common/DCAEReporterPlugin.java | 37 + .../org/onap/appc/dg/common/DgResolverPlugin.java | 35 + .../appc/dg/common/IntermediateMessageSender.java | 51 + .../java/org/onap/appc/dg/common/JsonDgUtil.java | 54 + .../java/org/onap/appc/dg/common/LegacyUtil.java | 43 + .../onap/appc/dg/common/OutputMessagePlugin.java | 38 + .../onap/appc/dg/common/VNFCDgResolverPlugin.java | 37 + .../org/onap/appc/dg/common/VNFConfigurator.java | 46 + .../org/onap/appc/dg/common/VnfExecutionFlow.java | 34 + .../onap/appc/dg/common/impl/AbstractResolver.java | 117 ++ .../dg/common/impl/AbstractResolverDataReader.java | 130 +++ .../org/onap/appc/dg/common/impl/Constants.java | 99 ++ .../dg/common/impl/DCAEReporterPluginImpl.java | 168 +++ .../appc/dg/common/impl/DgResolverPluginImpl.java | 71 ++ .../java/org/onap/appc/dg/common/impl/FlowKey.java | 62 + .../common/impl/IntermediateMessageSenderImpl.java | 172 +++ .../onap/appc/dg/common/impl/JsonDgUtilImpl.java | 199 ++++ .../onap/appc/dg/common/impl/LegacyUtilImpl.java | 60 + .../dg/common/impl/OutputMessagePluginImpl.java | 73 ++ .../dg/common/impl/ResolverDataReaderFactory.java | 47 + .../onap/appc/dg/common/impl/ResolverFactory.java | 46 + .../dg/common/impl/VNFCDgResolverPluginImpl.java | 39 + .../org/onap/appc/dg/common/impl/VNFCResolver.java | 67 ++ .../dg/common/impl/VNFCResolverDataReader.java | 40 + .../appc/dg/common/impl/VNFConfiguratorImpl.java | 115 ++ .../org/onap/appc/dg/common/impl/VNFResolver.java | 63 + .../appc/dg/common/impl/VNFResolverDataReader.java | 43 + .../appc/dg/common/impl/VnfExecutionFlowImpl.java | 271 +++++ .../appc/dg/common/objects/ConnectionDetails.java | 68 ++ .../org/onap/appc/dg/common/utils/JAXBUtil.java | 53 + .../org/onap/appc/dg/common/utils/JSONUtil.java | 83 ++ .../appc/dg/common/DCAEReporterPlugin.java | 37 - .../openecomp/appc/dg/common/DgResolverPlugin.java | 35 - .../appc/dg/common/IntermediateMessageSender.java | 51 - .../org/openecomp/appc/dg/common/JsonDgUtil.java | 54 - .../org/openecomp/appc/dg/common/LegacyUtil.java | 43 - .../appc/dg/common/OutputMessagePlugin.java | 38 - .../appc/dg/common/VNFCDgResolverPlugin.java | 37 - .../openecomp/appc/dg/common/VNFConfigurator.java | 46 - .../openecomp/appc/dg/common/VnfExecutionFlow.java | 34 - .../appc/dg/common/impl/AbstractResolver.java | 117 -- .../dg/common/impl/AbstractResolverDataReader.java | 130 --- .../openecomp/appc/dg/common/impl/Constants.java | 99 -- .../dg/common/impl/DCAEReporterPluginImpl.java | 168 --- .../appc/dg/common/impl/DgResolverPluginImpl.java | 71 -- .../org/openecomp/appc/dg/common/impl/FlowKey.java | 62 - .../common/impl/IntermediateMessageSenderImpl.java | 172 --- .../appc/dg/common/impl/JsonDgUtilImpl.java | 199 ---- .../appc/dg/common/impl/LegacyUtilImpl.java | 60 - .../dg/common/impl/OutputMessagePluginImpl.java | 73 -- .../dg/common/impl/ResolverDataReaderFactory.java | 47 - .../appc/dg/common/impl/ResolverFactory.java | 46 - .../dg/common/impl/VNFCDgResolverPluginImpl.java | 39 - .../appc/dg/common/impl/VNFCResolver.java | 67 -- .../dg/common/impl/VNFCResolverDataReader.java | 40 - .../appc/dg/common/impl/VNFConfiguratorImpl.java | 115 -- .../openecomp/appc/dg/common/impl/VNFResolver.java | 63 - .../appc/dg/common/impl/VNFResolverDataReader.java | 43 - .../appc/dg/common/impl/VnfExecutionFlowImpl.java | 271 ----- .../appc/dg/common/objects/ConnectionDetails.java | 68 -- .../openecomp/appc/dg/common/utils/JAXBUtil.java | 53 - .../openecomp/appc/dg/common/utils/JSONUtil.java | 83 -- .../resources/org/onap/appc/default.properties | 50 + .../org/openecomp/appc/default.properties | 50 - .../dg/common/impl/DCAEReporterPluginImplTest.java | 119 ++ .../onap/appc/dg/common/impl/EventSenderMock.java | 69 ++ .../appc/dg/common/impl/JsonDgUtilImplTest.java | 172 +++ .../dg/common/impl/TestVNFConfiguratorImpl.java | 108 ++ .../dg/common/impl/TestVnfExecutionFlowImpl.java | 420 +++++++ .../dg/common/impl/DCAEReporterPluginImplTest.java | 119 -- .../appc/dg/common/impl/EventSenderMock.java | 69 -- .../appc/dg/common/impl/JsonDgUtilImplTest.java | 172 --- .../dg/common/impl/TestVNFConfiguratorImpl.java | 108 -- .../dg/common/impl/TestVnfExecutionFlowImpl.java | 420 ------- .../dg/dependencymanager/DependencyManager.java | 36 + .../appc/dg/dependencymanager/DependencyType.java | 35 + .../exception/DependencyModelNotFound.java | 32 + .../helper/DependencyModelParser.java | 193 ++++ .../impl/DependencyManagerImpl.java | 74 ++ .../impl/DependencyModelFactory.java | 40 + .../dependencymanager/impl/ResourceDependency.java | 86 ++ .../org/onap/appc/dg/flowbuilder/FlowBuilder.java | 34 + .../org/onap/appc/dg/flowbuilder/FlowStrategy.java | 35 + .../exception/InvalidDependencyModel.java | 32 + .../org/onap/appc/dg/flowbuilder/helper/Graph.java | 67 ++ .../dg/flowbuilder/impl/AbstractFlowStrategy.java | 136 +++ .../dg/flowbuilder/impl/FlowBuilderFactory.java | 51 + .../appc/dg/flowbuilder/impl/FlowBuilderImpl.java | 52 + .../dg/flowbuilder/impl/ForwardFlowStrategy.java | 117 ++ .../dg/flowbuilder/impl/ReverseFlowStrategy.java | 118 ++ .../org/onap/appc/dg/objects/DependencyTypes.java | 39 + .../org/onap/appc/dg/objects/FlowStrategies.java | 39 + .../org/onap/appc/dg/objects/InventoryModel.java | 46 + .../main/java/org/onap/appc/dg/objects/Node.java | 77 ++ .../onap/appc/dg/objects/VnfcDependencyModel.java | 51 + .../org/onap/appc/dg/objects/VnfcFlowModel.java | 92 ++ .../dg/dependencymanager/DependencyManager.java | 36 - .../appc/dg/dependencymanager/DependencyType.java | 35 - .../exception/DependencyModelNotFound.java | 32 - .../helper/DependencyModelParser.java | 193 ---- .../impl/DependencyManagerImpl.java | 74 -- .../impl/DependencyModelFactory.java | 40 - .../dependencymanager/impl/ResourceDependency.java | 86 -- .../openecomp/appc/dg/flowbuilder/FlowBuilder.java | 34 - .../appc/dg/flowbuilder/FlowStrategy.java | 35 - .../exception/InvalidDependencyModel.java | 32 - .../appc/dg/flowbuilder/helper/Graph.java | 67 -- .../dg/flowbuilder/impl/AbstractFlowStrategy.java | 136 --- .../dg/flowbuilder/impl/FlowBuilderFactory.java | 51 - .../appc/dg/flowbuilder/impl/FlowBuilderImpl.java | 52 - .../dg/flowbuilder/impl/ForwardFlowStrategy.java | 117 -- .../dg/flowbuilder/impl/ReverseFlowStrategy.java | 118 -- .../openecomp/appc/dg/objects/DependencyTypes.java | 39 - .../openecomp/appc/dg/objects/FlowStrategies.java | 39 - .../openecomp/appc/dg/objects/InventoryModel.java | 46 - .../java/org/openecomp/appc/dg/objects/Node.java | 77 -- .../appc/dg/objects/VnfcDependencyModel.java | 51 - .../openecomp/appc/dg/objects/VnfcFlowModel.java | 92 -- .../onap/appc/dg/flowbuilder/TestFlowBuilder.java | 332 ++++++ .../appc/dg/flowbuilder/TestFlowBuilder.java | 332 ------ .../main/java/org/onap/appc/domainmodel/Vnf.java | 72 ++ .../main/java/org/onap/appc/domainmodel/Vnfc.java | 148 +++ .../java/org/onap/appc/domainmodel/Vserver.java | 78 ++ .../java/org/openecomp/appc/domainmodel/Vnf.java | 72 -- .../java/org/openecomp/appc/domainmodel/Vnfc.java | 148 --- .../org/openecomp/appc/domainmodel/Vserver.java | 78 -- .../onap/appc/dg/licmgr/LicenseManagerPlugin.java | 55 + .../dg/licmgr/impl/LicenseManagerPluginImpl.java | 148 +++ .../appc/dg/licmgr/LicenseManagerPlugin.java | 55 - .../dg/licmgr/impl/LicenseManagerPluginImpl.java | 148 --- .../main/java/org/onap/appc/mdsal/MDSALStore.java | 65 ++ .../appc/mdsal/exception/MDSALStoreException.java | 72 ++ .../java/org/onap/appc/mdsal/impl/Constants.java | 125 ++ .../onap/appc/mdsal/impl/MDSALStoreFactory.java | 50 + .../org/onap/appc/mdsal/impl/MDSALStoreImpl.java | 154 +++ .../org/onap/appc/mdsal/objects/BundleInfo.java | 74 ++ .../onap/appc/mdsal/operation/ConfigOperation.java | 295 +++++ .../mdsal/operation/ConfigOperation.java~ccmerge | 295 +++++ .../operation/ConfigOperationRequestFormatter.java | 53 + .../java/org/openecomp/appc/mdsal/MDSALStore.java | 65 -- .../appc/mdsal/exception/MDSALStoreException.java | 72 -- .../org/openecomp/appc/mdsal/impl/Constants.java | 125 -- .../appc/mdsal/impl/MDSALStoreFactory.java | 50 - .../openecomp/appc/mdsal/impl/MDSALStoreImpl.java | 154 --- .../openecomp/appc/mdsal/objects/BundleInfo.java | 74 -- .../appc/mdsal/operation/ConfigOperation.java | 295 ----- .../mdsal/operation/ConfigOperation.java~ccmerge | 295 ----- .../operation/ConfigOperationRequestFormatter.java | 53 - .../onap/appc/dg/netconf/NetconfClientPlugin.java | 41 + .../org/onap/appc/dg/netconf/NetconfDBPlugin.java | 40 + .../dg/netconf/impl/NetconfClientPluginImpl.java | 314 +++++ .../appc/dg/netconf/impl/NetconfDBPluginImpl.java | 123 ++ .../appc/dg/netconf/NetconfClientPlugin.java | 41 - .../openecomp/appc/dg/netconf/NetconfDBPlugin.java | 40 - .../dg/netconf/impl/NetconfClientPluginImpl.java | 314 ----- .../appc/dg/netconf/impl/NetconfDBPluginImpl.java | 123 -- .../onap/appc/dg/netconf/impl/DAOServiceMock.java | 100 ++ .../impl/MockOperationalStateValidatorImpl.java | 64 ++ .../dg/netconf/impl/NetconfClientFactoryMock.java | 46 + .../dg/netconf/impl/NetconfClientJschMock.java | 103 ++ .../netconf/impl/NetconfClientPluginImplTest.java | 681 +++++++++++ .../dg/netconf/impl/NetconfDBPluginImplTest.java | 253 ++++ .../appc/dg/netconf/impl/ObjectMapperMock.java | 48 + .../impl/OperationStateValidatorFactoryMock.java | 50 + .../appc/dg/netconf/impl/DAOServiceMock.java | 100 -- .../impl/MockOperationalStateValidatorImpl.java | 64 -- .../dg/netconf/impl/NetconfClientFactoryMock.java | 46 - .../dg/netconf/impl/NetconfClientJschMock.java | 103 -- .../netconf/impl/NetconfClientPluginImplTest.java | 681 ----------- .../dg/netconf/impl/NetconfDBPluginImplTest.java | 253 ---- .../appc/dg/netconf/impl/ObjectMapperMock.java | 48 - .../impl/OperationStateValidatorFactoryMock.java | 50 - .../java/org/onap/appc/dg/ssh/SshDBPlugin.java | 35 + .../main/java/org/onap/appc/dg/ssh/SshService.java | 102 ++ .../org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java | 85 ++ .../org/onap/appc/dg/ssh/impl/SshServiceImpl.java | 109 ++ .../org/openecomp/appc/dg/ssh/SshDBPlugin.java | 35 - .../java/org/openecomp/appc/dg/ssh/SshService.java | 102 -- .../appc/dg/ssh/impl/SshDBPluginImpl.java | 85 -- .../openecomp/appc/dg/ssh/impl/SshServiceImpl.java | 109 -- .../onap/appc/dg/ssh/impl/SshServiceImplTest.java | 173 +++ .../appc/dg/ssh/impl/SshServiceImplTest.java | 173 --- .../org/onap/appc/dg/TestCheckConfigStatus.java | 217 ++++ .../java/org/onap/appc/dg/TestCommonConfig.java | 230 ++++ .../appc/dg/TestConfigurationDocumentRequest.java | 69 ++ .../test/java/org/onap/appc/dg/TestConfigure.java | 285 +++++ .../org/onap/appc/dg/TestDownloadCliConfig.java | 133 +++ .../org/onap/appc/dg/TestDownloadIsbcConfig.java | 152 +++ .../java/org/onap/appc/dg/TestGenerateConfig.java | 133 +++ .../onap/appc/dg/TestGenerateTemplateConfig.java | 112 ++ .../test/java/org/onap/appc/dg/TestGetAaiInfo.java | 146 +++ .../java/org/onap/appc/dg/TestGetConfigParams.java | 277 +++++ .../onap/appc/dg/TestGetDeviceRunningConfig.java | 131 +++ .../java/org/onap/appc/dg/TestGetVfModuleInfo.java | 123 ++ .../appc/dg/TestProcessParameterDefinition.java | 254 ++++ .../org/onap/appc/dg/TestPublishConfiguration.java | 51 + .../org/onap/appc/dg/TestSaveRunningConfig.java | 152 +++ .../test/java/org/onap/appc/dg/TestSetStatus.java | 154 +++ .../java/org/onap/appc/dg/TestUpdateAaiInfo.java | 166 +++ .../appc/dg/mock/instance/MockAaiResource.java | 188 +++ .../mock/instance/MockConfigureNodeExecutor.java | 71 ++ .../dg/mock/instance/MockSvcLogicJavaPlugin.java | 106 ++ .../openecomp/appc/dg/TestCheckConfigStatus.java | 217 ---- .../org/openecomp/appc/dg/TestCommonConfig.java | 230 ---- .../appc/dg/TestConfigurationDocumentRequest.java | 69 -- .../java/org/openecomp/appc/dg/TestConfigure.java | 285 ----- .../openecomp/appc/dg/TestDownloadCliConfig.java | 133 --- .../openecomp/appc/dg/TestDownloadIsbcConfig.java | 152 --- .../org/openecomp/appc/dg/TestGenerateConfig.java | 133 --- .../appc/dg/TestGenerateTemplateConfig.java | 112 -- .../java/org/openecomp/appc/dg/TestGetAaiInfo.java | 146 --- .../org/openecomp/appc/dg/TestGetConfigParams.java | 277 ----- .../appc/dg/TestGetDeviceRunningConfig.java | 131 --- .../org/openecomp/appc/dg/TestGetVfModuleInfo.java | 123 -- .../appc/dg/TestProcessParameterDefinition.java | 254 ---- .../appc/dg/TestPublishConfiguration.java | 51 - .../openecomp/appc/dg/TestSaveRunningConfig.java | 152 --- .../java/org/openecomp/appc/dg/TestSetStatus.java | 154 --- .../org/openecomp/appc/dg/TestUpdateAaiInfo.java | 166 --- .../appc/dg/mock/instance/MockAaiResource.java | 188 --- .../mock/instance/MockConfigureNodeExecutor.java | 71 -- .../dg/mock/instance/MockSvcLogicJavaPlugin.java | 106 -- .../org/onap/sdnc/dg/loader/DGLoaderActivator.java | 58 + .../org/onap/sdnc/dg/loader/DGXMLActivate.java | 133 +++ .../org/onap/sdnc/dg/loader/DGXMLGenerator.java | 128 +++ .../java/org/onap/sdnc/dg/loader/DGXMLLoad.java | 115 ++ .../onap/sdnc/dg/loader/DGXMLLoadNActivate.java | 175 +++ .../sdnc/dg/loader/DGLoaderActivator.java | 58 - .../openecomp/sdnc/dg/loader/DGXMLActivate.java | 133 --- .../openecomp/sdnc/dg/loader/DGXMLGenerator.java | 128 --- .../org/openecomp/sdnc/dg/loader/DGXMLLoad.java | 115 -- .../sdnc/dg/loader/DGXMLLoadNActivate.java | 175 --- .../java/org/onap/sdnc/dg/loader/DGLoaderTest.java | 188 +++ .../org/onap/sdnc/dg/loader/MockDGXMLActivate.java | 35 + .../org/onap/sdnc/dg/loader/MockDGXMLLoad.java | 37 + .../sdnc/dg/loader/MockDGXMLLoadNActivate.java | 34 + .../sdnc/dg/loader/MockSvcLogicDblibStore.java | 86 ++ .../onap/sdnc/dg/loader/MockSvcLogicFactory.java | 36 + .../org/openecomp/sdnc/dg/loader/DGLoaderTest.java | 188 --- .../sdnc/dg/loader/MockDGXMLActivate.java | 35 - .../openecomp/sdnc/dg/loader/MockDGXMLLoad.java | 37 - .../sdnc/dg/loader/MockDGXMLLoadNActivate.java | 34 - .../sdnc/dg/loader/MockSvcLogicDblibStore.java | 86 -- .../sdnc/dg/loader/MockSvcLogicFactory.java | 36 - .../org/onap/appc/executor/CommandExecutor.java | 44 + .../onap/appc/executor/UnstableVNFException.java | 32 + .../org/onap/appc/executor/conv/Converter.java | 52 + .../appc/executor/objects/CommandResponse.java | 42 + .../appc/executor/objects/LCMCommandStatus.java | 121 ++ .../org/onap/appc/executor/objects/Params.java | 60 + .../executor/objects/UniqueRequestIdentifier.java | 126 ++ .../openecomp/appc/executor/CommandExecutor.java | 44 - .../appc/executor/UnstableVNFException.java | 32 - .../openecomp/appc/executor/conv/Converter.java | 52 - .../appc/executor/objects/CommandResponse.java | 42 - .../appc/executor/objects/LCMCommandStatus.java | 121 -- .../openecomp/appc/executor/objects/Params.java | 60 - .../executor/objects/UniqueRequestIdentifier.java | 126 -- .../appc/executor/impl/CommandExecutorImpl.java | 149 +++ .../org/onap/appc/executor/impl/CommandTask.java | 85 ++ .../appc/executor/impl/CommandTaskFactory.java | 90 ++ .../org/onap/appc/executor/impl/CommonMethods.java | 75 ++ .../appc/executor/impl/ExpiredMessageHandler.java | 63 + .../onap/appc/executor/impl/LCMCommandTask.java | 294 +++++ .../appc/executor/impl/LCMReadonlyCommandTask.java | 78 ++ .../appc/executor/impl/CommandExecutorImpl.java | 149 --- .../openecomp/appc/executor/impl/CommandTask.java | 85 -- .../appc/executor/impl/CommandTaskFactory.java | 90 -- .../appc/executor/impl/CommonMethods.java | 75 -- .../appc/executor/impl/ExpiredMessageHandler.java | 63 - .../appc/executor/impl/LCMCommandTask.java | 294 ----- .../appc/executor/impl/LCMReadonlyCommandTask.java | 78 -- .../resources/org/onap/appc/default.properties | 38 + .../org/openecomp/appc/default.properties | 38 - .../appc/executor/CommandExecutionTaskTest.java | 295 +++++ .../onap/appc/executor/TestCommandExecutor.java | 167 +++ .../appc/executor/CommandExecutionTaskTest.java | 295 ----- .../appc/executor/TestCommandExecutor.java | 167 --- .../resources/org/onap/appc/default.properties | 91 ++ .../org/openecomp/appc/default.properties | 91 -- .../appc/dao/util/AppcJdbcConnectionFactory.java | 53 + .../main/java/org/onap/appc/dao/util/DBUtils.java | 69 ++ .../dao/util/DefaultJdbcConnectionFactory.java | 75 ++ .../onap/appc/dao/util/JdbcConnectionFactory.java | 33 + .../onap/appc/dao/util/JdbcRuntimeException.java | 36 + .../main/java/org/onap/appc/dao/util/Messages.java | 46 + .../appc/dao/util/AppcJdbcConnectionFactory.java | 53 - .../java/org/openecomp/appc/dao/util/DBUtils.java | 69 -- .../dao/util/DefaultJdbcConnectionFactory.java | 75 -- .../appc/dao/util/JdbcConnectionFactory.java | 33 - .../appc/dao/util/JdbcRuntimeException.java | 36 - .../java/org/openecomp/appc/dao/util/Messages.java | 46 - .../appc/domainmodel/lcm/ActionIdentifiers.java | 85 ++ .../org/onap/appc/domainmodel/lcm/ActionLevel.java | 29 + .../onap/appc/domainmodel/lcm/CommonHeader.java | 98 ++ .../java/org/onap/appc/domainmodel/lcm/Flags.java | 66 ++ .../onap/appc/domainmodel/lcm/OperationType.java | 29 + .../onap/appc/domainmodel/lcm/RequestContext.java | 106 ++ .../onap/appc/domainmodel/lcm/ResponseContext.java | 86 ++ .../onap/appc/domainmodel/lcm/RuntimeContext.java | 101 ++ .../java/org/onap/appc/domainmodel/lcm/Status.java | 53 + .../org/onap/appc/domainmodel/lcm/VNFContext.java | 76 ++ .../onap/appc/domainmodel/lcm/VNFOperation.java | 63 + .../appc/domainmodel/lcm/ActionIdentifiers.java | 85 -- .../appc/domainmodel/lcm/ActionLevel.java | 29 - .../appc/domainmodel/lcm/CommonHeader.java | 98 -- .../org/openecomp/appc/domainmodel/lcm/Flags.java | 66 -- .../appc/domainmodel/lcm/OperationType.java | 29 - .../appc/domainmodel/lcm/RequestContext.java | 106 -- .../appc/domainmodel/lcm/ResponseContext.java | 86 -- .../appc/domainmodel/lcm/RuntimeContext.java | 101 -- .../org/openecomp/appc/domainmodel/lcm/Status.java | 53 - .../openecomp/appc/domainmodel/lcm/VNFContext.java | 76 -- .../appc/domainmodel/lcm/VNFOperation.java | 63 - .../appc/executionqueue/ExecutionQueueService.java | 35 + .../executionqueue/MessageExpirationListener.java | 29 + .../org/onap/appc/executionqueue/helper/Util.java | 101 ++ .../impl/ExecutionQueueServiceFactory.java | 38 + .../impl/ExecutionQueueServiceImpl.java | 88 ++ .../appc/executionqueue/impl/QueueManager.java | 127 ++ .../executionqueue/impl/object/QueueMessage.java | 46 + .../appc/executionqueue/ExecutionQueueService.java | 35 - .../executionqueue/MessageExpirationListener.java | 29 - .../openecomp/appc/executionqueue/helper/Util.java | 101 -- .../impl/ExecutionQueueServiceFactory.java | 38 - .../impl/ExecutionQueueServiceImpl.java | 88 -- .../appc/executionqueue/impl/QueueManager.java | 127 -- .../executionqueue/impl/object/QueueMessage.java | 46 - .../executionqueue/ExecutionQueueServiceTest.java | 68 ++ .../org/onap/appc/executionqueue/Listener.java | 42 + .../java/org/onap/appc/executionqueue/Message.java | 45 + .../executionqueue/ExecutionQueueServiceTest.java | 68 -- .../openecomp/appc/executionqueue/Listener.java | 42 - .../org/openecomp/appc/executionqueue/Message.java | 45 - .../onap/appc/lockmanager/api/LockException.java | 37 + .../org/onap/appc/lockmanager/api/LockManager.java | 72 ++ .../appc/lockmanager/api/LockRuntimeException.java | 36 + .../appc/lockmanager/api/LockException.java | 37 - .../appc/lockmanager/api/LockManager.java | 72 -- .../appc/lockmanager/api/LockRuntimeException.java | 36 - .../impl/inmemory/LockManagerInMemoryImpl.java | 133 +++ .../appc/lockmanager/impl/inmemory/LockValue.java | 46 + .../appc/lockmanager/impl/sql/JdbcLockManager.java | 54 + .../onap/appc/lockmanager/impl/sql/Messages.java | 51 + .../impl/sql/MySqlConnectionFactory.java | 37 + .../impl/sql/optimistic/LockRecord.java | 74 ++ .../impl/sql/optimistic/MySqlLockManager.java | 35 + .../impl/sql/optimistic/SqlLockManager.java | 266 +++++ .../impl/sql/pessimistic/LockRecord.java | 65 ++ .../impl/sql/pessimistic/MySqlLockManager.java | 88 ++ .../impl/sql/pessimistic/SqlLockManager.java | 254 ++++ .../impl/inmemory/LockManagerInMemoryImpl.java | 133 --- .../appc/lockmanager/impl/inmemory/LockValue.java | 46 - .../appc/lockmanager/impl/sql/JdbcLockManager.java | 54 - .../appc/lockmanager/impl/sql/Messages.java | 51 - .../impl/sql/MySqlConnectionFactory.java | 37 - .../impl/sql/optimistic/LockRecord.java | 74 -- .../impl/sql/optimistic/MySqlLockManager.java | 35 - .../impl/sql/optimistic/SqlLockManager.java | 266 ----- .../impl/sql/pessimistic/LockRecord.java | 65 -- .../impl/sql/pessimistic/MySqlLockManager.java | 88 -- .../impl/sql/pessimistic/SqlLockManager.java | 254 ---- .../appc/lockmanager/api/LockManagerBaseTests.java | 170 +++ .../impl/inmemory/LockManagerInMemoryImplTest.java | 39 + .../impl/sql/MySqlLockManagerBaseTests.java | 96 ++ .../appc/lockmanager/impl/sql/Synchronizer.java | 83 ++ .../lockmanager/impl/sql/SynchronizerReceiver.java | 30 + .../impl/sql/optimistic/MySqlLockManagerMock.java | 135 +++ .../impl/sql/optimistic/TestMySqlLockManager.java | 230 ++++ .../impl/sql/pessimistic/MySqlLockManagerMock.java | 153 +++ .../impl/sql/pessimistic/TestMySqlLockManager.java | 124 ++ .../appc/lockmanager/api/LockManagerBaseTests.java | 170 --- .../impl/inmemory/LockManagerInMemoryImplTest.java | 39 - .../impl/sql/MySqlLockManagerBaseTests.java | 96 -- .../appc/lockmanager/impl/sql/Synchronizer.java | 83 -- .../lockmanager/impl/sql/SynchronizerReceiver.java | 30 - .../impl/sql/optimistic/MySqlLockManagerMock.java | 135 --- .../impl/sql/optimistic/TestMySqlLockManager.java | 230 ---- .../impl/sql/pessimistic/MySqlLockManagerMock.java | 153 --- .../impl/sql/pessimistic/TestMySqlLockManager.java | 124 -- .../AbstractRankedAttributesResolverFactory.java | 38 + .../appc/rankingframework/ConfigurationEntry.java | 30 + .../appc/rankingframework/ConfigurationSet.java | 33 + .../rankingframework/RankedAttributesContext.java | 29 + .../rankingframework/RankedAttributesResolver.java | 29 + .../RankedAttributesResolverFactory.java | 29 + .../rankingframework/impl/BacktraceStrategy.java | 122 ++ .../appc/rankingframework/impl/CompositeNode.java | 41 + .../onap/appc/rankingframework/impl/Constants.java | 33 + .../impl/DefaultRankedAttributesTreeFactory.java | 52 + .../onap/appc/rankingframework/impl/LeafNode.java | 48 + .../org/onap/appc/rankingframework/impl/Node.java | 43 + .../onap/appc/rankingframework/impl/NodeBase.java | 90 ++ .../impl/RankedAttributesTree.java | 48 + .../impl/RankedAttributesTreeBuilder.java | 103 ++ .../onap/appc/rankingframework/impl/Strategy.java | 33 + .../org/onap/appc/rankingframework/impl/Utils.java | 43 + .../AbstractRankedAttributesResolverFactory.java | 38 - .../appc/rankingframework/ConfigurationEntry.java | 30 - .../appc/rankingframework/ConfigurationSet.java | 33 - .../rankingframework/RankedAttributesContext.java | 29 - .../rankingframework/RankedAttributesResolver.java | 29 - .../RankedAttributesResolverFactory.java | 29 - .../rankingframework/impl/BacktraceStrategy.java | 122 -- .../appc/rankingframework/impl/CompositeNode.java | 41 - .../appc/rankingframework/impl/Constants.java | 33 - .../impl/DefaultRankedAttributesTreeFactory.java | 52 - .../appc/rankingframework/impl/LeafNode.java | 48 - .../openecomp/appc/rankingframework/impl/Node.java | 43 - .../appc/rankingframework/impl/NodeBase.java | 90 -- .../impl/RankedAttributesTree.java | 48 - .../impl/RankedAttributesTreeBuilder.java | 103 -- .../appc/rankingframework/impl/Strategy.java | 33 - .../appc/rankingframework/impl/Utils.java | 43 - .../rankingframework/TestRankingFramework.java | 228 ++++ .../rankingframework/TestRankingFramework.java | 228 ---- .../transactionrecorder/TransactionRecorder.java | 37 + .../impl/TransactionRecorderImpl.java | 81 ++ .../objects/TransactionRecord.java | 150 +++ .../transactionrecorder/TransactionRecorder.java | 37 - .../impl/TransactionRecorderImpl.java | 81 -- .../objects/TransactionRecord.java | 150 --- .../main/java/org/onap/appc/licmgr/Constants.java | 111 ++ .../onap/appc/licmgr/LicenseDataAccessService.java | 50 + .../java/org/onap/appc/licmgr/LicenseManager.java | 44 + .../appc/licmgr/exception/DataAccessException.java | 48 + .../org/onap/appc/licmgr/objects/LicenseModel.java | 48 + .../java/org/openecomp/appc/licmgr/Constants.java | 111 -- .../appc/licmgr/LicenseDataAccessService.java | 50 - .../org/openecomp/appc/licmgr/LicenseManager.java | 44 - .../appc/licmgr/exception/DataAccessException.java | 48 - .../appc/licmgr/objects/LicenseModel.java | 48 - .../licmgr/impl/LicenseDataAccessServiceImpl.java | 108 ++ .../onap/appc/licmgr/impl/LicenseManagerImpl.java | 88 ++ .../licmgr/impl/LicenseDataAccessServiceImpl.java | 108 -- .../appc/licmgr/impl/LicenseManagerImpl.java | 88 -- .../resources/org/onap/appc/default.properties | 37 + .../org/openecomp/appc/default.properties | 37 - .../onap/appc/licmgr/LicenseManagerImplTest.java | 25 + .../org/onap/appc/licmgr/LicenseManagerMock.java | 48 + .../appc/licmgr/LicenseManagerPluginImplTest.java | 25 + .../org/onap/appc/licmgr/LicenseServiceMock.java | 53 + .../appc/licmgr/TestVfLicenseModelConvert.java | 64 ++ .../appc/licmgr/LicenseManagerImplTest.java | 25 - .../openecomp/appc/licmgr/LicenseManagerMock.java | 48 - .../appc/licmgr/LicenseManagerPluginImplTest.java | 25 - .../openecomp/appc/licmgr/LicenseServiceMock.java | 53 - .../appc/licmgr/TestVfLicenseModelConvert.java | 64 -- .../onap/appc/message/RequestHandlerMessages.java | 31 + .../onap/appc/requesthandler/LCMStateManager.java | 45 + .../onap/appc/requesthandler/RequestHandler.java | 86 ++ .../objects/RequestHandlerInput.java | 61 + .../objects/RequestHandlerOutput.java | 51 + .../appc/message/RequestHandlerMessages.java | 31 - .../appc/requesthandler/LCMStateManager.java | 45 - .../appc/requesthandler/RequestHandler.java | 86 -- .../objects/RequestHandlerInput.java | 61 - .../objects/RequestHandlerOutput.java | 51 - .../onap/appc/messageadapter/MessageAdapter.java | 43 + .../messageadapter/impl/MessageAdapterImpl.java | 139 +++ .../appc/requesthandler/constant/Constants.java | 36 + .../onap/appc/requesthandler/conv/Converter.java | 411 +++++++ .../exceptions/DGWorkflowNotFoundException.java | 38 + .../exceptions/DuplicateRequestException.java | 32 + .../exceptions/InvalidInputException.java | 32 + .../exceptions/LCMOperationsDisabledException.java | 39 + .../exceptions/MissingVNFDataInAAIException.java | 36 + .../exceptions/RequestExpiredException.java | 32 + .../exceptions/VNFNotFoundException.java | 32 + .../exceptions/WorkflowNotFoundException.java | 37 + .../requesthandler/helper/RequestRegistry.java | 93 ++ .../requesthandler/helper/RequestValidator.java | 42 + .../impl/AbstractRequestHandlerImpl.java | 626 ++++++++++ .../impl/AbstractRequestValidatorImpl.java | 328 ++++++ .../requesthandler/impl/DmaapOutgoingMessage.java | 150 +++ .../requesthandler/impl/LCMStateManagerImpl.java | 65 ++ .../requesthandler/impl/RequestHandlerImpl.java | 235 ++++ .../requesthandler/impl/RequestValidatorImpl.java | 132 +++ .../requesthandler/impl/VMRequestHandlerImpl.java | 41 + .../impl/VMRequestValidatorImpl.java | 83 ++ .../workingstatemanager/WorkingStateManager.java | 51 + .../impl/JdbcWorkingStateManager.java | 47 + .../impl/RequestHandlerMessages.java | 31 + .../impl/WorkingStateManagerImpl.java | 231 ++++ .../objects/VNFWorkingState.java | 33 + .../objects/VnfWorkingStateDto.java | 93 ++ .../appc/messageadapter/MessageAdapter.java | 43 - .../messageadapter/impl/MessageAdapterImpl.java | 139 --- .../appc/requesthandler/constant/Constants.java | 36 - .../appc/requesthandler/conv/Converter.java | 411 ------- .../exceptions/DGWorkflowNotFoundException.java | 38 - .../exceptions/DuplicateRequestException.java | 32 - .../exceptions/InvalidInputException.java | 32 - .../exceptions/LCMOperationsDisabledException.java | 39 - .../exceptions/MissingVNFDataInAAIException.java | 36 - .../exceptions/RequestExpiredException.java | 32 - .../exceptions/VNFNotFoundException.java | 32 - .../exceptions/WorkflowNotFoundException.java | 37 - .../requesthandler/helper/RequestRegistry.java | 93 -- .../requesthandler/helper/RequestValidator.java | 42 - .../impl/AbstractRequestHandlerImpl.java | 626 ---------- .../impl/AbstractRequestValidatorImpl.java | 328 ------ .../requesthandler/impl/DmaapOutgoingMessage.java | 150 --- .../requesthandler/impl/LCMStateManagerImpl.java | 65 -- .../requesthandler/impl/RequestHandlerImpl.java | 235 ---- .../requesthandler/impl/RequestValidatorImpl.java | 132 --- .../requesthandler/impl/VMRequestHandlerImpl.java | 41 - .../impl/VMRequestValidatorImpl.java | 83 -- .../workingstatemanager/WorkingStateManager.java | 51 - .../impl/JdbcWorkingStateManager.java | 47 - .../impl/RequestHandlerMessages.java | 31 - .../impl/WorkingStateManagerImpl.java | 231 ---- .../objects/VNFWorkingState.java | 33 - .../objects/VnfWorkingStateDto.java | 93 -- .../resources/org/onap/appc/default.properties | 49 + .../org/openecomp/appc/default.properties | 49 - .../requesthandler/LCMStateManagerImplTest.java | 58 + .../appc/requesthandler/RequestValidatorTest.java | 570 +++++++++ .../onap/appc/requesthandler/TestConverter.java | 372 ++++++ .../appc/requesthandler/TestRequestHandler.java | 649 +++++++++++ .../TestWorkingStateManager.java | 113 ++ .../requesthandler/LCMStateManagerImplTest.java | 58 - .../appc/requesthandler/RequestValidatorTest.java | 570 --------- .../appc/requesthandler/TestConverter.java | 372 ------ .../appc/requesthandler/TestRequestHandler.java | 649 ----------- .../TestWorkingStateManager.java | 113 -- .../resources/org/onap/appc/default.properties | 98 ++ .../org/openecomp/appc/default.properties | 98 -- .../org/onap/appc/workflow/WorkFlowManager.java | 50 + .../workflow/objects/WorkflowExistsOutput.java | 97 ++ .../appc/workflow/objects/WorkflowRequest.java | 70 ++ .../appc/workflow/objects/WorkflowResponse.java | 50 + .../openecomp/appc/workflow/WorkFlowManager.java | 50 - .../workflow/objects/WorkflowExistsOutput.java | 97 -- .../appc/workflow/objects/WorkflowRequest.java | 70 -- .../appc/workflow/objects/WorkflowResponse.java | 50 - .../org/onap/appc/common/constant/Constants.java | 70 ++ .../appc/workflow/impl/WorkFlowManagerImpl.java | 347 ++++++ .../org/onap/appc/workflow/impl/WorkflowKey.java | 62 + .../onap/appc/workflow/impl/WorkflowResolver.java | 142 +++ .../workflow/impl/WorkflowResolverDataReader.java | 131 +++ .../openecomp/appc/common/constant/Constants.java | 70 -- .../appc/workflow/impl/WorkFlowManagerImpl.java | 347 ------ .../openecomp/appc/workflow/impl/WorkflowKey.java | 62 - .../appc/workflow/impl/WorkflowResolver.java | 142 --- .../workflow/impl/WorkflowResolverDataReader.java | 131 --- .../resources/org/onap/appc/default.properties | 43 + .../org/openecomp/appc/default.properties | 43 - .../onap/appc/workflow/TestWorkFlowManager.java | 189 +++ .../appc/workflow/TestWorkFlowManager.java | 189 --- .../resources/org/onap/appc/default.properties | 90 ++ .../org/openecomp/appc/default.properties | 90 -- .../org/onap/appc/listener/AbstractListener.java | 162 +++ .../appc/listener/AppcEventListenerActivator.java | 201 ++++ .../java/org/onap/appc/listener/Controller.java | 58 + .../java/org/onap/appc/listener/EventHandler.java | 188 +++ .../org/onap/appc/listener/LCM/conv/Converter.java | 105 ++ .../onap/appc/listener/LCM/impl/ListenerImpl.java | 164 +++ .../onap/appc/listener/LCM/impl/WorkerImpl.java | 127 ++ .../appc/listener/LCM/model/ActionIdentifiers.java | 84 ++ .../onap/appc/listener/LCM/model/CommonHeader.java | 115 ++ .../listener/LCM/model/DmaapIncomingMessage.java | 53 + .../onap/appc/listener/LCM/model/DmaapMessage.java | 119 ++ .../listener/LCM/model/DmaapOutgoingMessage.java | 53 + .../onap/appc/listener/LCM/model/InputBody.java | 89 ++ .../onap/appc/listener/LCM/model/OutputBody.java | 101 ++ .../appc/listener/LCM/model/ResponseStatus.java | 73 ++ .../GenericProviderOperationRequestFormatter.java | 84 ++ .../ProviderOperationRequestFormatter.java | 45 + .../listener/LCM/operation/ProviderOperations.java | 263 +++++ .../main/java/org/onap/appc/listener/Listener.java | 75 ++ .../org/onap/appc/listener/ListenerProperties.java | 285 +++++ .../onap/appc/listener/demo/impl/ListenerImpl.java | 132 +++ .../listener/demo/impl/ProviderOperations.java | 294 +++++ .../onap/appc/listener/demo/impl/WorkerImpl.java | 85 ++ .../org/onap/appc/listener/demo/model/Action.java | 58 + .../appc/listener/demo/model/CommonMessage.java | 343 ++++++ .../appc/listener/demo/model/IncomingMessage.java | 91 ++ .../appc/listener/demo/model/OutgoingMessage.java | 195 ++++ .../org/onap/appc/listener/demo/model/Status.java | 72 ++ .../onap/appc/listener/impl/ControllerImpl.java | 129 +++ .../onap/appc/listener/impl/EventHandlerImpl.java | 337 ++++++ .../java/org/onap/appc/listener/util/Mapper.java | 137 +++ .../openecomp/appc/listener/AbstractListener.java | 162 --- .../appc/listener/AppcEventListenerActivator.java | 201 ---- .../org/openecomp/appc/listener/Controller.java | 58 - .../org/openecomp/appc/listener/EventHandler.java | 188 --- .../appc/listener/LCM/conv/Converter.java | 105 -- .../appc/listener/LCM/impl/ListenerImpl.java | 164 --- .../appc/listener/LCM/impl/WorkerImpl.java | 127 -- .../appc/listener/LCM/model/ActionIdentifiers.java | 84 -- .../appc/listener/LCM/model/CommonHeader.java | 115 -- .../listener/LCM/model/DmaapIncomingMessage.java | 53 - .../appc/listener/LCM/model/DmaapMessage.java | 119 -- .../listener/LCM/model/DmaapOutgoingMessage.java | 53 - .../appc/listener/LCM/model/InputBody.java | 89 -- .../appc/listener/LCM/model/OutputBody.java | 101 -- .../appc/listener/LCM/model/ResponseStatus.java | 73 -- .../GenericProviderOperationRequestFormatter.java | 84 -- .../ProviderOperationRequestFormatter.java | 45 - .../listener/LCM/operation/ProviderOperations.java | 263 ----- .../java/org/openecomp/appc/listener/Listener.java | 75 -- .../appc/listener/ListenerProperties.java | 285 ----- .../appc/listener/demo/impl/ListenerImpl.java | 132 --- .../listener/demo/impl/ProviderOperations.java | 294 ----- .../appc/listener/demo/impl/WorkerImpl.java | 85 -- .../openecomp/appc/listener/demo/model/Action.java | 58 - .../appc/listener/demo/model/CommonMessage.java | 343 ------ .../appc/listener/demo/model/IncomingMessage.java | 91 -- .../appc/listener/demo/model/OutgoingMessage.java | 195 ---- .../openecomp/appc/listener/demo/model/Status.java | 72 -- .../appc/listener/impl/ControllerImpl.java | 129 --- .../appc/listener/impl/EventHandlerImpl.java | 337 ------ .../org/openecomp/appc/listener/util/Mapper.java | 137 --- .../resources/org/onap/appc/default.properties | 102 ++ .../org/openecomp/appc/default.properties | 102 -- .../org/onap/appc/listener/LCM/TestConverter.java | 94 ++ .../LCM1607/model/TestJsonGenericMessages.java | 102 ++ .../onap/appc/listener/TestAbstractListener.java | 101 ++ .../listener/TestAppcDmaapListenerActivator.java | 49 + .../onap/appc/listener/TestListenerProperties.java | 157 +++ .../onap/appc/listener/demo/model/TestEnums.java | 61 + .../appc/listener/demo/model/TestMessages.java | 163 +++ .../onap/appc/listener/impl/TestController.java | 29 + .../onap/appc/listener/impl/TestEventHandler.java | 173 +++ .../org/onap/appc/listener/impl/TestListener.java | 115 ++ .../org/onap/appc/listener/util/TestMapper.java | 107 ++ .../openecomp/appc/listener/LCM/TestConverter.java | 94 -- .../LCM1607/model/TestJsonGenericMessages.java | 102 -- .../appc/listener/TestAbstractListener.java | 101 -- .../listener/TestAppcDmaapListenerActivator.java | 49 - .../appc/listener/TestListenerProperties.java | 157 --- .../appc/listener/demo/model/TestEnums.java | 61 - .../appc/listener/demo/model/TestMessages.java | 163 --- .../appc/listener/impl/TestController.java | 29 - .../appc/listener/impl/TestEventHandler.java | 173 --- .../openecomp/appc/listener/impl/TestListener.java | 115 -- .../openecomp/appc/listener/util/TestMapper.java | 107 -- .../resources/org/onap/appc/default.properties | 92 ++ .../org/openecomp/appc/default.properties | 92 -- .../artifact/handler/ArtifactHandlerProvider.java | 213 ++++ .../handler/SdcArtifactHandlerActivator.java | 58 + .../artifact/handler/dbservices/DBService.java | 531 +++++++++ .../artifact/handler/node/ArtifactHandlerNode.java | 533 +++++++++ .../handler/utils/ArtifactHandlerProviderUtil.java | 191 ++++ .../appc/artifact/handler/utils/EscapeUtils.java | 43 + .../handler/utils/SdcArtifactHandlerConstants.java | 93 ++ .../rev170321/ArtifactHandlerProviderModule.java | 59 + .../ArtifactHandlerProviderModuleFactory.java | 37 + .../rev170321/ArtifactHandlerProviderModule.java | 59 - .../ArtifactHandlerProviderModuleFactory.java | 37 - .../artifact/handler/ArtifactHandlerProvider.java | 213 ---- .../handler/SdcArtifactHandlerActivator.java | 58 - .../artifact/handler/dbservices/DBService.java | 531 --------- .../artifact/handler/node/ArtifactHandlerNode.java | 533 --------- .../handler/utils/ArtifactHandlerProviderUtil.java | 191 ---- .../appc/artifact/handler/utils/EscapeUtils.java | 43 - .../handler/utils/SdcArtifactHandlerConstants.java | 93 -- .../artifact/handler/dbservices/DBServiceTest.java | 298 +++++ .../artifact/handler/dbservices/MockDBService.java | 51 + .../handler/dbservices/MockSvcLogicResource.java | 55 + .../handler/node/ArtifactHandlerNodeTest.java | 174 +++ .../handler/node/MockArtifactHandlerNode.java | 65 ++ .../utils/ArtifactHandlerProviderUtilTest.java | 82 ++ .../artifact/handler/dbservices/DBServiceTest.java | 298 ----- .../artifact/handler/dbservices/MockDBService.java | 51 - .../handler/dbservices/MockSvcLogicResource.java | 55 - .../handler/node/ArtifactHandlerNodeTest.java | 174 --- .../handler/node/MockArtifactHandlerNode.java | 65 -- .../utils/ArtifactHandlerProviderUtilTest.java | 82 -- .../org/onap/appc/design/data/ArtifactInfo.java | 42 + .../java/org/onap/appc/design/data/DesignInfo.java | 115 ++ .../org/onap/appc/design/data/DesignRequest.java | 132 +++ .../org/onap/appc/design/data/DesignResponse.java | 77 ++ .../java/org/onap/appc/design/data/StatusInfo.java | 86 ++ .../appc/design/dbervices/DbResponseProcessor.java | 110 ++ .../org/onap/appc/design/dbervices/DbService.java | 146 +++ .../appc/design/dbervices/DesignDBService.java | 645 +++++++++++ .../appc/design/dbervices/RequestValidator.java | 126 ++ .../propertyServices/PropertyUpdateService.java | 30 + .../design/services/DesignServiceProvider.java | 72 ++ .../design/services/impl/DesignServicesImpl.java | 160 +++ .../services/util/ArtifactHandlerClient.java | 187 +++ .../services/util/DesignServiceConstants.java | 106 ++ .../appc/design/services/util/EscapeUtils.java | 44 + .../util/SecureRestClientTrustManager.java | 58 + .../validator/ValidatorResponseProcessor.java | 38 + .../appc/design/validator/ValidatorService.java | 168 +++ .../appc/design/xinterface/XInterfaceService.java | 43 + .../appc/design/xinterface/XResponseProcessor.java | 38 + .../openecomp/appc/design/data/ArtifactInfo.java | 42 - .../org/openecomp/appc/design/data/DesignInfo.java | 115 -- .../openecomp/appc/design/data/DesignRequest.java | 132 --- .../openecomp/appc/design/data/DesignResponse.java | 77 -- .../org/openecomp/appc/design/data/StatusInfo.java | 86 -- .../appc/design/dbervices/DbResponseProcessor.java | 110 -- .../openecomp/appc/design/dbervices/DbService.java | 146 --- .../appc/design/dbervices/DesignDBService.java | 645 ----------- .../appc/design/dbervices/RequestValidator.java | 126 -- .../propertyServices/PropertyUpdateService.java | 30 - .../design/services/DesignServiceProvider.java | 72 -- .../design/services/impl/DesignServicesImpl.java | 160 --- .../services/util/ArtifactHandlerClient.java | 187 --- .../services/util/DesignServiceConstants.java | 106 -- .../appc/design/services/util/EscapeUtils.java | 44 - .../util/SecureRestClientTrustManager.java | 58 - .../validator/ValidatorResponseProcessor.java | 38 - .../appc/design/validator/ValidatorService.java | 168 --- .../appc/design/xinterface/XInterfaceService.java | 43 - .../appc/design/xinterface/XResponseProcessor.java | 38 - .../design/validator/TestArifactHandlerClient.java | 73 ++ .../onap/appc/design/validator/TestDBService.java | 242 ++++ .../onap/appc/design/validator/TestDbResponse.java | 51 + .../onap/appc/design/validator/TestDesigndata.java | 102 ++ .../appc/design/validator/TestEscapeUtils.java | 52 + .../design/validator/TestValidatorService.java | 131 +++ .../design/validator/TestArifactHandlerClient.java | 73 -- .../appc/design/validator/TestDBService.java | 242 ---- .../appc/design/validator/TestDbResponse.java | 51 - .../appc/design/validator/TestDesigndata.java | 102 -- .../appc/design/validator/TestEscapeUtils.java | 52 - .../design/validator/TestValidatorService.java | 131 --- .../appc/lifecyclemanager/LifecycleManager.java | 33 + .../appc/lifecyclemanager/objects/LCMResponse.java | 36 + .../objects/LifecycleException.java | 36 + .../objects/NoTransitionDefinedException.java | 36 + .../objects/VNFOperationOutcome.java | 32 + .../appc/lifecyclemanager/LifecycleManager.java | 33 - .../appc/lifecyclemanager/objects/LCMResponse.java | 36 - .../objects/LifecycleException.java | 36 - .../objects/NoTransitionDefinedException.java | 36 - .../objects/VNFOperationOutcome.java | 32 - .../impl/LifecycleManagerImpl.java | 102 ++ .../impl/LifecycleManagerImpl.java | 102 -- .../resources/org/onap/appc/default.properties | 39 + .../org/openecomp/appc/default.properties | 39 - .../java/org/onap/appc/LifecycleManagerTest.java | 185 +++ .../org/onap/appc/OamLifeCycleManagerTest.java | 152 +++ .../org/openecomp/appc/LifecycleManagerTest.java | 185 --- .../openecomp/appc/OamLifeCycleManagerTest.java | 152 --- .../org/onap/appc/statemachine/StateMachine.java | 45 + .../appc/statemachine/StateMetaDataReader.java | 31 + .../statemachine/impl/StateMachineFactory.java | 42 + .../appc/statemachine/impl/StateMachineImpl.java | 103 ++ .../impl/readers/AppcOamMetaDataReader.java | 113 ++ .../statemachine/impl/readers/AppcOamStates.java | 56 + .../impl/readers/VnfMetaDataReader.java | 493 ++++++++ .../org/onap/appc/statemachine/objects/Event.java | 67 ++ .../onap/appc/statemachine/objects/Response.java | 39 + .../org/onap/appc/statemachine/objects/State.java | 81 ++ .../statemachine/objects/StateMachineMetadata.java | 78 ++ .../statemachine/objects/StateMachineResponse.java | 51 + .../onap/appc/statemachine/objects/Transition.java | 51 + .../openecomp/appc/statemachine/StateMachine.java | 45 - .../appc/statemachine/StateMetaDataReader.java | 31 - .../statemachine/impl/StateMachineFactory.java | 42 - .../appc/statemachine/impl/StateMachineImpl.java | 103 -- .../impl/readers/AppcOamMetaDataReader.java | 113 -- .../statemachine/impl/readers/AppcOamStates.java | 56 - .../impl/readers/VnfMetaDataReader.java | 493 -------- .../openecomp/appc/statemachine/objects/Event.java | 67 -- .../appc/statemachine/objects/Response.java | 39 - .../openecomp/appc/statemachine/objects/State.java | 81 -- .../statemachine/objects/StateMachineMetadata.java | 78 -- .../statemachine/objects/StateMachineResponse.java | 51 - .../appc/statemachine/objects/Transition.java | 51 - .../statemachine/impl/StateMachineFactoryTest.java | 59 + .../statemachine/impl/StateMachineImplTest.java | 107 ++ .../impl/readers/AppcOamMetaDataReaderTest.java | 74 ++ .../impl/readers/AppcOamStatesTest.java | 71 ++ .../impl/readers/VnfMetaDataReaderTest.java | 79 ++ .../onap/appc/statemachine/objects/EventTest.java | 70 ++ .../appc/statemachine/objects/ResponseTest.java | 40 + .../objects/StateMachineMetadataTest.java | 61 + .../objects/StateMachineResponseTest.java | 71 ++ .../onap/appc/statemachine/objects/StateTest.java | 91 ++ .../appc/statemachine/objects/TransitionTest.java | 57 + .../statemachine/impl/StateMachineFactoryTest.java | 59 - .../statemachine/impl/StateMachineImplTest.java | 107 -- .../impl/readers/AppcOamMetaDataReaderTest.java | 74 -- .../impl/readers/AppcOamStatesTest.java | 71 -- .../impl/readers/VnfMetaDataReaderTest.java | 79 -- .../appc/statemachine/objects/EventTest.java | 70 -- .../appc/statemachine/objects/ResponseTest.java | 40 - .../objects/StateMachineMetadataTest.java | 61 - .../objects/StateMachineResponseTest.java | 71 -- .../appc/statemachine/objects/StateTest.java | 91 -- .../appc/statemachine/objects/TransitionTest.java | 57 - .../main/java/org/onap/appc/MetricActivator.java | 56 + .../onap/appc/metricservice/MetricRegistry.java | 49 + .../org/onap/appc/metricservice/MetricService.java | 41 + .../org/onap/appc/metricservice/Publisher.java | 37 + .../metricservice/impl/MetricRegistryImpl.java | 101 ++ .../appc/metricservice/impl/MetricServiceImpl.java | 59 + .../onap/appc/metricservice/metric/Counter.java | 30 + .../metric/DispatchingFunctionCounterBuilder.java | 34 + .../metric/DispatchingFuntionMetric.java | 32 + .../metric/DmaapRequestCounterBuilder.java | 34 + .../metric/DmaapRequestCounterMetric.java | 32 + .../org/onap/appc/metricservice/metric/Metric.java | 55 + .../metricservice/metric/MetricBuilderFactory.java | 33 + .../onap/appc/metricservice/metric/MetricType.java | 35 + .../metricservice/metric/PrimitiveCounter.java | 36 + .../metric/PrimitiveCounterBuilder.java | 36 + .../metric/impl/DefaultPrimitiveCounter.java | 113 ++ .../DispatchingFunctionCounterBuilderImpl.java | 64 ++ .../metric/impl/DispatchingFuntionMetricImpl.java | 124 ++ .../impl/DmaapRequestCounterBuilderImpl.java | 67 ++ .../metric/impl/DmaapRequestCounterMetricImpl.java | 121 ++ .../metric/impl/MetricBuilderFactoryImpl.java | 48 + .../metric/impl/PrimitiveCounterBuilderImpl.java | 59 + .../metricservice/policy/PolicyBuilderFactory.java | 30 + .../metricservice/policy/PublishingPolicy.java | 43 + .../policy/ScheduledPolicyBuilder.java | 41 + .../policy/ScheduledPublishingPolicy.java | 36 + .../policy/impl/PolicyBuilderFactoryImpl.java | 36 + .../policy/impl/ScheduledPolicyBuilderImpl.java | 68 ++ .../policy/impl/ScheduledPublishingPolicyImpl.java | 224 ++++ .../appc/metricservice/publisher/LogPublisher.java | 52 + .../java/org/openecomp/appc/MetricActivator.java | 56 - .../appc/metricservice/MetricRegistry.java | 49 - .../appc/metricservice/MetricService.java | 41 - .../openecomp/appc/metricservice/Publisher.java | 37 - .../metricservice/impl/MetricRegistryImpl.java | 101 -- .../appc/metricservice/impl/MetricServiceImpl.java | 59 - .../appc/metricservice/metric/Counter.java | 30 - .../metric/DispatchingFunctionCounterBuilder.java | 34 - .../metric/DispatchingFuntionMetric.java | 32 - .../metric/DmaapRequestCounterBuilder.java | 34 - .../metric/DmaapRequestCounterMetric.java | 32 - .../appc/metricservice/metric/Metric.java | 55 - .../metricservice/metric/MetricBuilderFactory.java | 33 - .../appc/metricservice/metric/MetricType.java | 35 - .../metricservice/metric/PrimitiveCounter.java | 36 - .../metric/PrimitiveCounterBuilder.java | 36 - .../metric/impl/DefaultPrimitiveCounter.java | 113 -- .../DispatchingFunctionCounterBuilderImpl.java | 64 -- .../metric/impl/DispatchingFuntionMetricImpl.java | 124 -- .../impl/DmaapRequestCounterBuilderImpl.java | 67 -- .../metric/impl/DmaapRequestCounterMetricImpl.java | 121 -- .../metric/impl/MetricBuilderFactoryImpl.java | 48 - .../metric/impl/PrimitiveCounterBuilderImpl.java | 59 - .../metricservice/policy/PolicyBuilderFactory.java | 30 - .../metricservice/policy/PublishingPolicy.java | 43 - .../policy/ScheduledPolicyBuilder.java | 41 - .../policy/ScheduledPublishingPolicy.java | 36 - .../policy/impl/PolicyBuilderFactoryImpl.java | 36 - .../policy/impl/ScheduledPolicyBuilderImpl.java | 68 -- .../policy/impl/ScheduledPublishingPolicyImpl.java | 224 ---- .../appc/metricservice/publisher/LogPublisher.java | 52 - .../resources/org/onap/appc/default.properties | 31 + .../org/openecomp/appc/default.properties | 31 - .../appc/metricservice/TestMetricServiceImpl.java | 169 +++ .../appc/metricservice/TestMetricServiceImpl.java | 169 --- .../resources/org/onap/appc/default.properties | 29 + .../org/openecomp/appc/default.properties | 29 - .../src/main/java/org/onap/appc/oam/AppcOam.java | 339 ++++++ .../java/org/onap/appc/oam/OAMCommandStatus.java | 74 ++ .../onap/appc/oam/messageadapter/Converter.java | 156 +++ .../oam/messageadapter/DmaapOutgoingMessage.java | 137 +++ .../appc/oam/messageadapter/MessageAdapter.java | 183 +++ .../onap/appc/oam/messageadapter/OAMContext.java | 75 ++ .../appc/oam/processor/BaseActionRunnable.java | 254 ++++ .../org/onap/appc/oam/processor/BaseCommon.java | 265 +++++ .../org/onap/appc/oam/processor/BaseProcessor.java | 216 ++++ .../onap/appc/oam/processor/OamMmodeProcessor.java | 170 +++ .../appc/oam/processor/OamRestartProcessor.java | 208 ++++ .../onap/appc/oam/processor/OamStartProcessor.java | 151 +++ .../onap/appc/oam/processor/OamStopProcessor.java | 120 ++ .../org/onap/appc/oam/util/AsyncTaskHelper.java | 394 +++++++ .../java/org/onap/appc/oam/util/BundleFilter.java | 128 +++ .../java/org/onap/appc/oam/util/BundleHelper.java | 274 +++++ .../onap/appc/oam/util/ConfigurationHelper.java | 106 ++ .../org/onap/appc/oam/util/OperationHelper.java | 205 ++++ .../java/org/onap/appc/oam/util/StateHelper.java | 144 +++ .../appc/oam/impl/rev170303/AppcOamModule.java | 55 + .../oam/impl/rev170303/AppcOamModuleFactory.java | 37 + .../appc/oam/impl/rev170303/AppcOamModule.java | 55 - .../oam/impl/rev170303/AppcOamModuleFactory.java | 37 - .../main/java/org/openecomp/appc/oam/AppcOam.java | 339 ------ .../org/openecomp/appc/oam/OAMCommandStatus.java | 74 -- .../appc/oam/messageadapter/Converter.java | 156 --- .../oam/messageadapter/DmaapOutgoingMessage.java | 137 --- .../appc/oam/messageadapter/MessageAdapter.java | 183 --- .../appc/oam/messageadapter/OAMContext.java | 75 -- .../appc/oam/processor/BaseActionRunnable.java | 254 ---- .../openecomp/appc/oam/processor/BaseCommon.java | 265 ----- .../appc/oam/processor/BaseProcessor.java | 216 ---- .../appc/oam/processor/OamMmodeProcessor.java | 170 --- .../appc/oam/processor/OamRestartProcessor.java | 208 ---- .../appc/oam/processor/OamStartProcessor.java | 151 --- .../appc/oam/processor/OamStopProcessor.java | 120 -- .../openecomp/appc/oam/util/AsyncTaskHelper.java | 394 ------- .../org/openecomp/appc/oam/util/BundleFilter.java | 128 --- .../org/openecomp/appc/oam/util/BundleHelper.java | 274 ----- .../appc/oam/util/ConfigurationHelper.java | 106 -- .../openecomp/appc/oam/util/OperationHelper.java | 205 ---- .../org/openecomp/appc/oam/util/StateHelper.java | 144 --- .../resources/org/onap/appc/default.properties | 90 ++ .../src/main/resources/org/onap/appc/logback.xml | 287 +++++ .../org/openecomp/appc/default.properties | 90 -- .../main/resources/org/openecomp/appc/logback.xml | 287 ----- .../test/java/org/onap/appc/oam/AppcOamTest.java | 166 +++ .../org/onap/appc/oam/OAMCommandStatusTest.java | 99 ++ .../oam/messageadapter/MessageAdapterTest.java | 115 ++ .../appc/oam/processor/BaseActionRunnableTest.java | 293 +++++ .../onap/appc/oam/processor/BaseCommonTest.java | 182 +++ .../onap/appc/oam/processor/BaseProcessorTest.java | 174 +++ .../onap/appc/oam/util/AsyncTaskHelperTest.java | 665 +++++++++++ .../org/onap/appc/oam/util/BundleHelperTest.java | 180 +++ .../appc/oam/util/ConfigurationHelperTest.java | 128 +++ .../onap/appc/oam/util/OperationHelperTest.java | 240 ++++ .../org/onap/appc/oam/util/StateHelperTest.java | 173 +++ .../java/org/openecomp/appc/oam/AppcOamTest.java | 166 --- .../openecomp/appc/oam/OAMCommandStatusTest.java | 99 -- .../oam/messageadapter/MessageAdapterTest.java | 115 -- .../appc/oam/processor/BaseActionRunnableTest.java | 293 ----- .../appc/oam/processor/BaseCommonTest.java | 182 --- .../appc/oam/processor/BaseProcessorTest.java | 174 --- .../appc/oam/util/AsyncTaskHelperTest.java | 665 ----------- .../openecomp/appc/oam/util/BundleHelperTest.java | 180 --- .../appc/oam/util/ConfigurationHelperTest.java | 128 --- .../appc/oam/util/OperationHelperTest.java | 240 ---- .../openecomp/appc/oam/util/StateHelperTest.java | 173 --- .../appc/aai/client/AppcAaiClientActivator.java | 63 + .../appc/aai/client/AppcAaiClientConstant.java | 51 + .../org/onap/appc/aai/client/aai/AaiService.java | 775 +++++++++++++ .../onap/appc/aai/client/node/AAIResourceNode.java | 514 +++++++++ .../appc/aai/client/AppcAaiClientActivator.java | 63 - .../appc/aai/client/AppcAaiClientConstant.java | 51 - .../openecomp/appc/aai/client/aai/AaiService.java | 775 ------------- .../appc/aai/client/node/AAIResourceNode.java | 514 --------- .../onap/appc/aai/client/aai/MockAaiService.java | 541 +++++++++ .../onap/appc/aai/client/aai/TestAaiService.java | 351 ++++++ .../onap/appc/aai/client/node/MockAaiService.java | 88 ++ .../appc/aai/client/node/TestAAIResourceNode.java | 238 ++++ .../appc/aai/client/aai/MockAaiService.java | 541 --------- .../appc/aai/client/aai/TestAaiService.java | 351 ------ .../appc/aai/client/node/MockAaiService.java | 88 -- .../appc/aai/client/node/TestAAIResourceNode.java | 238 ---- .../onap/appc/instar/InstarClientActivator.java | 64 ++ .../onap/appc/instar/dme2client/Dme2Client.java | 184 +++ .../dme2client/SecureRestClientTrustManager.java | 58 + .../interfaceImpl/InstarResponseHandlerImpl.java | 86 ++ .../instar/interfaceImpl/InstarRestClientImpl.java | 71 ++ .../interfaceImpl/InterfaceIpAddressImpl.java | 91 ++ .../interfaces/ResponseHandlerInterface.java | 31 + .../instar/interfaces/RestClientInterface.java | 32 + .../instar/interfaces/RuleHandlerInterface.java | 32 + .../onap/appc/instar/node/InstarClientNode.java | 135 +++ .../appc/instar/utils/InstarClientConstant.java | 82 ++ .../appc/instar/InstarClientActivator.java | 64 -- .../appc/instar/dme2client/Dme2Client.java | 184 --- .../dme2client/SecureRestClientTrustManager.java | 58 - .../interfaceImpl/InstarResponseHandlerImpl.java | 86 -- .../instar/interfaceImpl/InstarRestClientImpl.java | 71 -- .../interfaceImpl/InterfaceIpAddressImpl.java | 91 -- .../interfaces/ResponseHandlerInterface.java | 31 - .../instar/interfaces/RestClientInterface.java | 32 - .../instar/interfaces/RuleHandlerInterface.java | 32 - .../appc/instar/node/InstarClientNode.java | 135 --- .../appc/instar/utils/InstarClientConstant.java | 82 -- .../TestInstarResponseHandlerImpl.java | 78 ++ .../interfaceImpl/TestInstarRestClientImpl.java | 43 + .../interfaceImpl/TestInterfaceIpAddressImpl.java | 65 ++ .../org/onap/appc/instar/node/TestDme2Client.java | 46 + .../appc/instar/node/TestInstarClientNode.java | 83 ++ .../node/TestSecureRestClientTrustManager.java | 43 + .../TestInstarResponseHandlerImpl.java | 78 -- .../interfaceImpl/TestInstarRestClientImpl.java | 43 - .../interfaceImpl/TestInterfaceIpAddressImpl.java | 65 -- .../openecomp/appc/instar/node/TestDme2Client.java | 46 - .../appc/instar/node/TestInstarClientNode.java | 83 -- .../node/TestSecureRestClientTrustManager.java | 43 - .../java/org/onap/appc/provider/AppcProvider.java | 261 +++++ .../org/onap/appc/provider/AppcProviderClient.java | 120 ++ .../org/onap/appc/provider/AppcProviderLcm.java | 1208 ++++++++++++++++++++ .../onap/appc/provider/ResponseHeaderBuilder.java | 91 ++ .../onap/appc/provider/lcm/util/LCMConstants.java | 38 + .../provider/lcm/util/RequestInputBuilder.java | 162 +++ .../appc/provider/lcm/util/ValidationService.java | 94 ++ .../appc/provider/topology/TopologyService.java | 800 +++++++++++++ .../impl/rev140523/AppcProviderModule.java | 88 ++ .../impl/rev140523/AppcProviderModuleFactory.java | 39 + .../lcm/impl/rev160108/AppcProviderLcmModule.java | 56 + .../rev160108/AppcProviderLcmModuleFactory.java | 37 + .../impl/rev140523/AppcProviderModule.java | 88 -- .../impl/rev140523/AppcProviderModuleFactory.java | 39 - .../lcm/impl/rev160108/AppcProviderLcmModule.java | 56 - .../rev160108/AppcProviderLcmModuleFactory.java | 37 - .../org/openecomp/appc/provider/AppcProvider.java | 261 ----- .../appc/provider/AppcProviderClient.java | 120 -- .../openecomp/appc/provider/AppcProviderLcm.java | 1208 -------------------- .../appc/provider/ResponseHeaderBuilder.java | 91 -- .../appc/provider/lcm/util/LCMConstants.java | 38 - .../provider/lcm/util/RequestInputBuilder.java | 162 --- .../appc/provider/lcm/util/ValidationService.java | 94 -- .../appc/provider/topology/TopologyService.java | 800 ------------- .../resources/org/onap/appc/default.properties | 58 + .../src/main/resources/org/onap/appc/logback.xml | 287 +++++ .../org/openecomp/appc/default.properties | 58 - .../main/resources/org/openecomp/appc/logback.xml | 287 ----- .../onap/appc/provider/AppcProviderClientTest.java | 99 ++ .../onap/appc/provider/AppcProviderLcmTest.java | 1118 ++++++++++++++++++ .../org/onap/appc/provider/AppcProviderTest.java | 225 ++++ .../appc/provider/ResponseHeaderBuilderTest.java | 38 + .../provider/topology/TopologyServiceTest.java | 157 +++ .../appc/provider/AppcProviderClientTest.java | 99 -- .../appc/provider/AppcProviderLcmTest.java | 1118 ------------------ .../openecomp/appc/provider/AppcProviderTest.java | 225 ---- .../appc/provider/ResponseHeaderBuilderTest.java | 38 - .../provider/topology/TopologyServiceTest.java | 157 --- .../onap/appc/sdc/artifacts/ArtifactProcessor.java | 41 + .../artifacts/helper/ArtifactStorageService.java | 329 ++++++ .../onap/appc/sdc/artifacts/helper/Constants.java | 72 ++ .../artifacts/helper/DependencyModelGenerator.java | 97 ++ .../artifacts/impl/AbstractArtifactProcessor.java | 196 ++++ .../artifacts/impl/ArtifactProcessorFactory.java | 85 ++ .../artifacts/impl/ConfigArtifactProcessor.java | 76 ++ .../artifacts/impl/LicenseArtifactProcessor.java | 92 ++ .../artifacts/impl/ToscaCsarArtifactProcessor.java | 241 ++++ .../appc/sdc/artifacts/object/ArtifactType.java | 46 + .../onap/appc/sdc/artifacts/object/Resource.java | 87 ++ .../appc/sdc/artifacts/object/SDCArtifact.java | 215 ++++ .../appc/sdc/artifacts/object/SDCReference.java | 94 ++ .../org/onap/appc/sdc/artifacts/object/Vnfc.java | 78 ++ .../onap/appc/sdc/listener/ProviderOperations.java | 211 ++++ .../onap/appc/sdc/listener/ProviderResponse.java | 45 + .../org/onap/appc/sdc/listener/SdcCallback.java | 148 +++ .../java/org/onap/appc/sdc/listener/SdcConfig.java | 202 ++++ .../org/onap/appc/sdc/listener/SdcListener.java | 219 ++++ .../main/java/org/onap/appc/sdc/listener/Util.java | 126 ++ .../java/org/onap/tlv/sdc/security/Passwords.java | 170 +++ .../appc/sdc/artifacts/ArtifactProcessor.java | 41 - .../artifacts/helper/ArtifactStorageService.java | 329 ------ .../appc/sdc/artifacts/helper/Constants.java | 72 -- .../artifacts/helper/DependencyModelGenerator.java | 97 -- .../artifacts/impl/AbstractArtifactProcessor.java | 196 ---- .../artifacts/impl/ArtifactProcessorFactory.java | 85 -- .../artifacts/impl/ConfigArtifactProcessor.java | 76 -- .../artifacts/impl/LicenseArtifactProcessor.java | 92 -- .../artifacts/impl/ToscaCsarArtifactProcessor.java | 241 ---- .../appc/sdc/artifacts/object/ArtifactType.java | 46 - .../appc/sdc/artifacts/object/Resource.java | 87 -- .../appc/sdc/artifacts/object/SDCArtifact.java | 215 ---- .../appc/sdc/artifacts/object/SDCReference.java | 94 -- .../openecomp/appc/sdc/artifacts/object/Vnfc.java | 78 -- .../appc/sdc/listener/ProviderOperations.java | 211 ---- .../appc/sdc/listener/ProviderResponse.java | 45 - .../openecomp/appc/sdc/listener/SdcCallback.java | 148 --- .../org/openecomp/appc/sdc/listener/SdcConfig.java | 202 ---- .../openecomp/appc/sdc/listener/SdcListener.java | 219 ---- .../java/org/openecomp/appc/sdc/listener/Util.java | 126 -- .../org/openecomp/tlv/sdc/security/Passwords.java | 170 --- .../resources/org/onap/appc/default.properties | 40 + .../org/openecomp/appc/default.properties | 40 - .../sdc/artifacts/impl/TestArtifactProcessor.java | 128 +++ .../impl/TestLicenseArtifactProcessor.java | 132 +++ .../onap/appc/sdc/listener/SdcCallbackTest.java | 233 ++++ .../onap/appc/sdc/listener/SdcListenerTest.java | 158 +++ .../org/onap/appc/sdc/listener/SdcTestObjects.java | 21 + .../org/onap/appc/sdc/listener/SdcTestUtils.java | 108 ++ .../java/org/onap/appc/sdc/listener/TestRun.java | 41 + .../sdc/artifacts/impl/TestArtifactProcessor.java | 128 --- .../impl/TestLicenseArtifactProcessor.java | 132 --- .../appc/sdc/listener/SdcCallbackTest.java | 233 ---- .../appc/sdc/listener/SdcListenerTest.java | 158 --- .../appc/sdc/listener/SdcTestObjects.java | 21 - .../openecomp/appc/sdc/listener/SdcTestUtils.java | 108 -- .../org/openecomp/appc/sdc/listener/TestRun.java | 41 - .../resources/org/onap/appc/default.properties | 36 + .../org/openecomp/appc/default.properties | 36 - .../java/org/onap/appc/yang/YANGGenerator.java | 49 + .../yang/exception/YANGGenerationException.java | 51 + .../onap/appc/yang/impl/YANGGeneratorFactory.java | 52 + .../org/onap/appc/yang/impl/YANGGeneratorImpl.java | 176 +++ .../main/java/org/onap/appc/yang/objects/Leaf.java | 72 ++ .../java/org/onap/appc/yang/type/YangTypes.java | 108 ++ .../org/openecomp/appc/yang/YANGGenerator.java | 49 - .../yang/exception/YANGGenerationException.java | 51 - .../appc/yang/impl/YANGGeneratorFactory.java | 52 - .../appc/yang/impl/YANGGeneratorImpl.java | 176 --- .../java/org/openecomp/appc/yang/objects/Leaf.java | 72 -- .../org/openecomp/appc/yang/type/YangTypes.java | 108 -- .../test/java/org/onap/appc/TestYANGGenerator.java | 197 ++++ .../java/org/openecomp/appc/TestYANGGenerator.java | 197 ---- .../org/onap/appc/seqgen/SequenceGenerator.java | 43 + .../seqgen/dgplugin/SequenceGeneratorPlugin.java | 31 + .../dgplugin/impl/SequenceGeneratorPluginImpl.java | 243 ++++ .../appc/seqgen/impl/SequenceGeneratorFactory.java | 54 + .../appc/seqgen/impl/StartSequenceGenerator.java | 275 +++++ .../appc/seqgen/impl/StopSequenceGenerator.java | 183 +++ .../onap/appc/seqgen/objects/ActionIdentifier.java | 63 + .../org/onap/appc/seqgen/objects/Constants.java | 123 ++ .../onap/appc/seqgen/objects/PreCheckOption.java | 74 ++ .../org/onap/appc/seqgen/objects/RequestInfo.java | 72 ++ .../appc/seqgen/objects/RequestInfoBuilder.java | 76 ++ .../org/onap/appc/seqgen/objects/Response.java | 65 ++ .../seqgen/objects/SequenceGeneratorInput.java | 93 ++ .../objects/SequenceGeneratorInputBuilder.java | 85 ++ .../org/onap/appc/seqgen/objects/Transaction.java | 142 +++ .../seqgen/provider/SequenceGeneratorProvider.java | 352 ++++++ .../impl/rev170706/SequenceGeneratorModule.java | 51 + .../rev170706/SequenceGeneratorModuleFactory.java | 33 + .../impl/rev170706/SequenceGeneratorModule.java | 51 - .../rev170706/SequenceGeneratorModuleFactory.java | 33 - .../openecomp/appc/seqgen/SequenceGenerator.java | 43 - .../seqgen/dgplugin/SequenceGeneratorPlugin.java | 31 - .../dgplugin/impl/SequenceGeneratorPluginImpl.java | 243 ---- .../appc/seqgen/impl/SequenceGeneratorFactory.java | 54 - .../appc/seqgen/impl/StartSequenceGenerator.java | 275 ----- .../appc/seqgen/impl/StopSequenceGenerator.java | 183 --- .../appc/seqgen/objects/ActionIdentifier.java | 63 - .../openecomp/appc/seqgen/objects/Constants.java | 123 -- .../appc/seqgen/objects/PreCheckOption.java | 74 -- .../openecomp/appc/seqgen/objects/RequestInfo.java | 72 -- .../appc/seqgen/objects/RequestInfoBuilder.java | 76 -- .../openecomp/appc/seqgen/objects/Response.java | 65 -- .../seqgen/objects/SequenceGeneratorInput.java | 93 -- .../objects/SequenceGeneratorInputBuilder.java | 85 -- .../openecomp/appc/seqgen/objects/Transaction.java | 142 --- .../seqgen/provider/SequenceGeneratorProvider.java | 352 ------ .../appc/seqgen/TestSequenceGeneratorPlugin.java | 272 +++++ .../appc/seqgen/TestSequenceGeneratorPlugin.java | 272 ----- 1590 files changed, 93577 insertions(+), 93577 deletions(-) create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/RPC.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcClientServiceFactoryProvider.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ApplicationContext.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/LifeCycleManagerStateful.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ResponseHandler.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientBusinessException.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientException.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientInternalException.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreResponseHandler.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/LCMRequestProcessor.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/RPCInvocator.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Action.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ActionIdentifiers.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CommonHeader.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Flags.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Payload.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Status.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockInput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockOutput.java create mode 100644 appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ZULU.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/RPC.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcClientServiceFactoryProvider.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ApplicationContext.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/LifeCycleManagerStateful.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ResponseHandler.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientBusinessException.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientException.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientInternalException.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreResponseHandler.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/LCMRequestProcessor.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/RPCInvocator.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Action.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ActionIdentifiers.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CommonHeader.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Flags.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Payload.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Status.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockInput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockOutput.java delete mode 100644 appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ZULU.java create mode 100644 appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java create mode 100644 appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/model/TestModelPOJO.java create mode 100644 appc-client/client-kit/src/test/java/org/onap/appc/generator/JsonHelper.java create mode 100644 appc-client/client-kit/src/test/java/org/onap/appc/generator/yang2json/Yang2JsonGeneratorTest.java delete mode 100644 appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java delete mode 100644 appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/model/TestModelPOJO.java delete mode 100644 appc-client/client-kit/src/test/java/org/openecomp/appc/generator/JsonHelper.java delete mode 100644 appc-client/client-kit/src/test/java/org/openecomp/appc/generator/yang2json/Yang2JsonGeneratorTest.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AbstractRequestResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AsyncRequestResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreException.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreManager.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreRegistry.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreAsyncResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreSyncResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/IInvocationManager.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimeoutHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimerService.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManager.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManagerFactory.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/MessageContext.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/RequestResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/SyncRequestResponseHandler.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueue.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueueManager.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TimerServiceImpl.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriter.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocol.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocolImpl.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Consumer.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ConsumerImpl.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageReader.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageWriter.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessagingService.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Producer.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProducerImpl.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Protocol.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolException.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolFactory.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolMessage.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolType.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/RetrieveMessageCallback.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBMessagingService.java create mode 100644 appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBPropertiesKeys.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AbstractRequestResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AsyncRequestResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreException.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreManager.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreRegistry.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreAsyncResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreSyncResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/IInvocationManager.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimeoutHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimerService.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManager.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManagerFactory.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/MessageContext.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/RequestResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/SyncRequestResponseHandler.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueue.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueueManager.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TimerServiceImpl.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriter.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocol.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocolImpl.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Consumer.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ConsumerImpl.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageReader.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageWriter.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessagingService.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Producer.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProducerImpl.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Protocol.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolException.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolFactory.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolMessage.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolType.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/RetrieveMessageCallback.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBMessagingService.java delete mode 100644 appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBPropertiesKeys.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/ResponseManagerTest.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/SyncFlowTest.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriterTest.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImpl.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java create mode 100644 appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestUEBMessagingService.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/ResponseManagerTest.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/SyncFlowTest.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriterTest.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImpl.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java delete mode 100644 appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestUEBMessagingService.java create mode 100644 appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/RequestHandler.java create mode 100644 appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/ResponseHandler.java create mode 100644 appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java create mode 100644 appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonResponseHandler.java create mode 100644 appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/main/ClientRunner.java delete mode 100644 appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/RequestHandler.java delete mode 100644 appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/ResponseHandler.java delete mode 100644 appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonRequestHandler.java delete mode 100644 appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonResponseHandler.java delete mode 100644 appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/main/ClientRunner.java create mode 100644 appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonRequestHandler.java create mode 100644 appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonResponseHandler.java create mode 100644 appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/main/TestClientRunner.java delete mode 100644 appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonRequestHandler.java delete mode 100644 appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonResponseHandler.java delete mode 100644 appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/main/TestClientRunner.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/CLI.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/ContextBuilder.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/MavenPlugin.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/JsonContextBuilderImpl.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/YangContextBuilderImpl.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/CodeGenWriter.java create mode 100644 appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/ModelGenerator.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/CLI.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/ContextBuilder.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/MavenPlugin.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/JsonContextBuilderImpl.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/YangContextBuilderImpl.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/CodeGenWriter.java delete mode 100644 appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/ModelGenerator.java create mode 100644 appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/api/CLITest.java create mode 100644 appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/impl/CodeGenWriterTest.java delete mode 100644 appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/api/CLITest.java delete mode 100644 appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/impl/CodeGenWriterTest.java create mode 100644 appc-common/src/main/java/org/onap/appc/CmdLine.java create mode 100644 appc-common/src/main/java/org/onap/appc/Constants.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/CacheStrategies.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/CacheStrategy.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/MetadataCache.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/impl/LRUCache.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheFactory.java create mode 100644 appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java create mode 100644 appc-common/src/main/java/org/onap/appc/concurrent/Signal.java create mode 100644 appc-common/src/main/java/org/onap/appc/configuration/Configuration.java create mode 100644 appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java create mode 100644 appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java create mode 100644 appc-common/src/main/java/org/onap/appc/configuration/package.html create mode 100644 appc-common/src/main/java/org/onap/appc/encryption/EncryptionException.java create mode 100644 appc-common/src/main/java/org/onap/appc/encryption/EncryptionTool.java create mode 100644 appc-common/src/main/java/org/onap/appc/encryption/HexHelper.java create mode 100644 appc-common/src/main/java/org/onap/appc/exceptions/APPCException.java create mode 100644 appc-common/src/main/java/org/onap/appc/exceptions/InvalidInputException.java create mode 100644 appc-common/src/main/java/org/onap/appc/exceptions/InvalidStateException.java create mode 100644 appc-common/src/main/java/org/onap/appc/exceptions/UnknownProviderException.java create mode 100644 appc-common/src/main/java/org/onap/appc/i18n/Msg.java create mode 100644 appc-common/src/main/java/org/onap/appc/logging/LoggingConstants.java create mode 100644 appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java create mode 100644 appc-common/src/main/java/org/onap/appc/metadata/MetadataService.java create mode 100644 appc-common/src/main/java/org/onap/appc/metadata/impl/MetadataServiceImpl.java create mode 100644 appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/Allocator.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/CacheManagement.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/CachedElement.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/Destructor.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/Pool.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/PoolDrainedException.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/PoolException.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/PoolExtensionException.java create mode 100644 appc-common/src/main/java/org/onap/appc/pool/PoolSpecificationException.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/JsonUtil.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/ObjectMapper.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/PathContext.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/StringHelper.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/StructuredPropertyHelper.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/Time.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/UnmodifiableProperties.java create mode 100644 appc-common/src/main/java/org/onap/appc/util/httpClient.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/CmdLine.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/Constants.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategies.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategy.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/MetadataCache.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/impl/LRUCache.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheFactory.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheImpl.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/concurrent/Signal.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/configuration/Configuration.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/configuration/ConfigurationFactory.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/configuration/package.html delete mode 100644 appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionTool.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/encryption/HexHelper.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/exceptions/APPCException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidInputException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidStateException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/exceptions/UnknownProviderException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/i18n/Msg.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/logging/LoggingConstants.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/logging/LoggingUtils.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/metadata/MetadataService.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/metadata/impl/MetadataServiceImpl.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifier.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/Allocator.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/CacheManagement.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/Destructor.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/Pool.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/PoolDrainedException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/PoolException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/PoolExtensionException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/pool/PoolSpecificationException.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/JsonUtil.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/MessageFormatter.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/ObjectMapper.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/PathContext.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/StringHelper.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/StructuredPropertyHelper.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/Time.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/UnmodifiableProperties.java delete mode 100644 appc-common/src/main/java/org/openecomp/appc/util/httpClient.java create mode 100644 appc-common/src/main/resources/org/onap/appc/i18n/MessageResources.properties create mode 100644 appc-common/src/main/resources/org/onap/appc/i18n/auth.properties create mode 100644 appc-common/src/main/resources/org/onap/appc/org.ops4j.pax.logging.cfg delete mode 100644 appc-common/src/main/resources/org/openecomp/appc/i18n/MessageResources.properties delete mode 100644 appc-common/src/main/resources/org/openecomp/appc/i18n/auth.properties delete mode 100644 appc-common/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg create mode 100644 appc-common/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/concurrent/TestSignal.java create mode 100644 appc-common/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/encryption/TestEncryption.java create mode 100644 appc-common/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/i18n/MsgTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/metadata/TestMetadataService.java create mode 100644 appc-common/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/pool/CachedElementTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/pool/Element.java create mode 100644 appc-common/src/test/java/org/onap/appc/pool/PoolTest.java create mode 100644 appc-common/src/test/java/org/onap/appc/pool/Testable.java create mode 100644 appc-common/src/test/java/org/onap/appc/util/TestJsonUtil.java create mode 100644 appc-common/src/test/java/org/onap/appc/util/TestStringHelper.java create mode 100644 appc-common/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/cache/CacheStrategiesTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/cache/impl/LRUCacheTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheFactoryTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheImplTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/concurrent/TestSignal.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/configuration/DefaultConfigurationTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/encryption/TestEncryption.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/exceptions/APPCExceptionTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidInputExceptionTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidStateExceptionTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/exceptions/UnknownProviderExceptionTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/i18n/MsgTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/logging/LoggingConstantsTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/metadata/TestMetadataService.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifierTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/pool/CachedElementTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/pool/Element.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/pool/PoolTest.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/pool/Testable.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/util/TestJsonUtil.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/util/TestStringHelper.java delete mode 100644 appc-common/src/test/java/org/openecomp/appc/util/TestStructuredPropertyHelper.java create mode 100644 appc-common/src/test/resources/org/onap/appc/i18n/TestAdditionalResources.properties create mode 100644 appc-common/src/test/resources/org/onap/appc/i18n/TestResources_de.properties create mode 100644 appc-common/src/test/resources/org/onap/appc/i18n/TestResources_en_US.properties delete mode 100644 appc-common/src/test/resources/org/openecomp/appc/i18n/TestAdditionalResources.properties delete mode 100644 appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_de.properties delete mode 100644 appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_en_US.properties create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/AppcDgUtilActivator.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/ExecuteNodeAction.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/InputParameterValidation.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/UpgradeStubNode.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImpl.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/InputParameterValidationImpl.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImpl.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/AppcDgUtilActivator.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/ExecuteNodeAction.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/InputParameterValidation.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/UpgradeStubNode.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImpl.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImpl.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImpl.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/AppcDgUtilActivatorTest.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImplTest.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/InputParameterValidationImplTest.java create mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImplTest.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/AppcDgUtilActivatorTest.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImplTest.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImplTest.java delete mode 100644 appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCheckConfigStatus.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCommonConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigurationDocumentRequest.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigure.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadCliConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadIsbcConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateTemplateConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetAaiInfo.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetConfigParams.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetDeviceRunningConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetVfModuleInfo.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestProcessParameterDefinition.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestPublishConfiguration.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSaveRunningConfig.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSetStatus.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestUpdateAaiInfo.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockAaiResource.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockConfigureNodeExecutor.java create mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCheckConfigStatus.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCommonConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigurationDocumentRequest.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigure.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadCliConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadIsbcConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateTemplateConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetAaiInfo.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetConfigParams.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetDeviceRunningConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetVfModuleInfo.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestProcessParameterDefinition.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestPublishConfiguration.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSaveRunningConfig.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSetStatus.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestUpdateAaiInfo.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockAaiResource.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockConfigureNodeExecutor.java delete mode 100644 appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java create mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGLoaderActivator.java create mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLActivate.java create mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLGenerator.java create mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoad.java create mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoadNActivate.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGLoaderActivator.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLActivate.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLGenerator.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoad.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoadNActivate.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/DGLoaderTest.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLActivate.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoad.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoadNActivate.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicDblibStore.java create mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicFactory.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/DGLoaderTest.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLActivate.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoad.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoadNActivate.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicDblibStore.java delete mode 100644 appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicFactory.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/CommandExecutor.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/UnstableVNFException.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/conv/Converter.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/CommandResponse.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/LCMCommandStatus.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/Params.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/UniqueRequestIdentifier.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/CommandExecutor.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/UnstableVNFException.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/conv/Converter.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/CommandResponse.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/LCMCommandStatus.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/Params.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/UniqueRequestIdentifier.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTaskFactory.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommonMethods.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/ExpiredMessageHandler.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMCommandTask.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMReadonlyCommandTask.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandExecutorImpl.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTask.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTaskFactory.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommonMethods.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/ExpiredMessageHandler.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMCommandTask.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMReadonlyCommandTask.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/CommandExecutionTaskTest.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/TestCommandExecutor.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutor.java create mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcJdbcConnectionFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DBUtils.java create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DefaultJdbcConnectionFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcConnectionFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcRuntimeException.java create mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/Messages.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/AppcJdbcConnectionFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DBUtils.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DefaultJdbcConnectionFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcConnectionFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcRuntimeException.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/Messages.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionIdentifiers.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionLevel.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/CommonHeader.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Flags.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/OperationType.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RequestContext.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ResponseContext.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RuntimeContext.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Status.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFContext.java create mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFOperation.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionIdentifiers.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/CommonHeader.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Flags.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/OperationType.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RequestContext.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ResponseContext.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RuntimeContext.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Status.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFContext.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFOperation.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/ExecutionQueueService.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/MessageExpirationListener.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/helper/Util.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceImpl.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/QueueManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/object/QueueMessage.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/ExecutionQueueService.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/MessageExpirationListener.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/helper/Util.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceImpl.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/QueueManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/object/QueueMessage.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/ExecutionQueueServiceTest.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Listener.java create mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Message.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/ExecutionQueueServiceTest.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Listener.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Message.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockException.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockRuntimeException.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockException.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockRuntimeException.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockValue.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/JdbcLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/Messages.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/MySqlConnectionFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/LockRecord.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/LockRecord.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/LockRecord.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/api/LockManagerBaseTests.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/Synchronizer.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/SynchronizerReceiver.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java create mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/api/LockManagerBaseTests.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/Synchronizer.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/SynchronizerReceiver.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/AbstractRankedAttributesResolverFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationEntry.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationSet.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesContext.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolver.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolverFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/BacktraceStrategy.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/CompositeNode.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Constants.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/LeafNode.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Node.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/NodeBase.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTree.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTreeBuilder.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Strategy.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Utils.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/AbstractRankedAttributesResolverFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationEntry.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationSet.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesContext.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolver.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolverFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/BacktraceStrategy.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/CompositeNode.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Constants.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/LeafNode.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Node.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/NodeBase.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTree.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTreeBuilder.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Strategy.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Utils.java create mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/onap/appc/rankingframework/TestRankingFramework.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/openecomp/appc/rankingframework/TestRankingFramework.java create mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/TransactionRecorder.java create mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java create mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/objects/TransactionRecord.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/TransactionRecorder.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/impl/TransactionRecorderImpl.java delete mode 100644 appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/objects/TransactionRecord.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/Constants.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseDataAccessService.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseManager.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/exception/DataAccessException.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/objects/LicenseModel.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/Constants.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseDataAccessService.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseManager.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/exception/DataAccessException.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/objects/LicenseModel.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseDataAccessServiceImpl.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseManagerImpl.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseDataAccessServiceImpl.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseManagerImpl.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerImplTest.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerMock.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerPluginImplTest.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseServiceMock.java create mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/TestVfLicenseModelConvert.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerImplTest.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerMock.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerPluginImplTest.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseServiceMock.java delete mode 100644 appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/TestVfLicenseModelConvert.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/message/RequestHandlerMessages.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/LCMStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/RequestHandler.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerInput.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerOutput.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/message/RequestHandlerMessages.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/LCMStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/RequestHandler.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerInput.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerOutput.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/WorkFlowManager.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowExistsOutput.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowRequest.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowResponse.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/WorkFlowManager.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowExistsOutput.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowRequest.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowResponse.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/common/constant/Constants.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowKey.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolver.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolverDataReader.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/common/constant/Constants.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkFlowManagerImpl.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowKey.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolver.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolverDataReader.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/TestWorkFlowManager.java delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/openecomp/appc/workflow/TestWorkFlowManager.java create mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AbstractListener.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AppcEventListenerActivator.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Controller.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/EventHandler.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/conv/Converter.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/ListenerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/WorkerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ActionIdentifiers.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/CommonHeader.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/InputBody.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/OutputBody.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ResponseStatus.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperations.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Listener.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/ListenerProperties.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ListenerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ProviderOperations.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/WorkerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Action.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/CommonMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/IncomingMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/OutgoingMessage.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Status.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/ControllerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/EventHandlerImpl.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/util/Mapper.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AbstractListener.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AppcEventListenerActivator.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Controller.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/EventHandler.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/conv/Converter.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/ListenerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/WorkerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ActionIdentifiers.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/CommonHeader.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapIncomingMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapOutgoingMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/InputBody.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/OutputBody.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ResponseStatus.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperations.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Listener.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/ListenerProperties.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ListenerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ProviderOperations.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/WorkerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Action.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/CommonMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/IncomingMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/OutgoingMessage.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Status.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/ControllerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/util/Mapper.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/TestConverter.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAbstractListener.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAppcDmaapListenerActivator.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestListenerProperties.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestEventHandler.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestListener.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM/TestConverter.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM1607/model/TestJsonGenericMessages.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAbstractListener.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAppcDmaapListenerActivator.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestListenerProperties.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestEnums.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestMessages.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestController.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestEventHandler.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestListener.java delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/util/TestMapper.java create mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-event-listener/appc-event-listener-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/ArtifactHandlerProvider.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/SdcArtifactHandlerActivator.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/dbservices/DBService.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNode.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/EscapeUtils.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/ArtifactHandlerProvider.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/SdcArtifactHandlerActivator.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/dbservices/DBService.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNode.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/EscapeUtils.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/DBServiceTest.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockDBService.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockSvcLogicResource.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNodeTest.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/MockArtifactHandlerNode.java create mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/DBServiceTest.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockDBService.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockSvcLogicResource.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNodeTest.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/MockArtifactHandlerNode.java delete mode 100644 appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/ArtifactInfo.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignInfo.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignRequest.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignResponse.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/StatusInfo.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbResponseProcessor.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbService.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DesignDBService.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/RequestValidator.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/propertyServices/PropertyUpdateService.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/DesignServiceProvider.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/impl/DesignServicesImpl.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/ArtifactHandlerClient.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/DesignServiceConstants.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/EscapeUtils.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/SecureRestClientTrustManager.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorResponseProcessor.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorService.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XInterfaceService.java create mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XResponseProcessor.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/ArtifactInfo.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignInfo.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignRequest.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignResponse.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/StatusInfo.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbResponseProcessor.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DesignDBService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/RequestValidator.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/propertyServices/PropertyUpdateService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/DesignServiceProvider.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/impl/DesignServicesImpl.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/ArtifactHandlerClient.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/DesignServiceConstants.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/EscapeUtils.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/SecureRestClientTrustManager.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorResponseProcessor.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XInterfaceService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XResponseProcessor.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestArifactHandlerClient.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDBService.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDbResponse.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDesigndata.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestEscapeUtils.java create mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestValidatorService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestArifactHandlerClient.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDBService.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDbResponse.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDesigndata.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestEscapeUtils.java delete mode 100644 appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestValidatorService.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/LifecycleManager.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LCMResponse.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LifecycleException.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/NoTransitionDefinedException.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/VNFOperationOutcome.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/LifecycleManager.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LCMResponse.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LifecycleException.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/NoTransitionDefinedException.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/VNFOperationOutcome.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/onap/appc/lifecyclemanager/impl/LifecycleManagerImpl.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/impl/LifecycleManagerImpl.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/LifecycleManagerTest.java create mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/OamLifeCycleManagerTest.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/LifecycleManagerTest.java delete mode 100644 appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/OamLifeCycleManagerTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMachine.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMetaDataReader.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineFactory.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineImpl.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReader.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamStates.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReader.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Event.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Response.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/State.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineMetadata.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineResponse.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Transition.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMachine.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMetaDataReader.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineFactory.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineImpl.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReader.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStates.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReader.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Event.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Response.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/State.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineMetadata.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineResponse.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Transition.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineFactoryTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineImplTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamStatesTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/EventTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/ResponseTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineMetadataTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineResponseTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateTest.java create mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/TransitionTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineFactoryTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineImplTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStatesTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/EventTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/ResponseTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineMetadataTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineResponseTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateTest.java delete mode 100644 appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/TransitionTest.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/MetricActivator.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricRegistry.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricService.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/Publisher.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricRegistryImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricServiceImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Counter.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFuntionMetric.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterBuilder.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterMetric.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Metric.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricBuilderFactory.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricType.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounter.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounterBuilder.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PolicyBuilderFactory.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PublishingPolicy.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPolicyBuilder.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPublishingPolicy.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/publisher/LogPublisher.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/MetricActivator.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricRegistry.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricService.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/Publisher.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricRegistryImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricServiceImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Counter.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFuntionMetric.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterBuilder.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterMetric.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Metric.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricBuilderFactory.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricType.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounter.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounterBuilder.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PolicyBuilderFactory.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PublishingPolicy.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPolicyBuilder.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPublishingPolicy.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/publisher/LogPublisher.java create mode 100644 appc-metric/appc-metric-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-metric/appc-metric-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-metric/appc-metric-bundle/src/test/java/org/onap/appc/metricservice/TestMetricServiceImpl.java delete mode 100644 appc-metric/appc-metric-bundle/src/test/java/org/openecomp/appc/metricservice/TestMetricServiceImpl.java create mode 100644 appc-metric/appc-metric-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-metric/appc-metric-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/AppcOam.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/OAMCommandStatus.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/Converter.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/DmaapOutgoingMessage.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/MessageAdapter.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/OAMContext.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseActionRunnable.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseCommon.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseProcessor.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamMmodeProcessor.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamRestartProcessor.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStartProcessor.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStopProcessor.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/AsyncTaskHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleFilter.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/ConfigurationHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/OperationHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/StateHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModule.java create mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModuleFactory.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModule.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModuleFactory.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/OAMCommandStatus.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/Converter.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/DmaapOutgoingMessage.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/MessageAdapter.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/OAMContext.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseActionRunnable.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseCommon.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamRestartProcessor.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStartProcessor.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStopProcessor.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleFilter.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleHelper.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/ConfigurationHelper.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/OperationHelper.java delete mode 100644 appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/StateHelper.java create mode 100644 appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/default.properties create mode 100644 appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/logback.xml delete mode 100644 appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/default.properties delete mode 100644 appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/logback.xml create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/ConfigurationHelperTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/OperationHelperTest.java create mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/StateHelperTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/OAMCommandStatusTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java delete mode 100644 appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java create mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientActivator.java create mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientConstant.java create mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/aai/AaiService.java create mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/node/AAIResourceNode.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientActivator.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientConstant.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/aai/AaiService.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/node/AAIResourceNode.java create mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/MockAaiService.java create mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/TestAaiService.java create mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/MockAaiService.java create mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/TestAAIResourceNode.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/MockAaiService.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/TestAaiService.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/MockAaiService.java delete mode 100644 appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/TestAAIResourceNode.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/InstarClientActivator.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/Dme2Client.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/SecureRestClientTrustManager.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarRestClientImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/ResponseHandlerInterface.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RestClientInterface.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RuleHandlerInterface.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/node/InstarClientNode.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/utils/InstarClientConstant.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/InstarClientActivator.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/Dme2Client.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/SecureRestClientTrustManager.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarRestClientImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/ResponseHandlerInterface.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RestClientInterface.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RuleHandlerInterface.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/node/InstarClientNode.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/utils/InstarClientConstant.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarRestClientImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestDme2Client.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestInstarClientNode.java create mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestSecureRestClientTrustManager.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarRestClientImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestDme2Client.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestInstarClientNode.java delete mode 100644 appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestSecureRestClientTrustManager.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProvider.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderClient.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderLcm.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/ResponseHeaderBuilder.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/LCMConstants.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/RequestInputBuilder.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/ValidationService.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/topology/TopologyService.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModule.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModuleFactory.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java create mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModule.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModuleFactory.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProvider.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderClient.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderLcm.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/ResponseHeaderBuilder.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/LCMConstants.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/RequestInputBuilder.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/ValidationService.java delete mode 100644 appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/topology/TopologyService.java create mode 100644 appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/default.properties create mode 100644 appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/logback.xml delete mode 100644 appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/default.properties delete mode 100644 appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/logback.xml create mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderClientTest.java create mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderLcmTest.java create mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderTest.java create mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/ResponseHeaderBuilderTest.java create mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/topology/TopologyServiceTest.java delete mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderClientTest.java delete mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderLcmTest.java delete mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderTest.java delete mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/ResponseHeaderBuilderTest.java delete mode 100644 appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/topology/TopologyServiceTest.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/ArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/ArtifactStorageService.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/Constants.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/DependencyModelGenerator.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/ArtifactType.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Resource.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCArtifact.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCReference.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Vnfc.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderOperations.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderResponse.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcCallback.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcConfig.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcListener.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/Util.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/tlv/sdc/security/Passwords.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcCallbackTest.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcListenerTest.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestObjects.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestUtils.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/TestRun.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestObjects.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestUtils.java delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/YANGGenerator.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/exception/YANGGenerationException.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorFactory.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorImpl.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/objects/Leaf.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/type/YangTypes.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/java/org/onap/appc/TestYANGGenerator.java delete mode 100644 appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/SequenceGenerator.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/SequenceGeneratorFactory.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StartSequenceGenerator.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StopSequenceGenerator.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/ActionIdentifier.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Constants.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/PreCheckOption.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfo.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfoBuilder.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Response.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInput.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInputBuilder.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Transaction.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/provider/SequenceGeneratorProvider.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/SequenceGenerator.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/SequenceGeneratorFactory.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StartSequenceGenerator.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StopSequenceGenerator.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/ActionIdentifier.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Constants.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/PreCheckOption.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfo.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfoBuilder.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Response.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInput.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInputBuilder.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Transaction.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/provider/SequenceGeneratorProvider.java create mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/onap/appc/seqgen/TestSequenceGeneratorPlugin.java delete mode 100644 appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/openecomp/appc/seqgen/TestSequenceGeneratorPlugin.java diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/RPC.java b/appc-client/client-kit/src/main/java/org/onap/appc/RPC.java new file mode 100644 index 000000000..2b2c5220a --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/RPC.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface RPC { + String name(); + Class outputType(); +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcClientServiceFactoryProvider.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcClientServiceFactoryProvider.java new file mode 100644 index 000000000..0ae23f19a --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcClientServiceFactoryProvider.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.api; + +import org.onap.appc.client.lcm.impl.business.AppcLifeCycleManagerServiceFactoryImpl; + +public class AppcClientServiceFactoryProvider { + + private static AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory; + + public static synchronized T getFactory(Class clazz) { + if (clazz.equals(AppcLifeCycleManagerServiceFactory.class)) { + if (appcLifeCycleManagerServiceFactory == null) { + appcLifeCycleManagerServiceFactory = new AppcLifeCycleManagerServiceFactoryImpl(); + } + return (T) appcLifeCycleManagerServiceFactory; + } else { + throw new IllegalArgumentException(clazz.getName()); + } + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java new file mode 100644 index 000000000..c0d2daa01 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.api; + +import org.onap.appc.client.lcm.exceptions.AppcClientException; + +import java.util.Properties; + +public interface AppcLifeCycleManagerServiceFactory { + + /** + * Creates a new stateful LCM API + * @param context application context parameters + * @param properties configures the behaviour of the LCM + * @return a new stateful LCM API + * @throws AppcClientException in case of problem in instantiation + */ + LifeCycleManagerStateful createLifeCycleManagerStateful(ApplicationContext context, Properties properties) throws AppcClientException; + + /** + * performs a shutdown of LCM API. + * in case of graceful, will try and execute the remaining requests, otherwise, will force the shutdown right away + * @param isForceShutdown - boolean. If true to perform force shutdown, other to perform graceful shutdown. + */ + void shutdownLifeCycleManager(boolean isForceShutdown); + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ApplicationContext.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ApplicationContext.java new file mode 100644 index 000000000..b0877ef55 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ApplicationContext.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.api; + +/** + * Created by gital on 11/27/2016. + */ +public class ApplicationContext { + + private String mechID; + private String applicationID; + + public String getMechID() { + return mechID; + } + + public void setMechID(String mechID) { + this.mechID = mechID; + } + + public String getApplicationID() { + return applicationID; + } + + public void setApplicationID(String applicationID) { + this.applicationID = applicationID; + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/LifeCycleManagerStateful.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/LifeCycleManagerStateful.java new file mode 100644 index 000000000..5600f137f --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/LifeCycleManagerStateful.java @@ -0,0 +1,901 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/* + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.api; + +import org.onap.appc.client.lcm.model.AuditOutput; +import org.onap.appc.client.lcm.model.AuditInput; +import org.onap.appc.client.lcm.model.CheckLockOutput; +import org.onap.appc.client.lcm.model.CheckLockInput; +import org.onap.appc.client.lcm.model.ConfigBackupOutput; +import org.onap.appc.client.lcm.model.ConfigBackupInput; +import org.onap.appc.client.lcm.model.ConfigBackupDeleteOutput; +import org.onap.appc.client.lcm.model.ConfigBackupDeleteInput; +import org.onap.appc.client.lcm.model.ConfigExportOutput; +import org.onap.appc.client.lcm.model.ConfigExportInput; +import org.onap.appc.client.lcm.model.ConfigModifyOutput; +import org.onap.appc.client.lcm.model.ConfigModifyInput; +import org.onap.appc.client.lcm.model.ConfigRestoreOutput; +import org.onap.appc.client.lcm.model.ConfigRestoreInput; +import org.onap.appc.client.lcm.model.ConfigScaleoutOutput; +import org.onap.appc.client.lcm.model.ConfigScaleoutInput; +import org.onap.appc.client.lcm.model.ConfigureOutput; +import org.onap.appc.client.lcm.model.ConfigureInput; +import org.onap.appc.client.lcm.model.EvacuateOutput; +import org.onap.appc.client.lcm.model.EvacuateInput; +import org.onap.appc.client.lcm.model.HealthCheckOutput; +import org.onap.appc.client.lcm.model.HealthCheckInput; +import org.onap.appc.client.lcm.model.LiveUpgradeOutput; +import org.onap.appc.client.lcm.model.LiveUpgradeInput; +import org.onap.appc.client.lcm.model.LockOutput; +import org.onap.appc.client.lcm.model.LockInput; +import org.onap.appc.client.lcm.model.MigrateOutput; +import org.onap.appc.client.lcm.model.MigrateInput; +import org.onap.appc.client.lcm.model.RebuildOutput; +import org.onap.appc.client.lcm.model.RebuildInput; +import org.onap.appc.client.lcm.model.RestartOutput; +import org.onap.appc.client.lcm.model.RestartInput; +import org.onap.appc.client.lcm.model.RollbackOutput; +import org.onap.appc.client.lcm.model.RollbackInput; +import org.onap.appc.client.lcm.model.SnapshotOutput; +import org.onap.appc.client.lcm.model.SnapshotInput; +import org.onap.appc.client.lcm.model.SoftwareUploadOutput; +import org.onap.appc.client.lcm.model.SoftwareUploadInput; +import org.onap.appc.client.lcm.model.StartOutput; +import org.onap.appc.client.lcm.model.StartInput; +import org.onap.appc.client.lcm.model.StopOutput; +import org.onap.appc.client.lcm.model.StopInput; +import org.onap.appc.client.lcm.model.SyncOutput; +import org.onap.appc.client.lcm.model.SyncInput; +import org.onap.appc.client.lcm.model.TerminateOutput; +import org.onap.appc.client.lcm.model.TerminateInput; +import org.onap.appc.client.lcm.model.TestOutput; +import org.onap.appc.client.lcm.model.TestInput; +import org.onap.appc.client.lcm.model.UnlockOutput; +import org.onap.appc.client.lcm.model.UnlockInput; +import org.onap.appc.RPC; +import org.onap.appc.client.lcm.exceptions.AppcClientException; + +/** + * Defines the services and request/response requirements for the ECOMP APP-C + * component. + */ +@javax.annotation.Generated(value = { + "templates/client-kit/open-api-to-java.ftl" }, date = "2017-05-04T20:09:01.723+05:30", comments = "Auto-generated from Open API specification") +public interface LifeCycleManagerStateful { + + /** + * The Audit command compares the configuration of the VNF associated with the + * current request against the configuration that is stored in APPC's + * configuration store. A successful Audit means that the current VNF + * configuration matches the APPC stored configuration. A failed Audit indicates + * that the request configuration is different from the stored configuration. + * This command can be applied to any VNF type. The only restriction is that a + * particular VNF should be able to support the interface for Reading + * Configuration using existing adapters and use the following protocols: CLI, + * RestConf and XML. The Audit action does not require any payload parameters + * + * @param auditInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "audit", outputType = AuditOutput.class) + AuditOutput audit(AuditInput auditInput) throws AppcClientException; + + /** + * The Audit command compares the configuration of the VNF associated with the + * current request against the configuration that is stored in APPC's + * configuration store. A successful Audit means that the current VNF + * configuration matches the APPC stored configuration. A failed Audit indicates + * that the request configuration is different from the stored configuration. + * This command can be applied to any VNF type. The only restriction is that a + * particular VNF should be able to support the interface for Reading + * Configuration using existing adapters and use the following protocols: CLI, + * RestConf and XML. The Audit action does not require any payload parameters + * + * @param auditInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "audit", outputType = AuditOutput.class) + void audit(AuditInput auditInput, ResponseHandler listener) throws AppcClientException; + + /** + * The CheckLock command returns true if the specified VNF is locked, false if + * not. A CheckLock command is deemed successful if the processing completes + * without error, whether the VNF is locked or not. The command returns only a + * single response with a final status. The APPC also locks the target VNF + * during any command processing, so a VNF can have a locked status even if no + * Lock command has been explicitly called. The CheckLock command returns a + * specific response structure that extends the default LCM response. The + * CheckLock action does not require any payload parameters + * + * @param checkLockInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "check-lock", outputType = CheckLockOutput.class) + CheckLockOutput checkLock(CheckLockInput checkLockInput) throws AppcClientException; + + /** + * The CheckLock command returns true if the specified VNF is locked, false if + * not. A CheckLock command is deemed successful if the processing completes + * without error, whether the VNF is locked or not. The command returns only a + * single response with a final status. The APPC also locks the target VNF + * during any command processing, so a VNF can have a locked status even if no + * Lock command has been explicitly called. The CheckLock command returns a + * specific response structure that extends the default LCM response. The + * CheckLock action does not require any payload parameters + * + * @param checkLockInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "check-lock", outputType = CheckLockOutput.class) + void checkLock(CheckLockInput checkLockInput, ResponseHandler listener) throws AppcClientException; + + /** + * An operation to Backup configurations of a virtual network function (or VM) + * + * @param configBackupInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-backup", outputType = ConfigBackupOutput.class) + ConfigBackupOutput configBackup(ConfigBackupInput configBackupInput) throws AppcClientException; + + /** + * An operation to Backup configurations of a virtual network function (or VM) + * + * @param configBackupInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-backup", outputType = ConfigBackupOutput.class) + void configBackup(ConfigBackupInput configBackupInput, ResponseHandler listener) + throws AppcClientException; + + /** + * An operation to Delete backup configurations of a virtual network function + * (or VM) + * + * @param configBackupDeleteInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-backup-delete", outputType = ConfigBackupDeleteOutput.class) + ConfigBackupDeleteOutput configBackupDelete(ConfigBackupDeleteInput configBackupDeleteInput) + throws AppcClientException; + + /** + * An operation to Delete backup configurations of a virtual network function + * (or VM) + * + * @param configBackupDeleteInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-backup-delete", outputType = ConfigBackupDeleteOutput.class) + void configBackupDelete(ConfigBackupDeleteInput configBackupDeleteInput, + ResponseHandler listener) throws AppcClientException; + + /** + * An operation to Export configurations of a virtual network function (or VM) + * + * @param configExportInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-export", outputType = ConfigExportOutput.class) + ConfigExportOutput configExport(ConfigExportInput configExportInput) throws AppcClientException; + + /** + * An operation to Export configurations of a virtual network function (or VM) + * + * @param configExportInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-export", outputType = ConfigExportOutput.class) + void configExport(ConfigExportInput configExportInput, ResponseHandler listener) + throws AppcClientException; + + /** + * Use the ModifyConfig command when a full configuration cycle is either not + * required or is considered too costly. The ModifyConfig LCM action affects + * only a subset of the total configuration data of a VNF. The set of + * configuration parameters to be affected is a subset of the total + * configuration data of the target VNF type. The payload block must contain the + * configuration parameters to be modified and their values. A successful modify + * returns a success response. A failed modify returns a failure response and + * the specific failure messages in the response payload block + * + * @param configModifyInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-modify", outputType = ConfigModifyOutput.class) + ConfigModifyOutput configModify(ConfigModifyInput configModifyInput) throws AppcClientException; + + /** + * Use the ModifyConfig command when a full configuration cycle is either not + * required or is considered too costly. The ModifyConfig LCM action affects + * only a subset of the total configuration data of a VNF. The set of + * configuration parameters to be affected is a subset of the total + * configuration data of the target VNF type. The payload block must contain the + * configuration parameters to be modified and their values. A successful modify + * returns a success response. A failed modify returns a failure response and + * the specific failure messages in the response payload block + * + * @param configModifyInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-modify", outputType = ConfigModifyOutput.class) + void configModify(ConfigModifyInput configModifyInput, ResponseHandler listener) + throws AppcClientException; + + /** + * An operation to restore the configurations of a virtual network function (or + * VM) + * + * @param configRestoreInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-restore", outputType = ConfigRestoreOutput.class) + ConfigRestoreOutput configRestore(ConfigRestoreInput configRestoreInput) throws AppcClientException; + + /** + * An operation to restore the configurations of a virtual network function (or + * VM) + * + * @param configRestoreInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-restore", outputType = ConfigRestoreOutput.class) + void configRestore(ConfigRestoreInput configRestoreInput, ResponseHandler listener) + throws AppcClientException; + + /** + * An operation to scaleout the configurations of a virtual network function (or + * VM) + * + * @param configScaleoutInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-scaleout", outputType = ConfigScaleoutOutput.class) + ConfigScaleoutOutput configScaleout(ConfigScaleoutInput configScaleoutInput) throws AppcClientException; + + /** + * An operation to scaleout the configurations of a virtual network function (or + * VM) + * + * @param configScaleoutInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "config-scaleout", outputType = ConfigScaleoutOutput.class) + void configScaleout(ConfigScaleoutInput configScaleoutInput, ResponseHandler listener) + throws AppcClientException; + + /** + * An operation to configure the configurations of a virtual network function + * (or VM) + * + * @param configureInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "configure", outputType = ConfigureOutput.class) + ConfigureOutput configure(ConfigureInput configureInput) throws AppcClientException; + + /** + * An operation to configure the configurations of a virtual network function + * (or VM) + * + * @param configureInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "configure", outputType = ConfigureOutput.class) + void configure(ConfigureInput configureInput, ResponseHandler listener) throws AppcClientException; + + /** + * An operation to evacuate a virtual network function (or VM) + * + * @param evacuateInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "evacuate", outputType = EvacuateOutput.class) + EvacuateOutput evacuate(EvacuateInput evacuateInput) throws AppcClientException; + + /** + * An operation to evacuate a virtual network function (or VM) + * + * @param evacuateInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "evacuate", outputType = EvacuateOutput.class) + void evacuate(EvacuateInput evacuateInput, ResponseHandler listener) throws AppcClientException; + + /** + * This command runs a VNF health check and returns the result. A health check + * is VNF-specific. For a complex VNF, APPC initiates further subordinate health + * checks + * + * @param healthCheckInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "health-check", outputType = HealthCheckOutput.class) + HealthCheckOutput healthCheck(HealthCheckInput healthCheckInput) throws AppcClientException; + + /** + * This command runs a VNF health check and returns the result. A health check + * is VNF-specific. For a complex VNF, APPC initiates further subordinate health + * checks + * + * @param healthCheckInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "health-check", outputType = HealthCheckOutput.class) + void healthCheck(HealthCheckInput healthCheckInput, ResponseHandler listener) + throws AppcClientException; + + /** + * The LiveUpgrade LCM action upgrades the target VNF to a new version without + * interrupting VNF operation. A successful upgrade returns a success status. A + * failed upgrade returns a failure code and the failure messages in the + * response payload block. The payload includes the IP of the location that + * hosts the new software version installer file and the new software version. + * Connections or operations that are active at the time of the LiveUpgrade + * action request will not be interrupted by the action and, therefore, the + * action may take a significant amount of time to run. A LiveUpgrade is defined + * as non-disruptive; it is the responsibility of the VNF to handle disruptions + * if they occur + * + * @param liveUpgradeInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "live-upgrade", outputType = LiveUpgradeOutput.class) + LiveUpgradeOutput liveUpgrade(LiveUpgradeInput liveUpgradeInput) throws AppcClientException; + + /** + * The LiveUpgrade LCM action upgrades the target VNF to a new version without + * interrupting VNF operation. A successful upgrade returns a success status. A + * failed upgrade returns a failure code and the failure messages in the + * response payload block. The payload includes the IP of the location that + * hosts the new software version installer file and the new software version. + * Connections or operations that are active at the time of the LiveUpgrade + * action request will not be interrupted by the action and, therefore, the + * action may take a significant amount of time to run. A LiveUpgrade is defined + * as non-disruptive; it is the responsibility of the VNF to handle disruptions + * if they occur + * + * @param liveUpgradeInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "live-upgrade", outputType = LiveUpgradeOutput.class) + void liveUpgrade(LiveUpgradeInput liveUpgradeInput, ResponseHandler listener) + throws AppcClientException; + + /** + * Use the Lock command to ensure exclusive access during a series of critical + * LCM commands. The Lock action will return a successful result if the VNF is + * not already locked or if it was locked with the same request-id, otherwise + * the action returns a response with a reject status code. When a VNF is + * locked, any subsequent sequential commands with same request-id will be + * accepted. Commands associated with other request-ids will be rejected. The + * Lock command returns only one final response with the status of the request + * processing. The APPC also locks the target VNF during any command processing. + * If a lock action is then requested on that VNF, it will be rejected because + * the VNF was already locked, even though no actual lock command was explicitly + * invoked + * + * @param lockInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "lock", outputType = LockOutput.class) + LockOutput lock(LockInput lockInput) throws AppcClientException; + + /** + * Use the Lock command to ensure exclusive access during a series of critical + * LCM commands. The Lock action will return a successful result if the VNF is + * not already locked or if it was locked with the same request-id, otherwise + * the action returns a response with a reject status code. When a VNF is + * locked, any subsequent sequential commands with same request-id will be + * accepted. Commands associated with other request-ids will be rejected. The + * Lock command returns only one final response with the status of the request + * processing. The APPC also locks the target VNF during any command processing. + * If a lock action is then requested on that VNF, it will be rejected because + * the VNF was already locked, even though no actual lock command was explicitly + * invoked + * + * @param lockInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "lock", outputType = LockOutput.class) + void lock(LockInput lockInput, ResponseHandler listener) throws AppcClientException; + + /** + * Migrates a running target VFC from its current AIC host to another. A + * destination AIC node will be selected by relying on AIC internal rules to + * migrate. A successful Migrate action returns a success response and the new + * AIC node identity in the response payload block. A failed Migrate action + * returns a failure and the failure messages in the response payload block + * + * @param migrateInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "migrate", outputType = MigrateOutput.class) + MigrateOutput migrate(MigrateInput migrateInput) throws AppcClientException; + + /** + * Migrates a running target VFC from its current AIC host to another. A + * destination AIC node will be selected by relying on AIC internal rules to + * migrate. A successful Migrate action returns a success response and the new + * AIC node identity in the response payload block. A failed Migrate action + * returns a failure and the failure messages in the response payload block + * + * @param migrateInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "migrate", outputType = MigrateOutput.class) + void migrate(MigrateInput migrateInput, ResponseHandler listener) throws AppcClientException; + + /** + * Recreates a target VFC instance to a known, stable state. A successful + * rebuild returns a success response and the rebuild details in the response + * payload block. A failed rebuild returns a failure and the failure messages in + * the response payload block + * + * @param rebuildInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "rebuild", outputType = RebuildOutput.class) + RebuildOutput rebuild(RebuildInput rebuildInput) throws AppcClientException; + + /** + * Recreates a target VFC instance to a known, stable state. A successful + * rebuild returns a success response and the rebuild details in the response + * payload block. A failed rebuild returns a failure and the failure messages in + * the response payload block + * + * @param rebuildInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "rebuild", outputType = RebuildOutput.class) + void rebuild(RebuildInput rebuildInput, ResponseHandler listener) throws AppcClientException; + + /** + * An operation to restart a virtual network function (or VM) + * + * @param restartInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "restart", outputType = RestartOutput.class) + RestartOutput restart(RestartInput restartInput) throws AppcClientException; + + /** + * An operation to restart a virtual network function (or VM) + * + * @param restartInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "restart", outputType = RestartOutput.class) + void restart(RestartInput restartInput, ResponseHandler listener) throws AppcClientException; + + /** + * Sets a VNF to the previous version of the configuration without explicitly + * invoking the configuration set name. This command is used when the + * configuration was successful, but the health-check was not. A successful + * rollback returns a success status when the restart process has completed. A + * failed or a partially failed (for a complex VNF) rollback returns a failure + * and the failure messages in the response payload block. This command can be + * applied to any VNF type. The only restriction is that the particular VNF + * should be built based on the generic heap stack + * + * @param rollbackInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "rollback", outputType = RollbackOutput.class) + RollbackOutput rollback(RollbackInput rollbackInput) throws AppcClientException; + + /** + * Sets a VNF to the previous version of the configuration without explicitly + * invoking the configuration set name. This command is used when the + * configuration was successful, but the health-check was not. A successful + * rollback returns a success status when the restart process has completed. A + * failed or a partially failed (for a complex VNF) rollback returns a failure + * and the failure messages in the response payload block. This command can be + * applied to any VNF type. The only restriction is that the particular VNF + * should be built based on the generic heap stack + * + * @param rollbackInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "rollback", outputType = RollbackOutput.class) + void rollback(RollbackInput rollbackInput, ResponseHandler listener) throws AppcClientException; + + /** + * Creates a snapshot of a VNF, or VM. The Snapshot command returns a customized + * response containing a reference to the newly created snapshot instance if the + * action is successful. This command can be applied to any VNF type. The only + * restriction is that the particular VNF should be built based on the generic + * heap stack + * + * @param snapshotInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "snapshot", outputType = SnapshotOutput.class) + SnapshotOutput snapshot(SnapshotInput snapshotInput) throws AppcClientException; + + /** + * Creates a snapshot of a VNF, or VM. The Snapshot command returns a customized + * response containing a reference to the newly created snapshot instance if the + * action is successful. This command can be applied to any VNF type. The only + * restriction is that the particular VNF should be built based on the generic + * heap stack + * + * @param snapshotInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "snapshot", outputType = SnapshotOutput.class) + void snapshot(SnapshotInput snapshotInput, ResponseHandler listener) throws AppcClientException; + + /** + * This LCM command uploads the file that contains a new software version to the + * target VNF + * + * @param softwareUploadInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "software-upload", outputType = SoftwareUploadOutput.class) + SoftwareUploadOutput softwareUpload(SoftwareUploadInput softwareUploadInput) throws AppcClientException; + + /** + * This LCM command uploads the file that contains a new software version to the + * target VNF + * + * @param softwareUploadInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "software-upload", outputType = SoftwareUploadOutput.class) + void softwareUpload(SoftwareUploadInput softwareUploadInput, ResponseHandler listener) + throws AppcClientException; + + /** + * An operation to start a virtual network function (or VM) + * + * @param startInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "start", outputType = StartOutput.class) + StartOutput start(StartInput startInput) throws AppcClientException; + + /** + * An operation to start a virtual network function (or VM) + * + * @param startInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "start", outputType = StartOutput.class) + void start(StartInput startInput, ResponseHandler listener) throws AppcClientException; + + /** + * Stop a target VNF or VNFC. A successful stop returns a success response. For + * a multi-component stop to be considered successful, all component stop + * actions must succeed. A failed stop returns a failure and the failure + * messages in the response payload block + * + * @param stopInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "stop", outputType = StopOutput.class) + StopOutput stop(StopInput stopInput) throws AppcClientException; + + /** + * Stop a target VNF or VNFC. A successful stop returns a success response. For + * a multi-component stop to be considered successful, all component stop + * actions must succeed. A failed stop returns a failure and the failure + * messages in the response payload block + * + * @param stopInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "stop", outputType = StopOutput.class) + void stop(StopInput stopInput, ResponseHandler listener) throws AppcClientException; + + /** + * The Sync action updates the current configuration in the APPC store with the + * running configuration from the device. A successful Sync returns a success + * status. A failed Sync returns a failure response status and failure messages + * in the response payload block. This command can be applied to any VNF type. + * The only restriction is that a particular VNF should be able to support the + * interface for Reading Configuration using existing adapters and use the + * following protocols: CLI, RestConf and XML + * + * @param syncInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "sync", outputType = SyncOutput.class) + SyncOutput sync(SyncInput syncInput) throws AppcClientException; + + /** + * The Sync action updates the current configuration in the APPC store with the + * running configuration from the device. A successful Sync returns a success + * status. A failed Sync returns a failure response status and failure messages + * in the response payload block. This command can be applied to any VNF type. + * The only restriction is that a particular VNF should be able to support the + * interface for Reading Configuration using existing adapters and use the + * following protocols: CLI, RestConf and XML + * + * @param syncInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "sync", outputType = SyncOutput.class) + void sync(SyncInput syncInput, ResponseHandler listener) throws AppcClientException; + + /** + * Terminate a target VNF and release its resources (possibly gracefully). + * Specific scripts can be run before termination by placing them under the + * Terminate life cycle event. All configuration files related to the target VNF + * are deleted. The resources of a terminated VNF that are not managed by APPC, + * such as those handled by SDNC or other components, are not handled and remain + * the responsibility of their respective managing functions. A successful + * Terminate action returns a success response. For a multi-component terminate + * to be considered successful, all component Terminate actions must also + * succeed. A failed Terminate returns a failure status and the failure messages + * in the response payload block + * + * @param terminateInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "terminate", outputType = TerminateOutput.class) + TerminateOutput terminate(TerminateInput terminateInput) throws AppcClientException; + + /** + * Terminate a target VNF and release its resources (possibly gracefully). + * Specific scripts can be run before termination by placing them under the + * Terminate life cycle event. All configuration files related to the target VNF + * are deleted. The resources of a terminated VNF that are not managed by APPC, + * such as those handled by SDNC or other components, are not handled and remain + * the responsibility of their respective managing functions. A successful + * Terminate action returns a success response. For a multi-component terminate + * to be considered successful, all component Terminate actions must also + * succeed. A failed Terminate returns a failure status and the failure messages + * in the response payload block + * + * @param terminateInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "terminate", outputType = TerminateOutput.class) + void terminate(TerminateInput terminateInput, ResponseHandler listener) throws AppcClientException; + + /** + * The Test LCM action checks a target VNF or VNFC for correct operation. The + * functionality of the Test LCM action involves should involve more than a + * HealthCheck , it should provide a means for launching a test transaction and + * determining if the transaction completed successfully or not. A transaction + * launcher microservice will have to be supplied by the VNF and called by APPC. + * A successful test returns a success and the results of the test in the + * payload block. A failed test returns a failure and specific failure messages + * in the payload block + * + * @param testInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "test", outputType = TestOutput.class) + TestOutput test(TestInput testInput) throws AppcClientException; + + /** + * The Test LCM action checks a target VNF or VNFC for correct operation. The + * functionality of the Test LCM action involves should involve more than a + * HealthCheck , it should provide a means for launching a test transaction and + * determining if the transaction completed successfully or not. A transaction + * launcher microservice will have to be supplied by the VNF and called by APPC. + * A successful test returns a success and the results of the test in the + * payload block. A failed test returns a failure and specific failure messages + * in the payload block + * + * @param testInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "test", outputType = TestOutput.class) + void test(TestInput testInput, ResponseHandler listener) throws AppcClientException; + + /** + * Run the Unlock command to release the lock on a VNF and allow other clients + * to perform LCM commands on that VNF. The Unlock command will result in + * success if the VNF successfully unlocked or if it was already unlocked, + * otherwise commands will be rejected. The Unlock command will only return + * success if the VNF was locked with same request-id (on page 6). The Unlock + * command returns only one final response with the status of the request + * processing. The APPC also locks the target VNF during any command processing. + * If an Unlock action is then requested on that VNF with a different + * request-id, it will be rejected because the VNF is already locked for another + * process, even though no actual lock command was explicitly invoked + * + * @param unlockInput + * - RPC input object + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "unlock", outputType = UnlockOutput.class) + UnlockOutput unlock(UnlockInput unlockInput) throws AppcClientException; + + /** + * Run the Unlock command to release the lock on a VNF and allow other clients + * to perform LCM commands on that VNF. The Unlock command will result in + * success if the VNF successfully unlocked or if it was already unlocked, + * otherwise commands will be rejected. The Unlock command will only return + * success if the VNF was locked with same request-id (on page 6). The Unlock + * command returns only one final response with the status of the request + * processing. The APPC also locks the target VNF during any command processing. + * If an Unlock action is then requested on that VNF with a different + * request-id, it will be rejected because the VNF is already locked for another + * process, even though no actual lock command was explicitly invoked + * + * @param unlockInput + * - RPC input object + * @param listener + * - callback implementation + * @throws AppcClientException + * - throw AppcClientException + */ + @RPC(name = "unlock", outputType = UnlockOutput.class) + void unlock(UnlockInput unlockInput, ResponseHandler listener) throws AppcClientException; + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ResponseHandler.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ResponseHandler.java new file mode 100644 index 000000000..68459925f --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/api/ResponseHandler.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.api; + +import org.onap.appc.client.lcm.exceptions.AppcClientException; + +public interface ResponseHandler { + + /** + * Handler to react when a response arrives + * @param response the response output object + */ + void onResponse(T response); + + /** + * Handler to react when an exception arrives instead of a response + * @param exception detailed with type of exception + */ + void onException(AppcClientException exception); +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientBusinessException.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientBusinessException.java new file mode 100644 index 000000000..7d91f39e5 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientBusinessException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.exceptions; + +public class AppcClientBusinessException extends AppcClientException { + + public AppcClientBusinessException() { + super(); + } + + public AppcClientBusinessException(String message) { + super(message); + } + + public AppcClientBusinessException(String message, Throwable cause) { + super(message, cause); + } + + public AppcClientBusinessException(Throwable cause) { + super(cause); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientException.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientException.java new file mode 100644 index 000000000..c72f6150e --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.exceptions; + +public class AppcClientException extends Exception { + + public AppcClientException() { + super(); + } + + public AppcClientException(String message) { + super(message); + } + + public AppcClientException(String message, Throwable cause) { + super(message, cause); + } + + public AppcClientException(Throwable cause) { + super(cause); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientInternalException.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientInternalException.java new file mode 100644 index 000000000..9b6dfed7b --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/exceptions/AppcClientInternalException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.exceptions; + +public class AppcClientInternalException extends AppcClientException { + + public AppcClientInternalException() { + super(); + } + + public AppcClientInternalException(String message) { + super(message); + } + + public AppcClientInternalException(String message, Throwable cause) { + super(message, cause); + } + + public AppcClientInternalException(Throwable cause) { + super(cause); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java new file mode 100644 index 000000000..b8ab36bbe --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; +import org.onap.appc.client.lcm.api.ApplicationContext; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.exceptions.AppcClientException; + +import java.lang.reflect.Proxy; +import java.util.Properties; + +public class AppcLifeCycleManagerServiceFactoryImpl implements AppcLifeCycleManagerServiceFactory { + + private LifeCycleManagerStateful lifeCycleManagerStateful; + private LCMRequestProcessor lcmRequestProcessor; + + @Override + public synchronized LifeCycleManagerStateful createLifeCycleManagerStateful(ApplicationContext context, Properties properties) throws AppcClientException{ + if (lifeCycleManagerStateful == null) { + lcmRequestProcessor = new LCMRequestProcessor(context, properties); + lifeCycleManagerStateful = (LifeCycleManagerStateful) Proxy.newProxyInstance(LifeCycleManagerStateful.class.getClassLoader(), new Class[]{LifeCycleManagerStateful.class}, new RPCInvocator(lcmRequestProcessor)); + } + else { + throw new IllegalStateException("already instansiated LifeCycleManagerStateful instance"); + } + return lifeCycleManagerStateful; + } + + @Override + public void shutdownLifeCycleManager(boolean isForceShutdown) { + if(lcmRequestProcessor != null){ + lcmRequestProcessor.shutdown(isForceShutdown); + } + else{ + throw new IllegalStateException("The life cycle manager library wasn't instantiated properly, therefore the shutdown event will not be handled"); + } + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java new file mode 100644 index 000000000..96e21d8f8 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.client.impl.core.CoreException; +import org.onap.appc.client.impl.core.ICoreAsyncResponseHandler; +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import com.fasterxml.jackson.databind.ObjectMapper; + +class CoreAsyncResponseHandlerImpl extends CoreResponseHandler implements ICoreAsyncResponseHandler { + + private final ResponseHandler responseHandler; + + CoreAsyncResponseHandlerImpl(ResponseHandler responseHandler, Class rpcOutput, ObjectMapper mapper) { + super(rpcOutput, mapper); + this.responseHandler = responseHandler; + } + + public boolean onResponse(String message, String type) { + Boolean[] isFinal = new Boolean[1]; + isFinal[0] = false; + try { + T responseObject = (T) super.getResponse(message, type, isFinal); + responseHandler.onResponse(responseObject); + return isFinal[0]; + } catch (Exception e) { + this.onException(e); + isFinal[0] = true; + } + return isFinal[0]; + } + + public void onException(Exception e) { + AppcClientException ex = new AppcClientException(e); + responseHandler.onException(ex); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreResponseHandler.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreResponseHandler.java new file mode 100644 index 000000000..3d4786862 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreResponseHandler.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; + +import org.onap.appc.client.lcm.model.Status; +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 java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +class CoreResponseHandler { + private final Class rpcOutput; + private final ObjectMapper mapper; + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(CoreResponseHandler.class); + + CoreResponseHandler(Class rpcOutput, ObjectMapper mapper) { + this.rpcOutput = rpcOutput; + this.mapper = mapper; + } + + T getResponse(String message, String type, Boolean[] isFinal) throws AppcClientInternalException { + if (type.equals("error")) { + try { + String correlationId = getCorrelationID(message); + LOG.error("Received response with error on correlation id: " + correlationId); + } catch (IOException e) { + LOG.error("Received response with error and couldn't extract correlationID"); + } + throw new AppcClientInternalException(message); + } + T responseObject = jsonToResponseObject(message); + int code = getStatusCode(responseObject); + + int family = code / 100; + + switch (family) { + case 1: + case 5: + // not final + break; + case 2: + case 3: + case 4: + isFinal[0] = true; + // final + break; + default: // Should never happen + throw new AppcClientInternalException(new IllegalStateException("Unsupported status code " + code + ". message: " + message)); + } + return responseObject; + + } + + private T jsonToResponseObject(String message) throws AppcClientInternalException { + try { + JsonNode jsonOutput = mapper.readTree(message).get("output"); + return rpcOutput.cast(mapper.treeToValue(jsonOutput, rpcOutput)); + } catch (IOException e) { + throw new AppcClientInternalException("failed to read message: " + message, e); + } + } + + private int getStatusCode(Object response) throws AppcClientInternalException { + try { + Method method = response.getClass().getMethod("getStatus"); + Status status = (Status) method.invoke(response); + return status.getCode(); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new AppcClientInternalException("failed to get status code from response: " + response, e); + } + } + + private String getCorrelationID(String message) throws IOException { + JsonNode common = mapper.readTree(message).get("output").get("common-header"); + String correlationId = common.get("request-id").asText() + "-" + common.get("sub-request-id").asText(); + return correlationId; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java new file mode 100644 index 000000000..66da8fbe2 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.client.impl.core.CoreException; +import org.onap.appc.client.impl.core.ICoreSyncResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; +import com.fasterxml.jackson.databind.ObjectMapper; + +class CoreSyncResponseHandlerImpl extends CoreResponseHandler implements ICoreSyncResponseHandler { + + CoreSyncResponseHandlerImpl(Class rpcOutput, ObjectMapper mapper) { + super(rpcOutput, mapper); + } + + public T onResponse(String message, String type) throws CoreException { + Boolean[] isFinal = new Boolean[1]; + isFinal[0] = false; + T responseObject = null; + try { + responseObject = (T) super.getResponse(message, type, isFinal); + responseObject = (isFinal[0]) ? responseObject : null; + } catch (AppcClientInternalException e) { + throw new CoreException(e); + } + + return responseObject; + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/LCMRequestProcessor.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/LCMRequestProcessor.java new file mode 100644 index 000000000..b718c1ac9 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/LCMRequestProcessor.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.client.impl.core.*; +import org.onap.appc.client.lcm.api.ApplicationContext; +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientBusinessException; +import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; +import org.onap.appc.client.lcm.model.CommonHeader; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Properties; +import java.util.concurrent.TimeoutException; + +class LCMRequestProcessor { + + private final IInvocationManager invocationManager; + private final ObjectMapper mapper; + + LCMRequestProcessor(ApplicationContext context, Properties properties) throws AppcClientBusinessException { + try{ + invocationManager = InvocationManagerFactory.getInstance(); + invocationManager.init(properties); + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } catch (CoreException e) { + throw new AppcClientBusinessException(e); + } + } + + void processAsync(Object rpcInput, String rpcName, Class rpcOutputType, ResponseHandler handler) throws AppcClientInternalException { + try { + String correlationID = createCorrelationID(rpcInput); + String rpcStr = marshallRPCInput(rpcInput); + ICoreAsyncResponseHandler asyncResponseHandler = new CoreAsyncResponseHandlerImpl(handler, rpcOutputType, mapper); + invocationManager.asyncRequest(rpcStr, asyncResponseHandler, correlationID, rpcName); + } catch (CoreException e) { + throw new AppcClientInternalException(e); + } + } + + T processSync(Object rpcInput, String rpcName, Class rpcOutputType) throws AppcClientInternalException, AppcClientBusinessException { + T response = null; + try { + String correlationID = createCorrelationID(rpcInput); + String rpcStr = marshallRPCInput(rpcInput); + ICoreSyncResponseHandler syncResponseHandler = new CoreSyncResponseHandlerImpl(rpcOutputType, mapper); + response = invocationManager.syncRequest(rpcStr, syncResponseHandler, correlationID, rpcName); + }catch (CoreException e){ + if (e.getCause() instanceof AppcClientInternalException) { + throw (AppcClientInternalException) e.getCause(); + } + else { + throw new AppcClientInternalException(e); + } + }catch (TimeoutException e){ + throw new AppcClientBusinessException(e); + } + return response; + } + + private CommonHeader getCommonHeader(Object rpcInput) throws AppcClientInternalException { + try { + Class clazz = rpcInput.getClass(); + Method method = clazz.getMethod("getCommonHeader"); + return CommonHeader.class.cast(method.invoke(rpcInput)); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new AppcClientInternalException("can't get commonHeader"); + } + } + + private String createCorrelationID(Object rpcInput) throws AppcClientInternalException { + CommonHeader commonHeader = getCommonHeader(rpcInput); + return commonHeader.getRequestId() + "-" + commonHeader.getSubRequestId(); + } + + private String marshallRPCInput(Object rpcInput) throws AppcClientInternalException { + try { + JsonNode body = mapper.valueToTree(rpcInput); + ObjectNode message = mapper.createObjectNode(); + message.set("input", body); + return message.toString(); + } catch (RuntimeException e) { + throw new AppcClientInternalException("can't marshall input", e); + } + } + + void shutdown(boolean isForceShutdown){ + invocationManager.shutdown(isForceShutdown); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/RPCInvocator.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/RPCInvocator.java new file mode 100644 index 000000000..525700d62 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/impl/business/RPCInvocator.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.lcm.impl.business; + +import org.onap.appc.RPC; +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientBusinessException; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +class RPCInvocator implements InvocationHandler { + + private final LCMRequestProcessor lcmRequestProcessor; + + RPCInvocator(LCMRequestProcessor lcmRequestProcessor) { + this.lcmRequestProcessor = lcmRequestProcessor; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (isLCMRequest(method)) { + try { + return invokeImpl(method, args); + } + catch (AppcClientInternalException | AppcClientBusinessException e) { + throw new AppcClientException(e); + } + } else { + // Delegate non-RPC Object's methods (hashCode/equals/etc) to the proxy instance itself + return method.invoke(proxy, args); + } + } + + private T invokeImpl(Method method, Object[] args) throws AppcClientInternalException, AppcClientBusinessException { + Object rpcInput = args[0]; + RPC annotation = method.getAnnotation(RPC.class); + String rpcName = annotation.name(); + @SuppressWarnings("unchecked") + Class rpcOutputType = (Class) annotation.outputType(); + + T result = null; + if (isAsync(method)) { + @SuppressWarnings("unchecked") + ResponseHandler handler = (ResponseHandler) args[1]; + lcmRequestProcessor.processAsync(rpcInput, rpcName, rpcOutputType, handler); + } + else { + result = lcmRequestProcessor.processSync(rpcInput, rpcName, rpcOutputType); + } + return result; + } + + private boolean isLCMRequest(Method method) { + return method.isAnnotationPresent(RPC.class); + } + + private boolean isAsync(Method method) { + return method.getReturnType().equals(Void.TYPE); + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Action.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Action.java new file mode 100644 index 000000000..d43a61c92 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Action.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** +* The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate +* +*/ +public enum Action { + + Restart("Restart"), + Rebuild("Rebuild"), + Migrate("Migrate"), + Evacuate("Evacuate"), + Snapshot("Snapshot"), + Rollback("Rollback"), + Sync("Sync"), + Audit("Audit"), + Stop("Stop"), + Start("Start"), + Terminate("Terminate"), + SoftwareUpload("SoftwareUpload"), + HealthCheck("HealthCheck"), + LiveUpgrade("LiveUpgrade"), + Lock("Lock"), + Unlock("Unlock"), + Test("Test"), + CheckLock("CheckLock"), + Configure("Configure"), + ConfigModify("ConfigModify"), + ConfigScaleOut("ConfigScaleOut"), + ConfigRestore("ConfigRestore"), + ConfigBackup("ConfigBackup"), + ConfigBackupDelete("ConfigBackupDelete"), + ConfigExport("ConfigExport"); + + private String value; + + Action(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static Action fromValue(String text) { + for (Action var : Action.values()) { + if (String.valueOf(var.value).equals(text)) { + return var; + } + } + return null; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ActionIdentifiers.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ActionIdentifiers.java new file mode 100644 index 000000000..bff2c44cb --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ActionIdentifiers.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.501+05:30", + comments = "Auto-generated from Open API specification") +public class ActionIdentifiers { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + + @JsonProperty("vnf-id") + private String vnfId; + + @JsonProperty("vnfc-name") + private String vnfcName; + + @JsonProperty("vserver-id") + private String vserverId; + + /** + * identifies a specific service the command refers to. When multiple APP-C instances are used and applied to a subset of services, this will become significant . The field is mandatory when the vnf-id is empty + */ + public String getServiceInstanceId() { + return serviceInstanceId; + } + + /** + * identifies a specific service the command refers to. When multiple APP-C instances are used and applied to a subset of services, this will become significant . The field is mandatory when the vnf-id is empty + */ + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + /** + * identifies the VNF to which this action is to be applied(vnf-id uniquely identifies the service-instance referred to). Note that some actions are applied to multiple VNFs in the same service. When this is the case, vnf-id may be left out, but service-instance-id must appear. The field is mandatory when service-instance-id is empty + */ + public String getVnfId() { + return vnfId; + } + + /** + * identifies the VNF to which this action is to be applied(vnf-id uniquely identifies the service-instance referred to). Note that some actions are applied to multiple VNFs in the same service. When this is the case, vnf-id may be left out, but service-instance-id must appear. The field is mandatory when service-instance-id is empty + */ + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + /** + * identifies the VNFC to which this action is to be applied. Some actions apply only to a component within a VNF (e.g. RESTART is sometimes applied to on VM only). In such a case, the name of the VNFC is used to search for the component within the VNF + */ + public String getVnfcName() { + return vnfcName; + } + + /** + * identifies the VNFC to which this action is to be applied. Some actions apply only to a component within a VNF (e.g. RESTART is sometimes applied to on VM only). In such a case, the name of the VNFC is used to search for the component within the VNF + */ + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + /** + * identifies a specific VM within the given service/vnf to which this action is to be applied + */ + public String getVserverId() { + return vserverId; + } + + /** + * identifies a specific VM within the given service/vnf to which this action is to be applied + */ + public void setVserverId(String vserverId) { + this.vserverId = vserverId; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditInput.java new file mode 100644 index 000000000..2301913a9 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.512+05:30", + comments = "Auto-generated from Open API specification") +public class AuditInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditOutput.java new file mode 100644 index 000000000..00f4244ba --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/AuditOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.517+05:30", + comments = "Auto-generated from Open API specification") +public class AuditOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockInput.java new file mode 100644 index 000000000..840aad615 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockInput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.519+05:30", + comments = "Auto-generated from Open API specification") +public class CheckLockInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockOutput.java new file mode 100644 index 000000000..2bfdea0fe --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CheckLockOutput.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.523+05:30", + comments = "Auto-generated from Open API specification") +public class CheckLockOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + public enum Locked { + TRUE, + FALSE; + } + + @JsonProperty("locked") + private Locked locked; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * TRUE/FALSE - returns TRUE when the given VNF was locked, otherwise returns FALSE + */ + public Locked getLocked() { + return locked; + } + + /** + * TRUE/FALSE - returns TRUE when the given VNF was locked, otherwise returns FALSE + */ + public void setLocked(Locked locked) { + this.locked = locked; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CommonHeader.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CommonHeader.java new file mode 100644 index 000000000..43320d333 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/CommonHeader.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A common header for all APP-C requests + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.49+05:30", + comments = "Auto-generated from Open API specification") +public class CommonHeader { + + @JsonProperty("timestamp") + private ZULU timestamp; + + @JsonProperty("api-ver") + private String apiVer; + + @JsonProperty("originator-id") + private String originatorId; + + @JsonProperty("request-id") + private String requestId; + + @JsonProperty("sub-request-id") + private String subRequestId; + + @JsonProperty("flags") + private Flags flags; + + /** + * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ + */ + public ZULU getTimestamp() { + return timestamp; + } + + /** + * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ + */ + public void setTimestamp(ZULU timestamp) { + this.timestamp = timestamp; + } + + /** + * api-ver is the API version identifier. A given release of APPC should support all previous versions of APPC API (correlate with general requirements) + */ + public String getApiVer() { + return apiVer; + } + + /** + * api-ver is the API version identifier. A given release of APPC should support all previous versions of APPC API (correlate with general requirements) + */ + public void setApiVer(String apiVer) { + this.apiVer = apiVer; + } + + /** + * originator-id an identifier of the calling system which can be used addressing purposes, i.e. returning asynchronous response to the proper destination over UEB (especially in case of multiple consumers of APP-C APIs) + */ + public String getOriginatorId() { + return originatorId; + } + + /** + * originator-id an identifier of the calling system which can be used addressing purposes, i.e. returning asynchronous response to the proper destination over UEB (especially in case of multiple consumers of APP-C APIs) + */ + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + /** + * UUID for the request ID. An OSS/BSS identifier for the request that caused the current action. Multiple API calls may be made with the same request-id The request-id shall be recorded throughout the operations on a single request + */ + public String getRequestId() { + return requestId; + } + + /** + * UUID for the request ID. An OSS/BSS identifier for the request that caused the current action. Multiple API calls may be made with the same request-id The request-id shall be recorded throughout the operations on a single request + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Uniquely identifies a specific LCM action. It is persistent over the life-cycle of a single request + */ + public String getSubRequestId() { + return subRequestId; + } + + /** + * Uniquely identifies a specific LCM action. It is persistent over the life-cycle of a single request + */ + public void setSubRequestId(String subRequestId) { + this.subRequestId = subRequestId; + } + + /** + * Flags are generic flags that apply to any and all commands, all are optional + */ + public Flags getFlags() { + return flags; + } + + /** + * Flags are generic flags that apply to any and all commands, all are optional + */ + public void setFlags(Flags flags) { + this.flags = flags; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteInput.java new file mode 100644 index 000000000..c5f14b6ae --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteInput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.533+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigBackupDeleteInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteOutput.java new file mode 100644 index 000000000..730240276 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupDeleteOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.537+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigBackupDeleteOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupInput.java new file mode 100644 index 000000000..26f799cb4 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.526+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigBackupInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupOutput.java new file mode 100644 index 000000000..1768ea74d --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigBackupOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.529+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigBackupOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportInput.java new file mode 100644 index 000000000..5c2d98d19 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportInput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.541+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigExportInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportOutput.java new file mode 100644 index 000000000..bbfe27af1 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigExportOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.543+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigExportOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyInput.java new file mode 100644 index 000000000..c1a9e6be6 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.559+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigModifyInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyOutput.java new file mode 100644 index 000000000..356299d77 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigModifyOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.563+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigModifyOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreInput.java new file mode 100644 index 000000000..ec26bae34 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.565+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigRestoreInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreOutput.java new file mode 100644 index 000000000..0646d670b --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigRestoreOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.568+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigRestoreOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutInput.java new file mode 100644 index 000000000..14c62689a --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.571+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigScaleoutInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutOutput.java new file mode 100644 index 000000000..fb3f1973a --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigScaleoutOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.574+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigScaleoutOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureInput.java new file mode 100644 index 000000000..b56d692b8 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.577+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigureInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureOutput.java new file mode 100644 index 000000000..fcf32bf2d --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ConfigureOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.585+05:30", + comments = "Auto-generated from Open API specification") +public class ConfigureOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateInput.java new file mode 100644 index 000000000..85c36e8a4 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.587+05:30", + comments = "Auto-generated from Open API specification") +public class EvacuateInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateOutput.java new file mode 100644 index 000000000..2c73a5b84 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/EvacuateOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.59+05:30", + comments = "Auto-generated from Open API specification") +public class EvacuateOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Flags.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Flags.java new file mode 100644 index 000000000..01d2652dd --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Flags.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Flags are generic flags that apply to any and all commands, all are optional + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.498+05:30", + comments = "Auto-generated from Open API specification") +public class Flags { + + public enum Mode { + EXCLUSIVE, + NORMAL; + } + + @JsonProperty("mode") + private Mode mode; + + public enum Force { + TRUE, + FALSE; + } + + @JsonProperty("force") + private Force force; + + @JsonProperty("ttl") + private int ttl; + + /** + * EXCLUSIVE (accept no queued requests on this VNF while processing) or NORMAL (queue other requests until complete) + */ + public Mode getMode() { + return mode; + } + + /** + * EXCLUSIVE (accept no queued requests on this VNF while processing) or NORMAL (queue other requests until complete) + */ + public void setMode(Mode mode) { + this.mode = mode; + } + + /** + * TRUE/FALSE - Execute action even if target is in unstable (i.e. locked, transiting, etc.) state + */ + public Force getForce() { + return force; + } + + /** + * TRUE/FALSE - Execute action even if target is in unstable (i.e. locked, transiting, etc.) state + */ + public void setForce(Force force) { + this.force = force; + } + + /** + * The timeout value (expressed in seconds) for action execution, between action being received by APPC and action initiation + */ + public int getTtl() { + return ttl; + } + + /** + * The timeout value (expressed in seconds) for action execution, between action being received by APPC and action initiation + */ + public void setTtl(int ttl) { + this.ttl = ttl; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckInput.java new file mode 100644 index 000000000..7bd3207cb --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.593+05:30", + comments = "Auto-generated from Open API specification") +public class HealthCheckInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckOutput.java new file mode 100644 index 000000000..41a907c71 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/HealthCheckOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.596+05:30", + comments = "Auto-generated from Open API specification") +public class HealthCheckOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeInput.java new file mode 100644 index 000000000..82a971bc7 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.602+05:30", + comments = "Auto-generated from Open API specification") +public class LiveUpgradeInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeOutput.java new file mode 100644 index 000000000..809adcd8f --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LiveUpgradeOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.604+05:30", + comments = "Auto-generated from Open API specification") +public class LiveUpgradeOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockInput.java new file mode 100644 index 000000000..f6f68d2c6 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.607+05:30", + comments = "Auto-generated from Open API specification") +public class LockInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockOutput.java new file mode 100644 index 000000000..0f77bced6 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/LockOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.609+05:30", + comments = "Auto-generated from Open API specification") +public class LockOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateInput.java new file mode 100644 index 000000000..5877aab07 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.612+05:30", + comments = "Auto-generated from Open API specification") +public class MigrateInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateOutput.java new file mode 100644 index 000000000..4d804db9a --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/MigrateOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.615+05:30", + comments = "Auto-generated from Open API specification") +public class MigrateOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Payload.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Payload.java new file mode 100644 index 000000000..56ce6c529 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Payload.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.472+05:30", + comments = "Auto-generated from Open API specification") +public class Payload { + + private String value; + + public Payload() {} + + @JsonCreator + public Payload(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildInput.java new file mode 100644 index 000000000..ecd199dee --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.618+05:30", + comments = "Auto-generated from Open API specification") +public class RebuildInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildOutput.java new file mode 100644 index 000000000..0816c5b87 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RebuildOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.621+05:30", + comments = "Auto-generated from Open API specification") +public class RebuildOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartInput.java new file mode 100644 index 000000000..4df2184c4 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.623+05:30", + comments = "Auto-generated from Open API specification") +public class RestartInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartOutput.java new file mode 100644 index 000000000..8c44631dd --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RestartOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.629+05:30", + comments = "Auto-generated from Open API specification") +public class RestartOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackInput.java new file mode 100644 index 000000000..db688c0ec --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackInput.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.653+05:30", + comments = "Auto-generated from Open API specification") +public class RollbackInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + @JsonProperty("identity-url") + private String identityUrl; + + @JsonProperty("snapshot-id") + private String snapshotId; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + + public String getIdentityUrl() { + return identityUrl; + } + + public void setIdentityUrl(String identityUrl) { + this.identityUrl = identityUrl; + } + + public String getSnapshotId() { + return snapshotId; + } + + public void setSnapshotId(String snapshotId) { + this.snapshotId = snapshotId; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackOutput.java new file mode 100644 index 000000000..21aa1f08f --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/RollbackOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.656+05:30", + comments = "Auto-generated from Open API specification") +public class RollbackOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotInput.java new file mode 100644 index 000000000..b3492c2dd --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotInput.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.659+05:30", + comments = "Auto-generated from Open API specification") +public class SnapshotInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + @JsonProperty("identity-url") + private String identityUrl; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + + public String getIdentityUrl() { + return identityUrl; + } + + public void setIdentityUrl(String identityUrl) { + this.identityUrl = identityUrl; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotOutput.java new file mode 100644 index 000000000..9036b2607 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SnapshotOutput.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.665+05:30", + comments = "Auto-generated from Open API specification") +public class SnapshotOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("snapshot-id") + private String snapshotId; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + public String getSnapshotId() { + return snapshotId; + } + + public void setSnapshotId(String snapshotId) { + this.snapshotId = snapshotId; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadInput.java new file mode 100644 index 000000000..270121a96 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.668+05:30", + comments = "Auto-generated from Open API specification") +public class SoftwareUploadInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadOutput.java new file mode 100644 index 000000000..8e32dd3a2 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SoftwareUploadOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.672+05:30", + comments = "Auto-generated from Open API specification") +public class SoftwareUploadOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationInput.java new file mode 100644 index 000000000..dca0bc47b --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-07-19T14:31:26.579+05:30", + comments = "Auto-generated from Open API specification") +public class StartApplicationInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationOutput.java new file mode 100644 index 000000000..061f2476e --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartApplicationOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-07-19T14:31:26.58+05:30", + comments = "Auto-generated from Open API specification") +public class StartApplicationOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartInput.java new file mode 100644 index 000000000..3e0829b52 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.675+05:30", + comments = "Auto-generated from Open API specification") +public class StartInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartOutput.java new file mode 100644 index 000000000..1efcae95d --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StartOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.679+05:30", + comments = "Auto-generated from Open API specification") +public class StartOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Status.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Status.java new file mode 100644 index 000000000..85f64c790 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/Status.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.507+05:30", + comments = "Auto-generated from Open API specification") +public class Status { + + @JsonProperty("code") + private int code; + + @JsonProperty("message") + private String message; + + /** + * Response code + */ + public int getCode() { + return code; + } + + /** + * Response code + */ + public void setCode(int code) { + this.code = code; + } + + /** + * Response message + */ + public String getMessage() { + return message; + } + + /** + * Response message + */ + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationInput.java new file mode 100644 index 000000000..dc9bf4840 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-07-19T14:31:26.586+05:30", + comments = "Auto-generated from Open API specification") +public class StopApplicationInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationOutput.java new file mode 100644 index 000000000..d0193a16d --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopApplicationOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-07-19T14:31:26.588+05:30", + comments = "Auto-generated from Open API specification") +public class StopApplicationOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopInput.java new file mode 100644 index 000000000..f5477405e --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.689+05:30", + comments = "Auto-generated from Open API specification") +public class StopInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopOutput.java new file mode 100644 index 000000000..9160a98f7 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/StopOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.692+05:30", + comments = "Auto-generated from Open API specification") +public class StopOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncInput.java new file mode 100644 index 000000000..2928c76a2 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.695+05:30", + comments = "Auto-generated from Open API specification") +public class SyncInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncOutput.java new file mode 100644 index 000000000..82347d295 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/SyncOutput.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.698+05:30", + comments = "Auto-generated from Open API specification") +public class SyncOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateInput.java new file mode 100644 index 000000000..de45dddda --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.701+05:30", + comments = "Auto-generated from Open API specification") +public class TerminateInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateOutput.java new file mode 100644 index 000000000..1a78f0e3f --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TerminateOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.704+05:30", + comments = "Auto-generated from Open API specification") +public class TerminateOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestInput.java new file mode 100644 index 000000000..33dab668e --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.706+05:30", + comments = "Auto-generated from Open API specification") +public class TestInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestOutput.java new file mode 100644 index 000000000..283a92d7e --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/TestOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.708+05:30", + comments = "Auto-generated from Open API specification") +public class TestOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockInput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockInput.java new file mode 100644 index 000000000..b03c683b7 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockInput.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.711+05:30", + comments = "Auto-generated from Open API specification") +public class UnlockInput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action") + private Action action; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("payload") + private Payload payload; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public Action getAction() { + return action; + } + + /** + * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + /** + * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate + */ + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public Payload getPayload() { + return payload; + } + + /** + * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockOutput.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockOutput.java new file mode 100644 index 000000000..9830c8f87 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/UnlockOutput.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.716+05:30", + comments = "Auto-generated from Open API specification") +public class UnlockOutput { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("status") + private Status status; + + /** + * A common header for all APP-C requests + */ + public CommonHeader getCommonHeader() { + return commonHeader; + } + + /** + * A common header for all APP-C requests + */ + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public Status getStatus() { + return status; + } + + /** + * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement + */ + public void setStatus(Status status) { + this.status = status; + } + +} diff --git a/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ZULU.java b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ZULU.java new file mode 100644 index 000000000..416b56a20 --- /dev/null +++ b/appc-client/client-kit/src/main/java/org/onap/appc/client/lcm/model/ZULU.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * NOTE: This file is auto-generated and should not be changed manually. + */ +package org.onap.appc.client.lcm.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ + */ +@javax.annotation.Generated( + value = {"templates/client-kit/open-api-to-java.ftl"}, + date = "2017-05-04T20:09:01.441+05:30", + comments = "Auto-generated from Open API specification") +public class ZULU { + + private String value; + + public ZULU() {} + + @JsonCreator + public ZULU(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/RPC.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/RPC.java deleted file mode 100644 index 2b2c5220a..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/RPC.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface RPC { - String name(); - Class outputType(); -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcClientServiceFactoryProvider.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcClientServiceFactoryProvider.java deleted file mode 100644 index 0ae23f19a..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcClientServiceFactoryProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.api; - -import org.onap.appc.client.lcm.impl.business.AppcLifeCycleManagerServiceFactoryImpl; - -public class AppcClientServiceFactoryProvider { - - private static AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory; - - public static synchronized T getFactory(Class clazz) { - if (clazz.equals(AppcLifeCycleManagerServiceFactory.class)) { - if (appcLifeCycleManagerServiceFactory == null) { - appcLifeCycleManagerServiceFactory = new AppcLifeCycleManagerServiceFactoryImpl(); - } - return (T) appcLifeCycleManagerServiceFactory; - } else { - throw new IllegalArgumentException(clazz.getName()); - } - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java deleted file mode 100644 index c0d2daa01..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/AppcLifeCycleManagerServiceFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.api; - -import org.onap.appc.client.lcm.exceptions.AppcClientException; - -import java.util.Properties; - -public interface AppcLifeCycleManagerServiceFactory { - - /** - * Creates a new stateful LCM API - * @param context application context parameters - * @param properties configures the behaviour of the LCM - * @return a new stateful LCM API - * @throws AppcClientException in case of problem in instantiation - */ - LifeCycleManagerStateful createLifeCycleManagerStateful(ApplicationContext context, Properties properties) throws AppcClientException; - - /** - * performs a shutdown of LCM API. - * in case of graceful, will try and execute the remaining requests, otherwise, will force the shutdown right away - * @param isForceShutdown - boolean. If true to perform force shutdown, other to perform graceful shutdown. - */ - void shutdownLifeCycleManager(boolean isForceShutdown); - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ApplicationContext.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ApplicationContext.java deleted file mode 100644 index b0877ef55..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ApplicationContext.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.api; - -/** - * Created by gital on 11/27/2016. - */ -public class ApplicationContext { - - private String mechID; - private String applicationID; - - public String getMechID() { - return mechID; - } - - public void setMechID(String mechID) { - this.mechID = mechID; - } - - public String getApplicationID() { - return applicationID; - } - - public void setApplicationID(String applicationID) { - this.applicationID = applicationID; - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/LifeCycleManagerStateful.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/LifeCycleManagerStateful.java deleted file mode 100644 index 5600f137f..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/LifeCycleManagerStateful.java +++ /dev/null @@ -1,901 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/* - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.api; - -import org.onap.appc.client.lcm.model.AuditOutput; -import org.onap.appc.client.lcm.model.AuditInput; -import org.onap.appc.client.lcm.model.CheckLockOutput; -import org.onap.appc.client.lcm.model.CheckLockInput; -import org.onap.appc.client.lcm.model.ConfigBackupOutput; -import org.onap.appc.client.lcm.model.ConfigBackupInput; -import org.onap.appc.client.lcm.model.ConfigBackupDeleteOutput; -import org.onap.appc.client.lcm.model.ConfigBackupDeleteInput; -import org.onap.appc.client.lcm.model.ConfigExportOutput; -import org.onap.appc.client.lcm.model.ConfigExportInput; -import org.onap.appc.client.lcm.model.ConfigModifyOutput; -import org.onap.appc.client.lcm.model.ConfigModifyInput; -import org.onap.appc.client.lcm.model.ConfigRestoreOutput; -import org.onap.appc.client.lcm.model.ConfigRestoreInput; -import org.onap.appc.client.lcm.model.ConfigScaleoutOutput; -import org.onap.appc.client.lcm.model.ConfigScaleoutInput; -import org.onap.appc.client.lcm.model.ConfigureOutput; -import org.onap.appc.client.lcm.model.ConfigureInput; -import org.onap.appc.client.lcm.model.EvacuateOutput; -import org.onap.appc.client.lcm.model.EvacuateInput; -import org.onap.appc.client.lcm.model.HealthCheckOutput; -import org.onap.appc.client.lcm.model.HealthCheckInput; -import org.onap.appc.client.lcm.model.LiveUpgradeOutput; -import org.onap.appc.client.lcm.model.LiveUpgradeInput; -import org.onap.appc.client.lcm.model.LockOutput; -import org.onap.appc.client.lcm.model.LockInput; -import org.onap.appc.client.lcm.model.MigrateOutput; -import org.onap.appc.client.lcm.model.MigrateInput; -import org.onap.appc.client.lcm.model.RebuildOutput; -import org.onap.appc.client.lcm.model.RebuildInput; -import org.onap.appc.client.lcm.model.RestartOutput; -import org.onap.appc.client.lcm.model.RestartInput; -import org.onap.appc.client.lcm.model.RollbackOutput; -import org.onap.appc.client.lcm.model.RollbackInput; -import org.onap.appc.client.lcm.model.SnapshotOutput; -import org.onap.appc.client.lcm.model.SnapshotInput; -import org.onap.appc.client.lcm.model.SoftwareUploadOutput; -import org.onap.appc.client.lcm.model.SoftwareUploadInput; -import org.onap.appc.client.lcm.model.StartOutput; -import org.onap.appc.client.lcm.model.StartInput; -import org.onap.appc.client.lcm.model.StopOutput; -import org.onap.appc.client.lcm.model.StopInput; -import org.onap.appc.client.lcm.model.SyncOutput; -import org.onap.appc.client.lcm.model.SyncInput; -import org.onap.appc.client.lcm.model.TerminateOutput; -import org.onap.appc.client.lcm.model.TerminateInput; -import org.onap.appc.client.lcm.model.TestOutput; -import org.onap.appc.client.lcm.model.TestInput; -import org.onap.appc.client.lcm.model.UnlockOutput; -import org.onap.appc.client.lcm.model.UnlockInput; -import org.onap.appc.RPC; -import org.onap.appc.client.lcm.exceptions.AppcClientException; - -/** - * Defines the services and request/response requirements for the ECOMP APP-C - * component. - */ -@javax.annotation.Generated(value = { - "templates/client-kit/open-api-to-java.ftl" }, date = "2017-05-04T20:09:01.723+05:30", comments = "Auto-generated from Open API specification") -public interface LifeCycleManagerStateful { - - /** - * The Audit command compares the configuration of the VNF associated with the - * current request against the configuration that is stored in APPC's - * configuration store. A successful Audit means that the current VNF - * configuration matches the APPC stored configuration. A failed Audit indicates - * that the request configuration is different from the stored configuration. - * This command can be applied to any VNF type. The only restriction is that a - * particular VNF should be able to support the interface for Reading - * Configuration using existing adapters and use the following protocols: CLI, - * RestConf and XML. The Audit action does not require any payload parameters - * - * @param auditInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "audit", outputType = AuditOutput.class) - AuditOutput audit(AuditInput auditInput) throws AppcClientException; - - /** - * The Audit command compares the configuration of the VNF associated with the - * current request against the configuration that is stored in APPC's - * configuration store. A successful Audit means that the current VNF - * configuration matches the APPC stored configuration. A failed Audit indicates - * that the request configuration is different from the stored configuration. - * This command can be applied to any VNF type. The only restriction is that a - * particular VNF should be able to support the interface for Reading - * Configuration using existing adapters and use the following protocols: CLI, - * RestConf and XML. The Audit action does not require any payload parameters - * - * @param auditInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "audit", outputType = AuditOutput.class) - void audit(AuditInput auditInput, ResponseHandler listener) throws AppcClientException; - - /** - * The CheckLock command returns true if the specified VNF is locked, false if - * not. A CheckLock command is deemed successful if the processing completes - * without error, whether the VNF is locked or not. The command returns only a - * single response with a final status. The APPC also locks the target VNF - * during any command processing, so a VNF can have a locked status even if no - * Lock command has been explicitly called. The CheckLock command returns a - * specific response structure that extends the default LCM response. The - * CheckLock action does not require any payload parameters - * - * @param checkLockInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "check-lock", outputType = CheckLockOutput.class) - CheckLockOutput checkLock(CheckLockInput checkLockInput) throws AppcClientException; - - /** - * The CheckLock command returns true if the specified VNF is locked, false if - * not. A CheckLock command is deemed successful if the processing completes - * without error, whether the VNF is locked or not. The command returns only a - * single response with a final status. The APPC also locks the target VNF - * during any command processing, so a VNF can have a locked status even if no - * Lock command has been explicitly called. The CheckLock command returns a - * specific response structure that extends the default LCM response. The - * CheckLock action does not require any payload parameters - * - * @param checkLockInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "check-lock", outputType = CheckLockOutput.class) - void checkLock(CheckLockInput checkLockInput, ResponseHandler listener) throws AppcClientException; - - /** - * An operation to Backup configurations of a virtual network function (or VM) - * - * @param configBackupInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-backup", outputType = ConfigBackupOutput.class) - ConfigBackupOutput configBackup(ConfigBackupInput configBackupInput) throws AppcClientException; - - /** - * An operation to Backup configurations of a virtual network function (or VM) - * - * @param configBackupInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-backup", outputType = ConfigBackupOutput.class) - void configBackup(ConfigBackupInput configBackupInput, ResponseHandler listener) - throws AppcClientException; - - /** - * An operation to Delete backup configurations of a virtual network function - * (or VM) - * - * @param configBackupDeleteInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-backup-delete", outputType = ConfigBackupDeleteOutput.class) - ConfigBackupDeleteOutput configBackupDelete(ConfigBackupDeleteInput configBackupDeleteInput) - throws AppcClientException; - - /** - * An operation to Delete backup configurations of a virtual network function - * (or VM) - * - * @param configBackupDeleteInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-backup-delete", outputType = ConfigBackupDeleteOutput.class) - void configBackupDelete(ConfigBackupDeleteInput configBackupDeleteInput, - ResponseHandler listener) throws AppcClientException; - - /** - * An operation to Export configurations of a virtual network function (or VM) - * - * @param configExportInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-export", outputType = ConfigExportOutput.class) - ConfigExportOutput configExport(ConfigExportInput configExportInput) throws AppcClientException; - - /** - * An operation to Export configurations of a virtual network function (or VM) - * - * @param configExportInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-export", outputType = ConfigExportOutput.class) - void configExport(ConfigExportInput configExportInput, ResponseHandler listener) - throws AppcClientException; - - /** - * Use the ModifyConfig command when a full configuration cycle is either not - * required or is considered too costly. The ModifyConfig LCM action affects - * only a subset of the total configuration data of a VNF. The set of - * configuration parameters to be affected is a subset of the total - * configuration data of the target VNF type. The payload block must contain the - * configuration parameters to be modified and their values. A successful modify - * returns a success response. A failed modify returns a failure response and - * the specific failure messages in the response payload block - * - * @param configModifyInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-modify", outputType = ConfigModifyOutput.class) - ConfigModifyOutput configModify(ConfigModifyInput configModifyInput) throws AppcClientException; - - /** - * Use the ModifyConfig command when a full configuration cycle is either not - * required or is considered too costly. The ModifyConfig LCM action affects - * only a subset of the total configuration data of a VNF. The set of - * configuration parameters to be affected is a subset of the total - * configuration data of the target VNF type. The payload block must contain the - * configuration parameters to be modified and their values. A successful modify - * returns a success response. A failed modify returns a failure response and - * the specific failure messages in the response payload block - * - * @param configModifyInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-modify", outputType = ConfigModifyOutput.class) - void configModify(ConfigModifyInput configModifyInput, ResponseHandler listener) - throws AppcClientException; - - /** - * An operation to restore the configurations of a virtual network function (or - * VM) - * - * @param configRestoreInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-restore", outputType = ConfigRestoreOutput.class) - ConfigRestoreOutput configRestore(ConfigRestoreInput configRestoreInput) throws AppcClientException; - - /** - * An operation to restore the configurations of a virtual network function (or - * VM) - * - * @param configRestoreInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-restore", outputType = ConfigRestoreOutput.class) - void configRestore(ConfigRestoreInput configRestoreInput, ResponseHandler listener) - throws AppcClientException; - - /** - * An operation to scaleout the configurations of a virtual network function (or - * VM) - * - * @param configScaleoutInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-scaleout", outputType = ConfigScaleoutOutput.class) - ConfigScaleoutOutput configScaleout(ConfigScaleoutInput configScaleoutInput) throws AppcClientException; - - /** - * An operation to scaleout the configurations of a virtual network function (or - * VM) - * - * @param configScaleoutInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "config-scaleout", outputType = ConfigScaleoutOutput.class) - void configScaleout(ConfigScaleoutInput configScaleoutInput, ResponseHandler listener) - throws AppcClientException; - - /** - * An operation to configure the configurations of a virtual network function - * (or VM) - * - * @param configureInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "configure", outputType = ConfigureOutput.class) - ConfigureOutput configure(ConfigureInput configureInput) throws AppcClientException; - - /** - * An operation to configure the configurations of a virtual network function - * (or VM) - * - * @param configureInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "configure", outputType = ConfigureOutput.class) - void configure(ConfigureInput configureInput, ResponseHandler listener) throws AppcClientException; - - /** - * An operation to evacuate a virtual network function (or VM) - * - * @param evacuateInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "evacuate", outputType = EvacuateOutput.class) - EvacuateOutput evacuate(EvacuateInput evacuateInput) throws AppcClientException; - - /** - * An operation to evacuate a virtual network function (or VM) - * - * @param evacuateInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "evacuate", outputType = EvacuateOutput.class) - void evacuate(EvacuateInput evacuateInput, ResponseHandler listener) throws AppcClientException; - - /** - * This command runs a VNF health check and returns the result. A health check - * is VNF-specific. For a complex VNF, APPC initiates further subordinate health - * checks - * - * @param healthCheckInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "health-check", outputType = HealthCheckOutput.class) - HealthCheckOutput healthCheck(HealthCheckInput healthCheckInput) throws AppcClientException; - - /** - * This command runs a VNF health check and returns the result. A health check - * is VNF-specific. For a complex VNF, APPC initiates further subordinate health - * checks - * - * @param healthCheckInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "health-check", outputType = HealthCheckOutput.class) - void healthCheck(HealthCheckInput healthCheckInput, ResponseHandler listener) - throws AppcClientException; - - /** - * The LiveUpgrade LCM action upgrades the target VNF to a new version without - * interrupting VNF operation. A successful upgrade returns a success status. A - * failed upgrade returns a failure code and the failure messages in the - * response payload block. The payload includes the IP of the location that - * hosts the new software version installer file and the new software version. - * Connections or operations that are active at the time of the LiveUpgrade - * action request will not be interrupted by the action and, therefore, the - * action may take a significant amount of time to run. A LiveUpgrade is defined - * as non-disruptive; it is the responsibility of the VNF to handle disruptions - * if they occur - * - * @param liveUpgradeInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "live-upgrade", outputType = LiveUpgradeOutput.class) - LiveUpgradeOutput liveUpgrade(LiveUpgradeInput liveUpgradeInput) throws AppcClientException; - - /** - * The LiveUpgrade LCM action upgrades the target VNF to a new version without - * interrupting VNF operation. A successful upgrade returns a success status. A - * failed upgrade returns a failure code and the failure messages in the - * response payload block. The payload includes the IP of the location that - * hosts the new software version installer file and the new software version. - * Connections or operations that are active at the time of the LiveUpgrade - * action request will not be interrupted by the action and, therefore, the - * action may take a significant amount of time to run. A LiveUpgrade is defined - * as non-disruptive; it is the responsibility of the VNF to handle disruptions - * if they occur - * - * @param liveUpgradeInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "live-upgrade", outputType = LiveUpgradeOutput.class) - void liveUpgrade(LiveUpgradeInput liveUpgradeInput, ResponseHandler listener) - throws AppcClientException; - - /** - * Use the Lock command to ensure exclusive access during a series of critical - * LCM commands. The Lock action will return a successful result if the VNF is - * not already locked or if it was locked with the same request-id, otherwise - * the action returns a response with a reject status code. When a VNF is - * locked, any subsequent sequential commands with same request-id will be - * accepted. Commands associated with other request-ids will be rejected. The - * Lock command returns only one final response with the status of the request - * processing. The APPC also locks the target VNF during any command processing. - * If a lock action is then requested on that VNF, it will be rejected because - * the VNF was already locked, even though no actual lock command was explicitly - * invoked - * - * @param lockInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "lock", outputType = LockOutput.class) - LockOutput lock(LockInput lockInput) throws AppcClientException; - - /** - * Use the Lock command to ensure exclusive access during a series of critical - * LCM commands. The Lock action will return a successful result if the VNF is - * not already locked or if it was locked with the same request-id, otherwise - * the action returns a response with a reject status code. When a VNF is - * locked, any subsequent sequential commands with same request-id will be - * accepted. Commands associated with other request-ids will be rejected. The - * Lock command returns only one final response with the status of the request - * processing. The APPC also locks the target VNF during any command processing. - * If a lock action is then requested on that VNF, it will be rejected because - * the VNF was already locked, even though no actual lock command was explicitly - * invoked - * - * @param lockInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "lock", outputType = LockOutput.class) - void lock(LockInput lockInput, ResponseHandler listener) throws AppcClientException; - - /** - * Migrates a running target VFC from its current AIC host to another. A - * destination AIC node will be selected by relying on AIC internal rules to - * migrate. A successful Migrate action returns a success response and the new - * AIC node identity in the response payload block. A failed Migrate action - * returns a failure and the failure messages in the response payload block - * - * @param migrateInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "migrate", outputType = MigrateOutput.class) - MigrateOutput migrate(MigrateInput migrateInput) throws AppcClientException; - - /** - * Migrates a running target VFC from its current AIC host to another. A - * destination AIC node will be selected by relying on AIC internal rules to - * migrate. A successful Migrate action returns a success response and the new - * AIC node identity in the response payload block. A failed Migrate action - * returns a failure and the failure messages in the response payload block - * - * @param migrateInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "migrate", outputType = MigrateOutput.class) - void migrate(MigrateInput migrateInput, ResponseHandler listener) throws AppcClientException; - - /** - * Recreates a target VFC instance to a known, stable state. A successful - * rebuild returns a success response and the rebuild details in the response - * payload block. A failed rebuild returns a failure and the failure messages in - * the response payload block - * - * @param rebuildInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "rebuild", outputType = RebuildOutput.class) - RebuildOutput rebuild(RebuildInput rebuildInput) throws AppcClientException; - - /** - * Recreates a target VFC instance to a known, stable state. A successful - * rebuild returns a success response and the rebuild details in the response - * payload block. A failed rebuild returns a failure and the failure messages in - * the response payload block - * - * @param rebuildInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "rebuild", outputType = RebuildOutput.class) - void rebuild(RebuildInput rebuildInput, ResponseHandler listener) throws AppcClientException; - - /** - * An operation to restart a virtual network function (or VM) - * - * @param restartInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "restart", outputType = RestartOutput.class) - RestartOutput restart(RestartInput restartInput) throws AppcClientException; - - /** - * An operation to restart a virtual network function (or VM) - * - * @param restartInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "restart", outputType = RestartOutput.class) - void restart(RestartInput restartInput, ResponseHandler listener) throws AppcClientException; - - /** - * Sets a VNF to the previous version of the configuration without explicitly - * invoking the configuration set name. This command is used when the - * configuration was successful, but the health-check was not. A successful - * rollback returns a success status when the restart process has completed. A - * failed or a partially failed (for a complex VNF) rollback returns a failure - * and the failure messages in the response payload block. This command can be - * applied to any VNF type. The only restriction is that the particular VNF - * should be built based on the generic heap stack - * - * @param rollbackInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "rollback", outputType = RollbackOutput.class) - RollbackOutput rollback(RollbackInput rollbackInput) throws AppcClientException; - - /** - * Sets a VNF to the previous version of the configuration without explicitly - * invoking the configuration set name. This command is used when the - * configuration was successful, but the health-check was not. A successful - * rollback returns a success status when the restart process has completed. A - * failed or a partially failed (for a complex VNF) rollback returns a failure - * and the failure messages in the response payload block. This command can be - * applied to any VNF type. The only restriction is that the particular VNF - * should be built based on the generic heap stack - * - * @param rollbackInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "rollback", outputType = RollbackOutput.class) - void rollback(RollbackInput rollbackInput, ResponseHandler listener) throws AppcClientException; - - /** - * Creates a snapshot of a VNF, or VM. The Snapshot command returns a customized - * response containing a reference to the newly created snapshot instance if the - * action is successful. This command can be applied to any VNF type. The only - * restriction is that the particular VNF should be built based on the generic - * heap stack - * - * @param snapshotInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "snapshot", outputType = SnapshotOutput.class) - SnapshotOutput snapshot(SnapshotInput snapshotInput) throws AppcClientException; - - /** - * Creates a snapshot of a VNF, or VM. The Snapshot command returns a customized - * response containing a reference to the newly created snapshot instance if the - * action is successful. This command can be applied to any VNF type. The only - * restriction is that the particular VNF should be built based on the generic - * heap stack - * - * @param snapshotInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "snapshot", outputType = SnapshotOutput.class) - void snapshot(SnapshotInput snapshotInput, ResponseHandler listener) throws AppcClientException; - - /** - * This LCM command uploads the file that contains a new software version to the - * target VNF - * - * @param softwareUploadInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "software-upload", outputType = SoftwareUploadOutput.class) - SoftwareUploadOutput softwareUpload(SoftwareUploadInput softwareUploadInput) throws AppcClientException; - - /** - * This LCM command uploads the file that contains a new software version to the - * target VNF - * - * @param softwareUploadInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "software-upload", outputType = SoftwareUploadOutput.class) - void softwareUpload(SoftwareUploadInput softwareUploadInput, ResponseHandler listener) - throws AppcClientException; - - /** - * An operation to start a virtual network function (or VM) - * - * @param startInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "start", outputType = StartOutput.class) - StartOutput start(StartInput startInput) throws AppcClientException; - - /** - * An operation to start a virtual network function (or VM) - * - * @param startInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "start", outputType = StartOutput.class) - void start(StartInput startInput, ResponseHandler listener) throws AppcClientException; - - /** - * Stop a target VNF or VNFC. A successful stop returns a success response. For - * a multi-component stop to be considered successful, all component stop - * actions must succeed. A failed stop returns a failure and the failure - * messages in the response payload block - * - * @param stopInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "stop", outputType = StopOutput.class) - StopOutput stop(StopInput stopInput) throws AppcClientException; - - /** - * Stop a target VNF or VNFC. A successful stop returns a success response. For - * a multi-component stop to be considered successful, all component stop - * actions must succeed. A failed stop returns a failure and the failure - * messages in the response payload block - * - * @param stopInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "stop", outputType = StopOutput.class) - void stop(StopInput stopInput, ResponseHandler listener) throws AppcClientException; - - /** - * The Sync action updates the current configuration in the APPC store with the - * running configuration from the device. A successful Sync returns a success - * status. A failed Sync returns a failure response status and failure messages - * in the response payload block. This command can be applied to any VNF type. - * The only restriction is that a particular VNF should be able to support the - * interface for Reading Configuration using existing adapters and use the - * following protocols: CLI, RestConf and XML - * - * @param syncInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "sync", outputType = SyncOutput.class) - SyncOutput sync(SyncInput syncInput) throws AppcClientException; - - /** - * The Sync action updates the current configuration in the APPC store with the - * running configuration from the device. A successful Sync returns a success - * status. A failed Sync returns a failure response status and failure messages - * in the response payload block. This command can be applied to any VNF type. - * The only restriction is that a particular VNF should be able to support the - * interface for Reading Configuration using existing adapters and use the - * following protocols: CLI, RestConf and XML - * - * @param syncInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "sync", outputType = SyncOutput.class) - void sync(SyncInput syncInput, ResponseHandler listener) throws AppcClientException; - - /** - * Terminate a target VNF and release its resources (possibly gracefully). - * Specific scripts can be run before termination by placing them under the - * Terminate life cycle event. All configuration files related to the target VNF - * are deleted. The resources of a terminated VNF that are not managed by APPC, - * such as those handled by SDNC or other components, are not handled and remain - * the responsibility of their respective managing functions. A successful - * Terminate action returns a success response. For a multi-component terminate - * to be considered successful, all component Terminate actions must also - * succeed. A failed Terminate returns a failure status and the failure messages - * in the response payload block - * - * @param terminateInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "terminate", outputType = TerminateOutput.class) - TerminateOutput terminate(TerminateInput terminateInput) throws AppcClientException; - - /** - * Terminate a target VNF and release its resources (possibly gracefully). - * Specific scripts can be run before termination by placing them under the - * Terminate life cycle event. All configuration files related to the target VNF - * are deleted. The resources of a terminated VNF that are not managed by APPC, - * such as those handled by SDNC or other components, are not handled and remain - * the responsibility of their respective managing functions. A successful - * Terminate action returns a success response. For a multi-component terminate - * to be considered successful, all component Terminate actions must also - * succeed. A failed Terminate returns a failure status and the failure messages - * in the response payload block - * - * @param terminateInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "terminate", outputType = TerminateOutput.class) - void terminate(TerminateInput terminateInput, ResponseHandler listener) throws AppcClientException; - - /** - * The Test LCM action checks a target VNF or VNFC for correct operation. The - * functionality of the Test LCM action involves should involve more than a - * HealthCheck , it should provide a means for launching a test transaction and - * determining if the transaction completed successfully or not. A transaction - * launcher microservice will have to be supplied by the VNF and called by APPC. - * A successful test returns a success and the results of the test in the - * payload block. A failed test returns a failure and specific failure messages - * in the payload block - * - * @param testInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "test", outputType = TestOutput.class) - TestOutput test(TestInput testInput) throws AppcClientException; - - /** - * The Test LCM action checks a target VNF or VNFC for correct operation. The - * functionality of the Test LCM action involves should involve more than a - * HealthCheck , it should provide a means for launching a test transaction and - * determining if the transaction completed successfully or not. A transaction - * launcher microservice will have to be supplied by the VNF and called by APPC. - * A successful test returns a success and the results of the test in the - * payload block. A failed test returns a failure and specific failure messages - * in the payload block - * - * @param testInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "test", outputType = TestOutput.class) - void test(TestInput testInput, ResponseHandler listener) throws AppcClientException; - - /** - * Run the Unlock command to release the lock on a VNF and allow other clients - * to perform LCM commands on that VNF. The Unlock command will result in - * success if the VNF successfully unlocked or if it was already unlocked, - * otherwise commands will be rejected. The Unlock command will only return - * success if the VNF was locked with same request-id (on page 6). The Unlock - * command returns only one final response with the status of the request - * processing. The APPC also locks the target VNF during any command processing. - * If an Unlock action is then requested on that VNF with a different - * request-id, it will be rejected because the VNF is already locked for another - * process, even though no actual lock command was explicitly invoked - * - * @param unlockInput - * - RPC input object - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "unlock", outputType = UnlockOutput.class) - UnlockOutput unlock(UnlockInput unlockInput) throws AppcClientException; - - /** - * Run the Unlock command to release the lock on a VNF and allow other clients - * to perform LCM commands on that VNF. The Unlock command will result in - * success if the VNF successfully unlocked or if it was already unlocked, - * otherwise commands will be rejected. The Unlock command will only return - * success if the VNF was locked with same request-id (on page 6). The Unlock - * command returns only one final response with the status of the request - * processing. The APPC also locks the target VNF during any command processing. - * If an Unlock action is then requested on that VNF with a different - * request-id, it will be rejected because the VNF is already locked for another - * process, even though no actual lock command was explicitly invoked - * - * @param unlockInput - * - RPC input object - * @param listener - * - callback implementation - * @throws AppcClientException - * - throw AppcClientException - */ - @RPC(name = "unlock", outputType = UnlockOutput.class) - void unlock(UnlockInput unlockInput, ResponseHandler listener) throws AppcClientException; - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ResponseHandler.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ResponseHandler.java deleted file mode 100644 index 68459925f..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/api/ResponseHandler.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.api; - -import org.onap.appc.client.lcm.exceptions.AppcClientException; - -public interface ResponseHandler { - - /** - * Handler to react when a response arrives - * @param response the response output object - */ - void onResponse(T response); - - /** - * Handler to react when an exception arrives instead of a response - * @param exception detailed with type of exception - */ - void onException(AppcClientException exception); -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientBusinessException.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientBusinessException.java deleted file mode 100644 index 7d91f39e5..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientBusinessException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.exceptions; - -public class AppcClientBusinessException extends AppcClientException { - - public AppcClientBusinessException() { - super(); - } - - public AppcClientBusinessException(String message) { - super(message); - } - - public AppcClientBusinessException(String message, Throwable cause) { - super(message, cause); - } - - public AppcClientBusinessException(Throwable cause) { - super(cause); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientException.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientException.java deleted file mode 100644 index c72f6150e..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.exceptions; - -public class AppcClientException extends Exception { - - public AppcClientException() { - super(); - } - - public AppcClientException(String message) { - super(message); - } - - public AppcClientException(String message, Throwable cause) { - super(message, cause); - } - - public AppcClientException(Throwable cause) { - super(cause); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientInternalException.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientInternalException.java deleted file mode 100644 index 9b6dfed7b..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/exceptions/AppcClientInternalException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.exceptions; - -public class AppcClientInternalException extends AppcClientException { - - public AppcClientInternalException() { - super(); - } - - public AppcClientInternalException(String message) { - super(message); - } - - public AppcClientInternalException(String message, Throwable cause) { - super(message, cause); - } - - public AppcClientInternalException(Throwable cause) { - super(cause); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java deleted file mode 100644 index b8ab36bbe..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/AppcLifeCycleManagerServiceFactoryImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; -import org.onap.appc.client.lcm.api.ApplicationContext; -import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; -import org.onap.appc.client.lcm.exceptions.AppcClientException; - -import java.lang.reflect.Proxy; -import java.util.Properties; - -public class AppcLifeCycleManagerServiceFactoryImpl implements AppcLifeCycleManagerServiceFactory { - - private LifeCycleManagerStateful lifeCycleManagerStateful; - private LCMRequestProcessor lcmRequestProcessor; - - @Override - public synchronized LifeCycleManagerStateful createLifeCycleManagerStateful(ApplicationContext context, Properties properties) throws AppcClientException{ - if (lifeCycleManagerStateful == null) { - lcmRequestProcessor = new LCMRequestProcessor(context, properties); - lifeCycleManagerStateful = (LifeCycleManagerStateful) Proxy.newProxyInstance(LifeCycleManagerStateful.class.getClassLoader(), new Class[]{LifeCycleManagerStateful.class}, new RPCInvocator(lcmRequestProcessor)); - } - else { - throw new IllegalStateException("already instansiated LifeCycleManagerStateful instance"); - } - return lifeCycleManagerStateful; - } - - @Override - public void shutdownLifeCycleManager(boolean isForceShutdown) { - if(lcmRequestProcessor != null){ - lcmRequestProcessor.shutdown(isForceShutdown); - } - else{ - throw new IllegalStateException("The life cycle manager library wasn't instantiated properly, therefore the shutdown event will not be handled"); - } - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java deleted file mode 100644 index 96e21d8f8..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreAsyncResponseHandlerImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.client.impl.core.CoreException; -import org.onap.appc.client.impl.core.ICoreAsyncResponseHandler; -import org.onap.appc.client.lcm.api.ResponseHandler; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import com.fasterxml.jackson.databind.ObjectMapper; - -class CoreAsyncResponseHandlerImpl extends CoreResponseHandler implements ICoreAsyncResponseHandler { - - private final ResponseHandler responseHandler; - - CoreAsyncResponseHandlerImpl(ResponseHandler responseHandler, Class rpcOutput, ObjectMapper mapper) { - super(rpcOutput, mapper); - this.responseHandler = responseHandler; - } - - public boolean onResponse(String message, String type) { - Boolean[] isFinal = new Boolean[1]; - isFinal[0] = false; - try { - T responseObject = (T) super.getResponse(message, type, isFinal); - responseHandler.onResponse(responseObject); - return isFinal[0]; - } catch (Exception e) { - this.onException(e); - isFinal[0] = true; - } - return isFinal[0]; - } - - public void onException(Exception e) { - AppcClientException ex = new AppcClientException(e); - responseHandler.onException(ex); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreResponseHandler.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreResponseHandler.java deleted file mode 100644 index 3d4786862..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreResponseHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; - -import org.onap.appc.client.lcm.model.Status; -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 java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -class CoreResponseHandler { - private final Class rpcOutput; - private final ObjectMapper mapper; - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(CoreResponseHandler.class); - - CoreResponseHandler(Class rpcOutput, ObjectMapper mapper) { - this.rpcOutput = rpcOutput; - this.mapper = mapper; - } - - T getResponse(String message, String type, Boolean[] isFinal) throws AppcClientInternalException { - if (type.equals("error")) { - try { - String correlationId = getCorrelationID(message); - LOG.error("Received response with error on correlation id: " + correlationId); - } catch (IOException e) { - LOG.error("Received response with error and couldn't extract correlationID"); - } - throw new AppcClientInternalException(message); - } - T responseObject = jsonToResponseObject(message); - int code = getStatusCode(responseObject); - - int family = code / 100; - - switch (family) { - case 1: - case 5: - // not final - break; - case 2: - case 3: - case 4: - isFinal[0] = true; - // final - break; - default: // Should never happen - throw new AppcClientInternalException(new IllegalStateException("Unsupported status code " + code + ". message: " + message)); - } - return responseObject; - - } - - private T jsonToResponseObject(String message) throws AppcClientInternalException { - try { - JsonNode jsonOutput = mapper.readTree(message).get("output"); - return rpcOutput.cast(mapper.treeToValue(jsonOutput, rpcOutput)); - } catch (IOException e) { - throw new AppcClientInternalException("failed to read message: " + message, e); - } - } - - private int getStatusCode(Object response) throws AppcClientInternalException { - try { - Method method = response.getClass().getMethod("getStatus"); - Status status = (Status) method.invoke(response); - return status.getCode(); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - throw new AppcClientInternalException("failed to get status code from response: " + response, e); - } - } - - private String getCorrelationID(String message) throws IOException { - JsonNode common = mapper.readTree(message).get("output").get("common-header"); - String correlationId = common.get("request-id").asText() + "-" + common.get("sub-request-id").asText(); - return correlationId; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java deleted file mode 100644 index 66da8fbe2..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/CoreSyncResponseHandlerImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.client.impl.core.CoreException; -import org.onap.appc.client.impl.core.ICoreSyncResponseHandler; -import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; -import com.fasterxml.jackson.databind.ObjectMapper; - -class CoreSyncResponseHandlerImpl extends CoreResponseHandler implements ICoreSyncResponseHandler { - - CoreSyncResponseHandlerImpl(Class rpcOutput, ObjectMapper mapper) { - super(rpcOutput, mapper); - } - - public T onResponse(String message, String type) throws CoreException { - Boolean[] isFinal = new Boolean[1]; - isFinal[0] = false; - T responseObject = null; - try { - responseObject = (T) super.getResponse(message, type, isFinal); - responseObject = (isFinal[0]) ? responseObject : null; - } catch (AppcClientInternalException e) { - throw new CoreException(e); - } - - return responseObject; - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/LCMRequestProcessor.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/LCMRequestProcessor.java deleted file mode 100644 index b718c1ac9..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/LCMRequestProcessor.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.client.impl.core.*; -import org.onap.appc.client.lcm.api.ApplicationContext; -import org.onap.appc.client.lcm.api.ResponseHandler; -import org.onap.appc.client.lcm.exceptions.AppcClientBusinessException; -import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; -import org.onap.appc.client.lcm.model.CommonHeader; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Properties; -import java.util.concurrent.TimeoutException; - -class LCMRequestProcessor { - - private final IInvocationManager invocationManager; - private final ObjectMapper mapper; - - LCMRequestProcessor(ApplicationContext context, Properties properties) throws AppcClientBusinessException { - try{ - invocationManager = InvocationManagerFactory.getInstance(); - invocationManager.init(properties); - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } catch (CoreException e) { - throw new AppcClientBusinessException(e); - } - } - - void processAsync(Object rpcInput, String rpcName, Class rpcOutputType, ResponseHandler handler) throws AppcClientInternalException { - try { - String correlationID = createCorrelationID(rpcInput); - String rpcStr = marshallRPCInput(rpcInput); - ICoreAsyncResponseHandler asyncResponseHandler = new CoreAsyncResponseHandlerImpl(handler, rpcOutputType, mapper); - invocationManager.asyncRequest(rpcStr, asyncResponseHandler, correlationID, rpcName); - } catch (CoreException e) { - throw new AppcClientInternalException(e); - } - } - - T processSync(Object rpcInput, String rpcName, Class rpcOutputType) throws AppcClientInternalException, AppcClientBusinessException { - T response = null; - try { - String correlationID = createCorrelationID(rpcInput); - String rpcStr = marshallRPCInput(rpcInput); - ICoreSyncResponseHandler syncResponseHandler = new CoreSyncResponseHandlerImpl(rpcOutputType, mapper); - response = invocationManager.syncRequest(rpcStr, syncResponseHandler, correlationID, rpcName); - }catch (CoreException e){ - if (e.getCause() instanceof AppcClientInternalException) { - throw (AppcClientInternalException) e.getCause(); - } - else { - throw new AppcClientInternalException(e); - } - }catch (TimeoutException e){ - throw new AppcClientBusinessException(e); - } - return response; - } - - private CommonHeader getCommonHeader(Object rpcInput) throws AppcClientInternalException { - try { - Class clazz = rpcInput.getClass(); - Method method = clazz.getMethod("getCommonHeader"); - return CommonHeader.class.cast(method.invoke(rpcInput)); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - throw new AppcClientInternalException("can't get commonHeader"); - } - } - - private String createCorrelationID(Object rpcInput) throws AppcClientInternalException { - CommonHeader commonHeader = getCommonHeader(rpcInput); - return commonHeader.getRequestId() + "-" + commonHeader.getSubRequestId(); - } - - private String marshallRPCInput(Object rpcInput) throws AppcClientInternalException { - try { - JsonNode body = mapper.valueToTree(rpcInput); - ObjectNode message = mapper.createObjectNode(); - message.set("input", body); - return message.toString(); - } catch (RuntimeException e) { - throw new AppcClientInternalException("can't marshall input", e); - } - } - - void shutdown(boolean isForceShutdown){ - invocationManager.shutdown(isForceShutdown); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/RPCInvocator.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/RPCInvocator.java deleted file mode 100644 index 525700d62..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/impl/business/RPCInvocator.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.lcm.impl.business; - -import org.onap.appc.RPC; -import org.onap.appc.client.lcm.api.ResponseHandler; -import org.onap.appc.client.lcm.exceptions.AppcClientBusinessException; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import org.onap.appc.client.lcm.exceptions.AppcClientInternalException; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -class RPCInvocator implements InvocationHandler { - - private final LCMRequestProcessor lcmRequestProcessor; - - RPCInvocator(LCMRequestProcessor lcmRequestProcessor) { - this.lcmRequestProcessor = lcmRequestProcessor; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (isLCMRequest(method)) { - try { - return invokeImpl(method, args); - } - catch (AppcClientInternalException | AppcClientBusinessException e) { - throw new AppcClientException(e); - } - } else { - // Delegate non-RPC Object's methods (hashCode/equals/etc) to the proxy instance itself - return method.invoke(proxy, args); - } - } - - private T invokeImpl(Method method, Object[] args) throws AppcClientInternalException, AppcClientBusinessException { - Object rpcInput = args[0]; - RPC annotation = method.getAnnotation(RPC.class); - String rpcName = annotation.name(); - @SuppressWarnings("unchecked") - Class rpcOutputType = (Class) annotation.outputType(); - - T result = null; - if (isAsync(method)) { - @SuppressWarnings("unchecked") - ResponseHandler handler = (ResponseHandler) args[1]; - lcmRequestProcessor.processAsync(rpcInput, rpcName, rpcOutputType, handler); - } - else { - result = lcmRequestProcessor.processSync(rpcInput, rpcName, rpcOutputType); - } - return result; - } - - private boolean isLCMRequest(Method method) { - return method.isAnnotationPresent(RPC.class); - } - - private boolean isAsync(Method method) { - return method.getReturnType().equals(Void.TYPE); - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Action.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Action.java deleted file mode 100644 index d43a61c92..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Action.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonCreator; - -/** -* The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate -* -*/ -public enum Action { - - Restart("Restart"), - Rebuild("Rebuild"), - Migrate("Migrate"), - Evacuate("Evacuate"), - Snapshot("Snapshot"), - Rollback("Rollback"), - Sync("Sync"), - Audit("Audit"), - Stop("Stop"), - Start("Start"), - Terminate("Terminate"), - SoftwareUpload("SoftwareUpload"), - HealthCheck("HealthCheck"), - LiveUpgrade("LiveUpgrade"), - Lock("Lock"), - Unlock("Unlock"), - Test("Test"), - CheckLock("CheckLock"), - Configure("Configure"), - ConfigModify("ConfigModify"), - ConfigScaleOut("ConfigScaleOut"), - ConfigRestore("ConfigRestore"), - ConfigBackup("ConfigBackup"), - ConfigBackupDelete("ConfigBackupDelete"), - ConfigExport("ConfigExport"); - - private String value; - - Action(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static Action fromValue(String text) { - for (Action var : Action.values()) { - if (String.valueOf(var.value).equals(text)) { - return var; - } - } - return null; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ActionIdentifiers.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ActionIdentifiers.java deleted file mode 100644 index bff2c44cb..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ActionIdentifiers.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.501+05:30", - comments = "Auto-generated from Open API specification") -public class ActionIdentifiers { - - @JsonProperty("service-instance-id") - private String serviceInstanceId; - - @JsonProperty("vnf-id") - private String vnfId; - - @JsonProperty("vnfc-name") - private String vnfcName; - - @JsonProperty("vserver-id") - private String vserverId; - - /** - * identifies a specific service the command refers to. When multiple APP-C instances are used and applied to a subset of services, this will become significant . The field is mandatory when the vnf-id is empty - */ - public String getServiceInstanceId() { - return serviceInstanceId; - } - - /** - * identifies a specific service the command refers to. When multiple APP-C instances are used and applied to a subset of services, this will become significant . The field is mandatory when the vnf-id is empty - */ - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - /** - * identifies the VNF to which this action is to be applied(vnf-id uniquely identifies the service-instance referred to). Note that some actions are applied to multiple VNFs in the same service. When this is the case, vnf-id may be left out, but service-instance-id must appear. The field is mandatory when service-instance-id is empty - */ - public String getVnfId() { - return vnfId; - } - - /** - * identifies the VNF to which this action is to be applied(vnf-id uniquely identifies the service-instance referred to). Note that some actions are applied to multiple VNFs in the same service. When this is the case, vnf-id may be left out, but service-instance-id must appear. The field is mandatory when service-instance-id is empty - */ - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - /** - * identifies the VNFC to which this action is to be applied. Some actions apply only to a component within a VNF (e.g. RESTART is sometimes applied to on VM only). In such a case, the name of the VNFC is used to search for the component within the VNF - */ - public String getVnfcName() { - return vnfcName; - } - - /** - * identifies the VNFC to which this action is to be applied. Some actions apply only to a component within a VNF (e.g. RESTART is sometimes applied to on VM only). In such a case, the name of the VNFC is used to search for the component within the VNF - */ - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - /** - * identifies a specific VM within the given service/vnf to which this action is to be applied - */ - public String getVserverId() { - return vserverId; - } - - /** - * identifies a specific VM within the given service/vnf to which this action is to be applied - */ - public void setVserverId(String vserverId) { - this.vserverId = vserverId; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditInput.java deleted file mode 100644 index 2301913a9..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.512+05:30", - comments = "Auto-generated from Open API specification") -public class AuditInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditOutput.java deleted file mode 100644 index 00f4244ba..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/AuditOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.517+05:30", - comments = "Auto-generated from Open API specification") -public class AuditOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockInput.java deleted file mode 100644 index 840aad615..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockInput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.519+05:30", - comments = "Auto-generated from Open API specification") -public class CheckLockInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockOutput.java deleted file mode 100644 index 2bfdea0fe..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CheckLockOutput.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.523+05:30", - comments = "Auto-generated from Open API specification") -public class CheckLockOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - public enum Locked { - TRUE, - FALSE; - } - - @JsonProperty("locked") - private Locked locked; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * TRUE/FALSE - returns TRUE when the given VNF was locked, otherwise returns FALSE - */ - public Locked getLocked() { - return locked; - } - - /** - * TRUE/FALSE - returns TRUE when the given VNF was locked, otherwise returns FALSE - */ - public void setLocked(Locked locked) { - this.locked = locked; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CommonHeader.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CommonHeader.java deleted file mode 100644 index 43320d333..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/CommonHeader.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * A common header for all APP-C requests - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.49+05:30", - comments = "Auto-generated from Open API specification") -public class CommonHeader { - - @JsonProperty("timestamp") - private ZULU timestamp; - - @JsonProperty("api-ver") - private String apiVer; - - @JsonProperty("originator-id") - private String originatorId; - - @JsonProperty("request-id") - private String requestId; - - @JsonProperty("sub-request-id") - private String subRequestId; - - @JsonProperty("flags") - private Flags flags; - - /** - * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ - */ - public ZULU getTimestamp() { - return timestamp; - } - - /** - * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ - */ - public void setTimestamp(ZULU timestamp) { - this.timestamp = timestamp; - } - - /** - * api-ver is the API version identifier. A given release of APPC should support all previous versions of APPC API (correlate with general requirements) - */ - public String getApiVer() { - return apiVer; - } - - /** - * api-ver is the API version identifier. A given release of APPC should support all previous versions of APPC API (correlate with general requirements) - */ - public void setApiVer(String apiVer) { - this.apiVer = apiVer; - } - - /** - * originator-id an identifier of the calling system which can be used addressing purposes, i.e. returning asynchronous response to the proper destination over UEB (especially in case of multiple consumers of APP-C APIs) - */ - public String getOriginatorId() { - return originatorId; - } - - /** - * originator-id an identifier of the calling system which can be used addressing purposes, i.e. returning asynchronous response to the proper destination over UEB (especially in case of multiple consumers of APP-C APIs) - */ - public void setOriginatorId(String originatorId) { - this.originatorId = originatorId; - } - - /** - * UUID for the request ID. An OSS/BSS identifier for the request that caused the current action. Multiple API calls may be made with the same request-id The request-id shall be recorded throughout the operations on a single request - */ - public String getRequestId() { - return requestId; - } - - /** - * UUID for the request ID. An OSS/BSS identifier for the request that caused the current action. Multiple API calls may be made with the same request-id The request-id shall be recorded throughout the operations on a single request - */ - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - /** - * Uniquely identifies a specific LCM action. It is persistent over the life-cycle of a single request - */ - public String getSubRequestId() { - return subRequestId; - } - - /** - * Uniquely identifies a specific LCM action. It is persistent over the life-cycle of a single request - */ - public void setSubRequestId(String subRequestId) { - this.subRequestId = subRequestId; - } - - /** - * Flags are generic flags that apply to any and all commands, all are optional - */ - public Flags getFlags() { - return flags; - } - - /** - * Flags are generic flags that apply to any and all commands, all are optional - */ - public void setFlags(Flags flags) { - this.flags = flags; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteInput.java deleted file mode 100644 index c5f14b6ae..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteInput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.533+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigBackupDeleteInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteOutput.java deleted file mode 100644 index 730240276..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupDeleteOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.537+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigBackupDeleteOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupInput.java deleted file mode 100644 index 26f799cb4..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.526+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigBackupInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupOutput.java deleted file mode 100644 index 1768ea74d..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigBackupOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.529+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigBackupOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportInput.java deleted file mode 100644 index 5c2d98d19..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportInput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.541+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigExportInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportOutput.java deleted file mode 100644 index bbfe27af1..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigExportOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.543+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigExportOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyInput.java deleted file mode 100644 index c1a9e6be6..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.559+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigModifyInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyOutput.java deleted file mode 100644 index 356299d77..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigModifyOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.563+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigModifyOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreInput.java deleted file mode 100644 index ec26bae34..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.565+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigRestoreInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreOutput.java deleted file mode 100644 index 0646d670b..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigRestoreOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.568+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigRestoreOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutInput.java deleted file mode 100644 index 14c62689a..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.571+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigScaleoutInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutOutput.java deleted file mode 100644 index fb3f1973a..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigScaleoutOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.574+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigScaleoutOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureInput.java deleted file mode 100644 index b56d692b8..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.577+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigureInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureOutput.java deleted file mode 100644 index fcf32bf2d..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ConfigureOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.585+05:30", - comments = "Auto-generated from Open API specification") -public class ConfigureOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateInput.java deleted file mode 100644 index 85c36e8a4..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.587+05:30", - comments = "Auto-generated from Open API specification") -public class EvacuateInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateOutput.java deleted file mode 100644 index 2c73a5b84..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/EvacuateOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.59+05:30", - comments = "Auto-generated from Open API specification") -public class EvacuateOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Flags.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Flags.java deleted file mode 100644 index 01d2652dd..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Flags.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Flags are generic flags that apply to any and all commands, all are optional - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.498+05:30", - comments = "Auto-generated from Open API specification") -public class Flags { - - public enum Mode { - EXCLUSIVE, - NORMAL; - } - - @JsonProperty("mode") - private Mode mode; - - public enum Force { - TRUE, - FALSE; - } - - @JsonProperty("force") - private Force force; - - @JsonProperty("ttl") - private int ttl; - - /** - * EXCLUSIVE (accept no queued requests on this VNF while processing) or NORMAL (queue other requests until complete) - */ - public Mode getMode() { - return mode; - } - - /** - * EXCLUSIVE (accept no queued requests on this VNF while processing) or NORMAL (queue other requests until complete) - */ - public void setMode(Mode mode) { - this.mode = mode; - } - - /** - * TRUE/FALSE - Execute action even if target is in unstable (i.e. locked, transiting, etc.) state - */ - public Force getForce() { - return force; - } - - /** - * TRUE/FALSE - Execute action even if target is in unstable (i.e. locked, transiting, etc.) state - */ - public void setForce(Force force) { - this.force = force; - } - - /** - * The timeout value (expressed in seconds) for action execution, between action being received by APPC and action initiation - */ - public int getTtl() { - return ttl; - } - - /** - * The timeout value (expressed in seconds) for action execution, between action being received by APPC and action initiation - */ - public void setTtl(int ttl) { - this.ttl = ttl; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckInput.java deleted file mode 100644 index 7bd3207cb..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.593+05:30", - comments = "Auto-generated from Open API specification") -public class HealthCheckInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckOutput.java deleted file mode 100644 index 41a907c71..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/HealthCheckOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.596+05:30", - comments = "Auto-generated from Open API specification") -public class HealthCheckOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeInput.java deleted file mode 100644 index 82a971bc7..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.602+05:30", - comments = "Auto-generated from Open API specification") -public class LiveUpgradeInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeOutput.java deleted file mode 100644 index 809adcd8f..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LiveUpgradeOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.604+05:30", - comments = "Auto-generated from Open API specification") -public class LiveUpgradeOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockInput.java deleted file mode 100644 index f6f68d2c6..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.607+05:30", - comments = "Auto-generated from Open API specification") -public class LockInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockOutput.java deleted file mode 100644 index 0f77bced6..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/LockOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.609+05:30", - comments = "Auto-generated from Open API specification") -public class LockOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateInput.java deleted file mode 100644 index 5877aab07..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.612+05:30", - comments = "Auto-generated from Open API specification") -public class MigrateInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateOutput.java deleted file mode 100644 index 4d804db9a..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/MigrateOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.615+05:30", - comments = "Auto-generated from Open API specification") -public class MigrateOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Payload.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Payload.java deleted file mode 100644 index 56ce6c529..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Payload.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.472+05:30", - comments = "Auto-generated from Open API specification") -public class Payload { - - private String value; - - public Payload() {} - - @JsonCreator - public Payload(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildInput.java deleted file mode 100644 index ecd199dee..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.618+05:30", - comments = "Auto-generated from Open API specification") -public class RebuildInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildOutput.java deleted file mode 100644 index 0816c5b87..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RebuildOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.621+05:30", - comments = "Auto-generated from Open API specification") -public class RebuildOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartInput.java deleted file mode 100644 index 4df2184c4..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.623+05:30", - comments = "Auto-generated from Open API specification") -public class RestartInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartOutput.java deleted file mode 100644 index 8c44631dd..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RestartOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.629+05:30", - comments = "Auto-generated from Open API specification") -public class RestartOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackInput.java deleted file mode 100644 index db688c0ec..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackInput.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.653+05:30", - comments = "Auto-generated from Open API specification") -public class RollbackInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - @JsonProperty("identity-url") - private String identityUrl; - - @JsonProperty("snapshot-id") - private String snapshotId; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - - public String getIdentityUrl() { - return identityUrl; - } - - public void setIdentityUrl(String identityUrl) { - this.identityUrl = identityUrl; - } - - public String getSnapshotId() { - return snapshotId; - } - - public void setSnapshotId(String snapshotId) { - this.snapshotId = snapshotId; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackOutput.java deleted file mode 100644 index 21aa1f08f..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/RollbackOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.656+05:30", - comments = "Auto-generated from Open API specification") -public class RollbackOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotInput.java deleted file mode 100644 index b3492c2dd..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotInput.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.659+05:30", - comments = "Auto-generated from Open API specification") -public class SnapshotInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - @JsonProperty("identity-url") - private String identityUrl; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - - public String getIdentityUrl() { - return identityUrl; - } - - public void setIdentityUrl(String identityUrl) { - this.identityUrl = identityUrl; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotOutput.java deleted file mode 100644 index 9036b2607..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SnapshotOutput.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.665+05:30", - comments = "Auto-generated from Open API specification") -public class SnapshotOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("snapshot-id") - private String snapshotId; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - public String getSnapshotId() { - return snapshotId; - } - - public void setSnapshotId(String snapshotId) { - this.snapshotId = snapshotId; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadInput.java deleted file mode 100644 index 270121a96..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.668+05:30", - comments = "Auto-generated from Open API specification") -public class SoftwareUploadInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadOutput.java deleted file mode 100644 index 8e32dd3a2..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SoftwareUploadOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.672+05:30", - comments = "Auto-generated from Open API specification") -public class SoftwareUploadOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationInput.java deleted file mode 100644 index dca0bc47b..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-07-19T14:31:26.579+05:30", - comments = "Auto-generated from Open API specification") -public class StartApplicationInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationOutput.java deleted file mode 100644 index 061f2476e..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartApplicationOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-07-19T14:31:26.58+05:30", - comments = "Auto-generated from Open API specification") -public class StartApplicationOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartInput.java deleted file mode 100644 index 3e0829b52..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.675+05:30", - comments = "Auto-generated from Open API specification") -public class StartInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartOutput.java deleted file mode 100644 index 1efcae95d..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StartOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.679+05:30", - comments = "Auto-generated from Open API specification") -public class StartOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Status.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Status.java deleted file mode 100644 index 85f64c790..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/Status.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.507+05:30", - comments = "Auto-generated from Open API specification") -public class Status { - - @JsonProperty("code") - private int code; - - @JsonProperty("message") - private String message; - - /** - * Response code - */ - public int getCode() { - return code; - } - - /** - * Response code - */ - public void setCode(int code) { - this.code = code; - } - - /** - * Response message - */ - public String getMessage() { - return message; - } - - /** - * Response message - */ - public void setMessage(String message) { - this.message = message; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationInput.java deleted file mode 100644 index dc9bf4840..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-07-19T14:31:26.586+05:30", - comments = "Auto-generated from Open API specification") -public class StopApplicationInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationOutput.java deleted file mode 100644 index d0193a16d..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopApplicationOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-07-19T14:31:26.588+05:30", - comments = "Auto-generated from Open API specification") -public class StopApplicationOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopInput.java deleted file mode 100644 index f5477405e..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.689+05:30", - comments = "Auto-generated from Open API specification") -public class StopInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopOutput.java deleted file mode 100644 index 9160a98f7..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/StopOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.692+05:30", - comments = "Auto-generated from Open API specification") -public class StopOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncInput.java deleted file mode 100644 index 2928c76a2..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.695+05:30", - comments = "Auto-generated from Open API specification") -public class SyncInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncOutput.java deleted file mode 100644 index 82347d295..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/SyncOutput.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.698+05:30", - comments = "Auto-generated from Open API specification") -public class SyncOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateInput.java deleted file mode 100644 index de45dddda..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.701+05:30", - comments = "Auto-generated from Open API specification") -public class TerminateInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateOutput.java deleted file mode 100644 index 1a78f0e3f..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TerminateOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.704+05:30", - comments = "Auto-generated from Open API specification") -public class TerminateOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestInput.java deleted file mode 100644 index 33dab668e..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.706+05:30", - comments = "Auto-generated from Open API specification") -public class TestInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestOutput.java deleted file mode 100644 index 283a92d7e..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/TestOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.708+05:30", - comments = "Auto-generated from Open API specification") -public class TestOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockInput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockInput.java deleted file mode 100644 index b03c683b7..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockInput.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.711+05:30", - comments = "Auto-generated from Open API specification") -public class UnlockInput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action") - private Action action; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("payload") - private Payload payload; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public Action getAction() { - return action; - } - - /** - * The action to be taken by APP-C, e.g. Restart, Rebuild, Migrate - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - /** - * A block containing the action arguments. These are used to specify the object upon which APP-C LCM command is to operate - */ - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public Payload getPayload() { - return payload; - } - - /** - * The payload can be any valid JSON string value. Json escape characters need to be added when required to include an inner json within the payload to make it a valid json string value - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockOutput.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockOutput.java deleted file mode 100644 index 9830c8f87..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/UnlockOutput.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.716+05:30", - comments = "Auto-generated from Open API specification") -public class UnlockOutput { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("status") - private Status status; - - /** - * A common header for all APP-C requests - */ - public CommonHeader getCommonHeader() { - return commonHeader; - } - - /** - * A common header for all APP-C requests - */ - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public Status getStatus() { - return status; - } - - /** - * The specific response codes are to be aligned with ASDC reference doc (main table removed to avoid duplication and digression from main table). See ASDC and ECOMP Distribution Consumer Interface Agreement - */ - public void setStatus(Status status) { - this.status = status; - } - -} diff --git a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ZULU.java b/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ZULU.java deleted file mode 100644 index 416b56a20..000000000 --- a/appc-client/client-kit/src/main/java/org/openecomp/appc/client/lcm/model/ZULU.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * NOTE: This file is auto-generated and should not be changed manually. - */ -package org.onap.appc.client.lcm.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Define a common definition of a time stamp (expressed as a formatted string) as follows yyyy-MM-ddTHH:mm:ss.SSSSSSSSZ - */ -@javax.annotation.Generated( - value = {"templates/client-kit/open-api-to-java.ftl"}, - date = "2017-05-04T20:09:01.441+05:30", - comments = "Auto-generated from Open API specification") -public class ZULU { - - private String value; - - public ZULU() {} - - @JsonCreator - public ZULU(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java b/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java new file mode 100644 index 000000000..6b24b0a83 --- /dev/null +++ b/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java @@ -0,0 +1,60 @@ +package org.onap.appc.client.lcm.impl.business; + + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.client.lcm.api.ApplicationContext; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.onap.appc.client.lcm.impl.business.LCMRequestProcessor; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class TestAppcLifeCycleManagerServiceFactoryImpl { + + AppcLifeCycleManagerServiceFactoryImpl appcLifeCycleManagerServiceFactory=new AppcLifeCycleManagerServiceFactoryImpl(); + + @Ignore + public void testCreateLifeCycleManagerStateful() throws AppcClientException{ + LifeCycleManagerStateful lifeCycleManagerStateful; + ApplicationContext applicationContext=new ApplicationContext(); + applicationContext.setApplicationID("AppID"); + applicationContext.setMechID("mechId"); + String folder="src/test/resources/data"; + Properties properties =getProperties(folder); + lifeCycleManagerStateful=appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(applicationContext,properties); + + Assert.assertNotNull(lifeCycleManagerStateful); + + } + + public static Properties getProperties(String folder) { + Properties prop = new Properties(); + + InputStream conf = null; + try { + conf = new FileInputStream(folder + "client-simulator.properties"); + } catch (FileNotFoundException e) { + + } + if (conf != null) { + try { + prop.load(conf); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); + } catch (Exception e) { + throw new RuntimeException("### ERROR ### - Could not load properties to test"); + } + } + return prop; + } +} diff --git a/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/model/TestModelPOJO.java b/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/model/TestModelPOJO.java new file mode 100644 index 000000000..9cb3b9f56 --- /dev/null +++ b/appc-client/client-kit/src/test/java/org/onap/appc/client/lcm/model/TestModelPOJO.java @@ -0,0 +1,144 @@ +package org.onap.appc.client.lcm.model; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +public class TestModelPOJO { + static List pojoClassName; + static List fields; + static{ + pojoClassName = new ArrayList<>(); + pojoClassName.add(AuditInput.class); + pojoClassName.add(AuditOutput.class); + pojoClassName.add(CheckLockInput.class); + pojoClassName.add(CheckLockOutput.class); + pojoClassName.add(ConfigBackupDeleteInput.class); + pojoClassName.add(ConfigBackupDeleteOutput.class); + pojoClassName.add(ConfigBackupInput.class); + pojoClassName.add(ConfigBackupOutput.class); + pojoClassName.add(ConfigExportInput.class); + pojoClassName.add(ConfigExportOutput.class); + pojoClassName.add(ConfigModifyInput.class); + pojoClassName.add(ConfigModifyOutput.class); + pojoClassName.add(ConfigRestoreInput.class); + pojoClassName.add(ConfigRestoreOutput.class); + pojoClassName.add(ConfigScaleoutInput.class); + pojoClassName.add(ConfigScaleoutOutput.class); + pojoClassName.add(ConfigureInput.class); + pojoClassName.add(ConfigureOutput.class); + pojoClassName.add(EvacuateInput.class); + pojoClassName.add(EvacuateOutput.class); + pojoClassName.add(HealthCheckInput.class); + pojoClassName.add(HealthCheckOutput.class); + pojoClassName.add(LiveUpgradeInput.class); + pojoClassName.add(LiveUpgradeOutput.class); + pojoClassName.add(LockInput.class); + pojoClassName.add(LockOutput.class); + pojoClassName.add(MigrateInput.class); + pojoClassName.add(MigrateOutput.class); + pojoClassName.add(RebuildInput.class); + pojoClassName.add(RebuildOutput.class); + pojoClassName.add(HealthCheckInput.class); + pojoClassName.add(RollbackInput.class); + pojoClassName.add(RollbackOutput.class); + pojoClassName.add(RestartInput.class); + pojoClassName.add(RestartOutput.class); + pojoClassName.add(SnapshotInput.class); + pojoClassName.add(SnapshotOutput.class); + pojoClassName.add(SoftwareUploadInput.class); + pojoClassName.add(SoftwareUploadOutput.class); + pojoClassName.add(StartApplicationInput.class); + pojoClassName.add(StartApplicationOutput.class); + pojoClassName.add(StartInput.class); + pojoClassName.add(StartOutput.class); + pojoClassName.add(StopApplicationInput.class); + pojoClassName.add(StopApplicationOutput.class); + pojoClassName.add(StopInput.class); + pojoClassName.add(SyncInput.class); + pojoClassName.add(SyncOutput.class); + pojoClassName.add(TerminateInput.class); + pojoClassName.add(TerminateOutput.class); + pojoClassName.add(TestInput.class); + pojoClassName.add(TestOutput.class); + pojoClassName.add(UnlockInput.class); + pojoClassName.add(UnlockOutput.class); + + fields = new ArrayList<>(); + fields.add("CommonHeader"); + fields.add("Action"); + fields.add("Payload"); + fields.add("Status"); + } + @Test + public void testModel() throws Exception{ + for(String field: fields){ + for(Class c: pojoClassName){ + Object instance = c.newInstance(); + Field[] fields = c.getDeclaredFields(); + for(Field f: fields){ + if(f.getType() == getClassForString(field)){ + Method m = c.getDeclaredMethod("set"+field,getClassForString(field)); + Object argument = createArgument(field); + m.invoke(instance,argument); + + Method getter = c.getDeclaredMethod("get"+field); + Object getValue = getter.invoke(instance); + Assert.assertEquals("POJO test failed for class:"+c.getCanonicalName()+" for method:"+m.getName(),argument, getValue); + } + } + } + } + } + + private Object createArgument(String field){ + if(field.equals("CommonHeader")){ + return createHeader(); + } + else if(field.equals("Action")){ + return createAction(); + }else if(field.equals("Payload")){ + return createPayload(); + }else if(field.equals("Status")){ + return createStatus(); + } + + throw new IllegalArgumentException(); + } + + private Action createAction(){ + return Action.Restart; + } + private Payload createPayload(){ + return new Payload(); + } + private CommonHeader createHeader(){ + CommonHeader header = new CommonHeader(); + header.setApiVer("apiver"); + header.setOriginatorId("originator"); + return header; + } + private Status createStatus() { + return new Status(); + } + + private Class getClassForString(String field){ + + if(field.equals("CommonHeader")){ + return CommonHeader.class; + }else if(field.equals("Action")){ + return Action.class; + }else if(field.equals("ActionIdentifiers")){ + return ActionIdentifiers.class; + }else if(field.equals("Payload")){ + return Payload.class; + }else if(field.equals("Status")){ + return Status.class; + } + throw new IllegalArgumentException(); + } +} diff --git a/appc-client/client-kit/src/test/java/org/onap/appc/generator/JsonHelper.java b/appc-client/client-kit/src/test/java/org/onap/appc/generator/JsonHelper.java new file mode 100644 index 000000000..e75a44e65 --- /dev/null +++ b/appc-client/client-kit/src/test/java/org/onap/appc/generator/JsonHelper.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.generator; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +public class JsonHelper { + + private enum PopulateType{ + PARAMETER, + SCHEMA_REF, + ; + } + + public static void populateRpcInputOutputParamsFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams) { + populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams,PopulateType.PARAMETER,false); + } + public static void populateRpcInputOutputSchemaRefFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams) { + populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams,PopulateType.SCHEMA_REF,true); + } + public static void populateRpcInputOutputParamsFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams,PopulateType populateType,boolean normalizeRpcOperation) { + //get all yang2json Input and output Params and populate jsonBodyInputParams & jsonBodyOutputParams + for(Iterator pathsElements = jsonNode.get("paths").elements(); pathsElements.hasNext(); ){ + JsonNode pathNode = pathsElements.next(); + String rpcOperation = pathNode.get("post").get("operationId").textValue(); + String bodyInputSchemaRef = pathNode.get("post").get("parameters").get(0).get("schema").get("properties").get("input").get("$ref").textValue(); + String bodyInputSchemaRefSuffix = JsonHelper.getStringSuffix(bodyInputSchemaRef,"/"); + rpcOperation = normalizeRpcOperation ? rpcOperation.replaceAll(Pattern.quote("-"),"").toLowerCase() : rpcOperation; + + String bodyOutputSchemaRef = pathNode.get("post").get("responses").get("200").get("schema").get("properties").get("output").get("$ref").textValue(); + String bodyOutputSchemaRefSuffix = JsonHelper.getStringSuffix(bodyOutputSchemaRef,"/"); + + Set inputParametersOrSchemaRef; + Set outputParametersOrSchemaRef; + if(populateType == PopulateType.SCHEMA_REF){ + inputParametersOrSchemaRef = new HashSet(); + inputParametersOrSchemaRef.add(bodyInputSchemaRefSuffix); + + outputParametersOrSchemaRef = new HashSet(); + outputParametersOrSchemaRef.add(bodyOutputSchemaRefSuffix); + }else{ + inputParametersOrSchemaRef = extractParams(jsonNode,bodyInputSchemaRefSuffix); + outputParametersOrSchemaRef = extractParams(jsonNode,bodyOutputSchemaRefSuffix); + } + jsonBodyInputParams.put(rpcOperation,inputParametersOrSchemaRef); + jsonBodyOutputParams.put(rpcOperation,outputParametersOrSchemaRef); + } + } + + private static Set extractParams(final JsonNode jsonNode,String schemaRefName) { + Iterator> fields = jsonNode.get("definitions").get(schemaRefName).get("properties").fields(); + Set params = new HashSet(); + for( ;fields.hasNext(); ){ + Map.Entry fieldEntry = fields.next(); + params.add(fieldEntry.getKey()); + } + return params; + } + + public static String getStringSuffix(String input, String afterString){ + int indexOf = input.lastIndexOf(afterString); + String stringSuffix = (indexOf > -1) ? input.substring(indexOf+1) : input; + return stringSuffix; + } +} diff --git a/appc-client/client-kit/src/test/java/org/onap/appc/generator/yang2json/Yang2JsonGeneratorTest.java b/appc-client/client-kit/src/test/java/org/onap/appc/generator/yang2json/Yang2JsonGeneratorTest.java new file mode 100644 index 000000000..ff3a4ccb6 --- /dev/null +++ b/appc-client/client-kit/src/test/java/org/onap/appc/generator/yang2json/Yang2JsonGeneratorTest.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.generator.yang2json; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Optional; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.RpcDefinition; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException; +import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; +import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; +import org.onap.appc.generator.JsonHelper; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; + +public class Yang2JsonGeneratorTest { + + private static SchemaContext yangSchema = null; + private static JsonNode jsonNode = null; + + public void readIOfiles() throws IOException{ + if(yangSchema == null){ + yangParse(); + } + if(jsonNode == null){ + jsonRead(); + } + + } + + public void testJsonRpcNum(){ + + int rpcYangNum = yangSchema.getModules().iterator().next().getRpcs().size(); + int rpcJsonNum = jsonNode.get("paths").size(); + Assert.assertTrue(rpcYangNum == rpcJsonNum); + } + + public void testJsonRpcsAndInOutParams(){ + + Map /*bodyInputParams*/> jsonBodyInputParams = new HashMap(); + Map /*bodyOutputParams*/> jsonBodyOutputParams= new HashMap(); + JsonHelper.populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams); + + Set rpcDefinitions = yangSchema.getModules().iterator().next().getRpcs(); + for(RpcDefinition rpcDef : rpcDefinitions){ + String rpcOperation = rpcDef.getQName().getLocalName(); + //verify all yang rpc operations & all input yang params/groupings exist in yang2json + Assert.assertTrue(jsonBodyInputParams.containsKey(rpcOperation)); + Collection inputChildNodes = rpcDef.getInput().getChildNodes(); + if(inputChildNodes != null || !inputChildNodes.isEmpty()) { + Assert.assertTrue(rpcOperation+": yang and yang2json input params size is not equal!",jsonBodyInputParams.get(rpcOperation).size() == inputChildNodes.size()); + Set inputYangParams = getYangParams(inputChildNodes); + Assert.assertTrue(rpcOperation+": yang and yang2json input params are not same!",jsonBodyInputParams.get(rpcOperation).containsAll(inputYangParams)); + } + + //verify all yang rpc operations & all output yang params/groupings exist in yang2json + Assert.assertTrue(jsonBodyOutputParams.containsKey(rpcOperation)); + Collection outputChildNodes = rpcDef.getOutput().getChildNodes(); + if(outputChildNodes != null || !outputChildNodes.isEmpty()) { + Assert.assertTrue(rpcOperation+": yang and yang2json output params size is not equal!",jsonBodyOutputParams.get(rpcOperation).size()== outputChildNodes.size()); + Set outputYangParams = getYangParams(outputChildNodes); + Assert.assertTrue(rpcOperation+": yang and yang2json output params are not same!",jsonBodyOutputParams.get(rpcOperation).containsAll(outputYangParams)); + } + } + } + + + private Set getYangParams(Collection dataSchemaNodes) { + Set yangParams = new HashSet(); + for(DataSchemaNode child : dataSchemaNodes){ + yangParams.add(child.getQName().getLocalName()); + } + return yangParams; + } + + + + private static void yangParse(){ + + try { + //sourceFileName + String yangFileName = System.getProperty("inputFile"); + YangTextSchemaContextResolver yangContextResolver = null; + yangContextResolver = YangTextSchemaContextResolver.create("yang-context-resolver"); + URL url = new File(yangFileName).toURI().toURL(); + yangContextResolver.registerSource(url); + Optional yangSchemaContext = yangContextResolver.getSchemaContext(); + yangSchema = yangSchemaContext.get(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (YangSyntaxErrorException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SchemaSourceException e) { + e.printStackTrace(); + } + + + } + + + private static void jsonRead ()throws IOException { + String jsonFilePath = System.getProperty("outputFile"); + File file = new File(jsonFilePath); + ObjectMapper mapper = new ObjectMapper(); + jsonNode = mapper.readTree(file); + } +} diff --git a/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java b/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java deleted file mode 100644 index 6b24b0a83..000000000 --- a/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/impl/business/TestAppcLifeCycleManagerServiceFactoryImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.onap.appc.client.lcm.impl.business; - - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.client.lcm.api.ApplicationContext; -import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import org.onap.appc.client.lcm.impl.business.LCMRequestProcessor; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class TestAppcLifeCycleManagerServiceFactoryImpl { - - AppcLifeCycleManagerServiceFactoryImpl appcLifeCycleManagerServiceFactory=new AppcLifeCycleManagerServiceFactoryImpl(); - - @Ignore - public void testCreateLifeCycleManagerStateful() throws AppcClientException{ - LifeCycleManagerStateful lifeCycleManagerStateful; - ApplicationContext applicationContext=new ApplicationContext(); - applicationContext.setApplicationID("AppID"); - applicationContext.setMechID("mechId"); - String folder="src/test/resources/data"; - Properties properties =getProperties(folder); - lifeCycleManagerStateful=appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(applicationContext,properties); - - Assert.assertNotNull(lifeCycleManagerStateful); - - } - - public static Properties getProperties(String folder) { - Properties prop = new Properties(); - - InputStream conf = null; - try { - conf = new FileInputStream(folder + "client-simulator.properties"); - } catch (FileNotFoundException e) { - - } - if (conf != null) { - try { - prop.load(conf); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); - } catch (Exception e) { - throw new RuntimeException("### ERROR ### - Could not load properties to test"); - } - } - return prop; - } -} diff --git a/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/model/TestModelPOJO.java b/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/model/TestModelPOJO.java deleted file mode 100644 index 9cb3b9f56..000000000 --- a/appc-client/client-kit/src/test/java/org/openecomp/appc/client/lcm/model/TestModelPOJO.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.onap.appc.client.lcm.model; - -import org.junit.Assert; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -public class TestModelPOJO { - static List pojoClassName; - static List fields; - static{ - pojoClassName = new ArrayList<>(); - pojoClassName.add(AuditInput.class); - pojoClassName.add(AuditOutput.class); - pojoClassName.add(CheckLockInput.class); - pojoClassName.add(CheckLockOutput.class); - pojoClassName.add(ConfigBackupDeleteInput.class); - pojoClassName.add(ConfigBackupDeleteOutput.class); - pojoClassName.add(ConfigBackupInput.class); - pojoClassName.add(ConfigBackupOutput.class); - pojoClassName.add(ConfigExportInput.class); - pojoClassName.add(ConfigExportOutput.class); - pojoClassName.add(ConfigModifyInput.class); - pojoClassName.add(ConfigModifyOutput.class); - pojoClassName.add(ConfigRestoreInput.class); - pojoClassName.add(ConfigRestoreOutput.class); - pojoClassName.add(ConfigScaleoutInput.class); - pojoClassName.add(ConfigScaleoutOutput.class); - pojoClassName.add(ConfigureInput.class); - pojoClassName.add(ConfigureOutput.class); - pojoClassName.add(EvacuateInput.class); - pojoClassName.add(EvacuateOutput.class); - pojoClassName.add(HealthCheckInput.class); - pojoClassName.add(HealthCheckOutput.class); - pojoClassName.add(LiveUpgradeInput.class); - pojoClassName.add(LiveUpgradeOutput.class); - pojoClassName.add(LockInput.class); - pojoClassName.add(LockOutput.class); - pojoClassName.add(MigrateInput.class); - pojoClassName.add(MigrateOutput.class); - pojoClassName.add(RebuildInput.class); - pojoClassName.add(RebuildOutput.class); - pojoClassName.add(HealthCheckInput.class); - pojoClassName.add(RollbackInput.class); - pojoClassName.add(RollbackOutput.class); - pojoClassName.add(RestartInput.class); - pojoClassName.add(RestartOutput.class); - pojoClassName.add(SnapshotInput.class); - pojoClassName.add(SnapshotOutput.class); - pojoClassName.add(SoftwareUploadInput.class); - pojoClassName.add(SoftwareUploadOutput.class); - pojoClassName.add(StartApplicationInput.class); - pojoClassName.add(StartApplicationOutput.class); - pojoClassName.add(StartInput.class); - pojoClassName.add(StartOutput.class); - pojoClassName.add(StopApplicationInput.class); - pojoClassName.add(StopApplicationOutput.class); - pojoClassName.add(StopInput.class); - pojoClassName.add(SyncInput.class); - pojoClassName.add(SyncOutput.class); - pojoClassName.add(TerminateInput.class); - pojoClassName.add(TerminateOutput.class); - pojoClassName.add(TestInput.class); - pojoClassName.add(TestOutput.class); - pojoClassName.add(UnlockInput.class); - pojoClassName.add(UnlockOutput.class); - - fields = new ArrayList<>(); - fields.add("CommonHeader"); - fields.add("Action"); - fields.add("Payload"); - fields.add("Status"); - } - @Test - public void testModel() throws Exception{ - for(String field: fields){ - for(Class c: pojoClassName){ - Object instance = c.newInstance(); - Field[] fields = c.getDeclaredFields(); - for(Field f: fields){ - if(f.getType() == getClassForString(field)){ - Method m = c.getDeclaredMethod("set"+field,getClassForString(field)); - Object argument = createArgument(field); - m.invoke(instance,argument); - - Method getter = c.getDeclaredMethod("get"+field); - Object getValue = getter.invoke(instance); - Assert.assertEquals("POJO test failed for class:"+c.getCanonicalName()+" for method:"+m.getName(),argument, getValue); - } - } - } - } - } - - private Object createArgument(String field){ - if(field.equals("CommonHeader")){ - return createHeader(); - } - else if(field.equals("Action")){ - return createAction(); - }else if(field.equals("Payload")){ - return createPayload(); - }else if(field.equals("Status")){ - return createStatus(); - } - - throw new IllegalArgumentException(); - } - - private Action createAction(){ - return Action.Restart; - } - private Payload createPayload(){ - return new Payload(); - } - private CommonHeader createHeader(){ - CommonHeader header = new CommonHeader(); - header.setApiVer("apiver"); - header.setOriginatorId("originator"); - return header; - } - private Status createStatus() { - return new Status(); - } - - private Class getClassForString(String field){ - - if(field.equals("CommonHeader")){ - return CommonHeader.class; - }else if(field.equals("Action")){ - return Action.class; - }else if(field.equals("ActionIdentifiers")){ - return ActionIdentifiers.class; - }else if(field.equals("Payload")){ - return Payload.class; - }else if(field.equals("Status")){ - return Status.class; - } - throw new IllegalArgumentException(); - } -} diff --git a/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/JsonHelper.java b/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/JsonHelper.java deleted file mode 100644 index e75a44e65..000000000 --- a/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/JsonHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.generator; - -import com.fasterxml.jackson.databind.JsonNode; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -public class JsonHelper { - - private enum PopulateType{ - PARAMETER, - SCHEMA_REF, - ; - } - - public static void populateRpcInputOutputParamsFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams) { - populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams,PopulateType.PARAMETER,false); - } - public static void populateRpcInputOutputSchemaRefFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams) { - populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams,PopulateType.SCHEMA_REF,true); - } - public static void populateRpcInputOutputParamsFromJson(final JsonNode jsonNode, Map> jsonBodyInputParams, Map> jsonBodyOutputParams,PopulateType populateType,boolean normalizeRpcOperation) { - //get all yang2json Input and output Params and populate jsonBodyInputParams & jsonBodyOutputParams - for(Iterator pathsElements = jsonNode.get("paths").elements(); pathsElements.hasNext(); ){ - JsonNode pathNode = pathsElements.next(); - String rpcOperation = pathNode.get("post").get("operationId").textValue(); - String bodyInputSchemaRef = pathNode.get("post").get("parameters").get(0).get("schema").get("properties").get("input").get("$ref").textValue(); - String bodyInputSchemaRefSuffix = JsonHelper.getStringSuffix(bodyInputSchemaRef,"/"); - rpcOperation = normalizeRpcOperation ? rpcOperation.replaceAll(Pattern.quote("-"),"").toLowerCase() : rpcOperation; - - String bodyOutputSchemaRef = pathNode.get("post").get("responses").get("200").get("schema").get("properties").get("output").get("$ref").textValue(); - String bodyOutputSchemaRefSuffix = JsonHelper.getStringSuffix(bodyOutputSchemaRef,"/"); - - Set inputParametersOrSchemaRef; - Set outputParametersOrSchemaRef; - if(populateType == PopulateType.SCHEMA_REF){ - inputParametersOrSchemaRef = new HashSet(); - inputParametersOrSchemaRef.add(bodyInputSchemaRefSuffix); - - outputParametersOrSchemaRef = new HashSet(); - outputParametersOrSchemaRef.add(bodyOutputSchemaRefSuffix); - }else{ - inputParametersOrSchemaRef = extractParams(jsonNode,bodyInputSchemaRefSuffix); - outputParametersOrSchemaRef = extractParams(jsonNode,bodyOutputSchemaRefSuffix); - } - jsonBodyInputParams.put(rpcOperation,inputParametersOrSchemaRef); - jsonBodyOutputParams.put(rpcOperation,outputParametersOrSchemaRef); - } - } - - private static Set extractParams(final JsonNode jsonNode,String schemaRefName) { - Iterator> fields = jsonNode.get("definitions").get(schemaRefName).get("properties").fields(); - Set params = new HashSet(); - for( ;fields.hasNext(); ){ - Map.Entry fieldEntry = fields.next(); - params.add(fieldEntry.getKey()); - } - return params; - } - - public static String getStringSuffix(String input, String afterString){ - int indexOf = input.lastIndexOf(afterString); - String stringSuffix = (indexOf > -1) ? input.substring(indexOf+1) : input; - return stringSuffix; - } -} diff --git a/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/yang2json/Yang2JsonGeneratorTest.java b/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/yang2json/Yang2JsonGeneratorTest.java deleted file mode 100644 index ff3a4ccb6..000000000 --- a/appc-client/client-kit/src/test/java/org/openecomp/appc/generator/yang2json/Yang2JsonGeneratorTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.generator.yang2json; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Optional; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.RpcDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; -import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; -import org.onap.appc.generator.JsonHelper; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.*; - -public class Yang2JsonGeneratorTest { - - private static SchemaContext yangSchema = null; - private static JsonNode jsonNode = null; - - public void readIOfiles() throws IOException{ - if(yangSchema == null){ - yangParse(); - } - if(jsonNode == null){ - jsonRead(); - } - - } - - public void testJsonRpcNum(){ - - int rpcYangNum = yangSchema.getModules().iterator().next().getRpcs().size(); - int rpcJsonNum = jsonNode.get("paths").size(); - Assert.assertTrue(rpcYangNum == rpcJsonNum); - } - - public void testJsonRpcsAndInOutParams(){ - - Map /*bodyInputParams*/> jsonBodyInputParams = new HashMap(); - Map /*bodyOutputParams*/> jsonBodyOutputParams= new HashMap(); - JsonHelper.populateRpcInputOutputParamsFromJson(jsonNode,jsonBodyInputParams, jsonBodyOutputParams); - - Set rpcDefinitions = yangSchema.getModules().iterator().next().getRpcs(); - for(RpcDefinition rpcDef : rpcDefinitions){ - String rpcOperation = rpcDef.getQName().getLocalName(); - //verify all yang rpc operations & all input yang params/groupings exist in yang2json - Assert.assertTrue(jsonBodyInputParams.containsKey(rpcOperation)); - Collection inputChildNodes = rpcDef.getInput().getChildNodes(); - if(inputChildNodes != null || !inputChildNodes.isEmpty()) { - Assert.assertTrue(rpcOperation+": yang and yang2json input params size is not equal!",jsonBodyInputParams.get(rpcOperation).size() == inputChildNodes.size()); - Set inputYangParams = getYangParams(inputChildNodes); - Assert.assertTrue(rpcOperation+": yang and yang2json input params are not same!",jsonBodyInputParams.get(rpcOperation).containsAll(inputYangParams)); - } - - //verify all yang rpc operations & all output yang params/groupings exist in yang2json - Assert.assertTrue(jsonBodyOutputParams.containsKey(rpcOperation)); - Collection outputChildNodes = rpcDef.getOutput().getChildNodes(); - if(outputChildNodes != null || !outputChildNodes.isEmpty()) { - Assert.assertTrue(rpcOperation+": yang and yang2json output params size is not equal!",jsonBodyOutputParams.get(rpcOperation).size()== outputChildNodes.size()); - Set outputYangParams = getYangParams(outputChildNodes); - Assert.assertTrue(rpcOperation+": yang and yang2json output params are not same!",jsonBodyOutputParams.get(rpcOperation).containsAll(outputYangParams)); - } - } - } - - - private Set getYangParams(Collection dataSchemaNodes) { - Set yangParams = new HashSet(); - for(DataSchemaNode child : dataSchemaNodes){ - yangParams.add(child.getQName().getLocalName()); - } - return yangParams; - } - - - - private static void yangParse(){ - - try { - //sourceFileName - String yangFileName = System.getProperty("inputFile"); - YangTextSchemaContextResolver yangContextResolver = null; - yangContextResolver = YangTextSchemaContextResolver.create("yang-context-resolver"); - URL url = new File(yangFileName).toURI().toURL(); - yangContextResolver.registerSource(url); - Optional yangSchemaContext = yangContextResolver.getSchemaContext(); - yangSchema = yangSchemaContext.get(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (YangSyntaxErrorException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (SchemaSourceException e) { - e.printStackTrace(); - } - - - } - - - private static void jsonRead ()throws IOException { - String jsonFilePath = System.getProperty("outputFile"); - File file = new File(jsonFilePath); - ObjectMapper mapper = new ObjectMapper(); - jsonNode = mapper.readTree(file); - } -} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AbstractRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AbstractRequestResponseHandler.java new file mode 100644 index 000000000..c5d6120f0 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AbstractRequestResponseHandler.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** Abstract request response handler class, responsible for common functionality of + * @{@link AsyncRequestResponseHandler} and @{@link SyncRequestResponseHandler} + */ +abstract class AbstractRequestResponseHandler implements RequestResponseHandler { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractRequestResponseHandler.class); + ICoreResponseHandler businessCallback; + protected String corrID; + CoreManager coreManager; + + + AbstractRequestResponseHandler(String corrID, + ICoreResponseHandler businessCallback, + CoreManager coreManager) + { + this.businessCallback = businessCallback; + this.corrID = corrID; + this.coreManager = coreManager; + } + + public synchronized void handleResponse(final MessageContext ctx, final String response) { + try { + coreManager.submitTask(ctx.getCorrelationID(), new Runnable() { + @Override + public void run() { + LOG.info("handling response of corrID <" + corrID + ">" + "response " + response); + if(coreManager.isExistHandler(corrID)) { + runTask(response, ctx.getType()); + } + + } + }); + } catch (InterruptedException e) { + LOG.error("could not handle response <" + response + "> of corrID <" + corrID + ">", e); + } + } + + /** + * + * @param response - Response + * @param type - Type of Response + */ + abstract void runTask(String response, String type); + + @Override + public void sendRequest(String request, String corrId, String rpcName) throws CoreException { + if(!coreManager.isShutdownInProgress()) { + coreManager.registerHandler(corrId, this); + coreManager.sendRequest(request, corrId, rpcName); + coreManager.startTimer(corrId); + }else{ + throw new CoreException("Shutdown is in progress. Request will not be handled"); + } + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AsyncRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AsyncRequestResponseHandler.java new file mode 100644 index 000000000..1bcf0af99 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/AsyncRequestResponseHandler.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.TimeoutException; + +/** Handles async responses + */ +class AsyncRequestResponseHandler extends AbstractRequestResponseHandler { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(AsyncRequestResponseHandler.class); + + AsyncRequestResponseHandler(String corrID, + ICoreResponseHandler businessCallback, + CoreManager coreManager) + { + super(corrID, businessCallback, coreManager); + } + + /** + * Calls API callback for sending response to consumer's listener. in case of complete response cleans timer and + * unregisters the handler. + * @param response - Response + * @param type - Type of Response + */ + public void runTask(String response, String type) { + boolean finalTask = false; + try { + finalTask = ((ICoreAsyncResponseHandler) businessCallback).onResponse(response, type); + } catch (Exception e){ + LOG.error("Error on API layer, for request with correlation-id " + corrID, e); + } + if (finalTask){ + coreManager.cancelTimer(corrID); + coreManager.unregisterHandler(corrID); + } + else{ + response = null; + type = null; + } + } + + /** + * Calls to API layer for sending timeout exception. + */ + @Override + public void onTimeOut() { + LOG.info("timeout for request with correlation-id " + corrID); + ((ICoreAsyncResponseHandler)businessCallback).onException(new TimeoutException("timeout for request with correlation-id " + corrID)); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreException.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreException.java new file mode 100644 index 000000000..a2bf6e250 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreException.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + + +public class CoreException extends Exception { + + public CoreException() { + super(); + } + + public CoreException(String message) { + super(message); + } + + public CoreException(String message, Throwable cause) { + super(message, cause); + } + + public CoreException(Throwable cause) { + super(cause); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreManager.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreManager.java new file mode 100644 index 000000000..c1c23890e --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreManager.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import org.onap.appc.client.impl.protocol.*; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Consolidates all services(Registry, Timeout and Task Queue) for handling of requests/responses events. + */ +class CoreManager{ + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(CoreManager.class); + private final ProtocolFactory protocolFactory; + protected AsyncProtocol protocol; + private final RetrieveMessageCallback protocolCallback = null; + private final CoreRegistry registry; + private final ITimerService timerService; + private final TaskQueueManager queueManager; + private String DEFAULT_TIMEOUT = "300000"; + private final static String RESPONSE_TIMEOUT = "client.response.timeout"; + private final static String GRACEFUL_SHUTDOWN_TIMEOUT = "client.graceful.shutdown.timeout"; + private boolean isForceShutdown = false; + private AtomicBoolean isGracefulShutdown = new AtomicBoolean(false); + private long shutdownTimeout; + + CoreManager(Properties prop) throws CoreException { + protocolFactory = ProtocolFactory.getInstance(); + try { + initProtocol(prop); + }catch (ProtocolException e){ + throw new CoreException(e); + } + registry = new CoreRegistry(new EmptyRegistryCallbackImpl()); + String timeoutProp = prop.getProperty(RESPONSE_TIMEOUT, DEFAULT_TIMEOUT); + long responseTimeout = Long.parseLong(timeoutProp); + String gracefulTimeout = prop.getProperty(GRACEFUL_SHUTDOWN_TIMEOUT, DEFAULT_TIMEOUT); + shutdownTimeout = Long.parseLong(gracefulTimeout); + timerService = new TimerServiceImpl(responseTimeout); + queueManager = new TaskQueueManager(prop); + listenShutdown(); + } + + /** + * initiates protocol layer services. + * @param prop - Properties + */ + private void initProtocol(Properties prop) throws ProtocolException { + protocol = (AsyncProtocol) protocolFactory.getProtocolObject(ProtocolType.ASYNC); + protocol.init(prop, getProtocolCallback()); + } + + /** + * Creates protocol response callback + * @return - @{@link ProtocolResponseCallbackImpl} + */ + RetrieveMessageCallback getProtocolCallback(){ + return new ProtocolResponseCallbackImpl(); + } + + /** + * Registers a new handler in registry + * @param corrID - Correlation ID + * @param requestResponseHandler handler to be called when response arrives + */ + void registerHandler(String corrID, RequestResponseHandler requestResponseHandler){ + registry.register(corrID, requestResponseHandler); + } + + /** + * Remove a handler from registry service by correlation ID. + * @param corrID - Correlation ID + * @return - @{@link RequestResponseHandler} + */ + RequestResponseHandler unregisterHandler(String corrID){ + return (RequestResponseHandler) registry.unregister(corrID); + } + + /** + * Checks in registry service if a handler is existing. + * @param corrID - Correlation ID + * @return - boolean + */ + boolean isExistHandler(String corrID) { + return registry.isExist(corrID); + } + + /** + * Starts timer for timeout event when a request was send successfully. + * @param corrID - Correlation ID + */ + void startTimer(String corrID){ + timerService.add(corrID, new TimeoutHandlerImpl(corrID)); + } + + /** + * Cancels timer for fimeout event, in case when complete response was received + * @param corrID + */ + void cancelTimer(String corrID){ + timerService.cancel(corrID); + } + + /** + * Submits a new task to Queue manager. it is using for both response and timeout tasks + * @param corrID - Correlation ID + * @param task - @{@link Runnable} task. + * @throws InterruptedException + */ + void submitTask(String corrID, Runnable task) throws InterruptedException { + queueManager.submit(corrID, task); + } + + /** + * Sends request to protocol. + * @param request - Request + * @param corrId - Correlation ID + * @param rpcName - RPC name + * @throws CoreException - @{@link CoreException} + */ + void sendRequest(String request, String corrId, String rpcName) throws CoreException { + MessageContext ctx = getMessageContext(corrId, rpcName); + try { + protocol.sendRequest(request, ctx); + } catch (ProtocolException e) { + unregisterHandler(corrId); + throw new CoreException(e); + } + } + + /** + * Creates @{@link MessageContext} + * @param correlationId - Correlation ID + * @param rpcName - RPC Name + * @return - @{@link MessageContext} + */ + private MessageContext getMessageContext(String correlationId, String rpcName){ + MessageContext msgCtx = new MessageContext(); + msgCtx.setCorrelationID(correlationId); + msgCtx.setRpc(rpcName); + return msgCtx; + } + + /** + * Implements response callback from protocol and filters responses by correlation ID. + * Only registered events(by correlation ID) will be handled. + */ + private class ProtocolResponseCallbackImpl implements RetrieveMessageCallback { + @Override + public void onResponse(String response, MessageContext context) { + String corrID = context.getCorrelationID(); + if (corrID != null) { + RequestResponseHandler messageHandler = (RequestResponseHandler) registry.get(corrID); + if (messageHandler != null) { + LOG.info("On response callback corrID <" + corrID + "> handler " + messageHandler + " response " + response); + messageHandler.handleResponse(context, response); + } + } + } + } + + + /** + * listens to @{@link Runtime} shutdown event + */ + private void listenShutdown() { + Runtime.getRuntime().addShutdownHook(new Thread(){ + public void run(){ + gracefulShutdown(); + } + }); + } + + /** + * Implements shutdown for client library. + * @param isForceShutdown - true force shutdown, false graceful shutdown + */ + void shutdown(boolean isForceShutdown){ + if(isForceShutdown){ + forceShutdown(); + }else{ + gracefulShutdown(); + } + } + + /** + * Graceful shutdown. in case of all requests already were handled, calls to force shutdown. another goes to force + * shutdown only when either all request will be handled or graceful shutdown will be time out. + */ + synchronized void gracefulShutdown(){ + isGracefulShutdown.set(true); + if(registry.isEmpty()){ + forceShutdown(); + } + else{ + try { + LOG.info("Core manager::graceful shutdown is starting... this <" + this + ">"); + wait(shutdownTimeout); + LOG.info("Core manager::graceful shutdown is continue... this <" + this + ">"); + forceShutdown(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } + + /** + * Closes Protocol, stops Queue Manager and shutdowns Time Service. + */ + private void forceShutdown(){ + isForceShutdown = true; + try { + LOG.info("Starting shutdown process."); + protocol.shutdown(); + queueManager.stopQueueManager(); + timerService.shutdown(); + } catch (InterruptedException e) { + LOG.info("Client library shutdown in progress ", e); + } + } + + /** + * + * @return - true when shutdown is in process + */ + boolean isShutdownInProgress(){ + return isForceShutdown || isGracefulShutdown.get(); + } + + /** + * Timeout handler implementation. + * This handler is responsible to assign a task for handling of timeout events. + * + */ + private class TimeoutHandlerImpl implements ITimeoutHandler { + + private final String corrID; + + TimeoutHandlerImpl(String corrID) { + this.corrID = corrID; + } + + /** + * When a timeout event is occurring, the new Timeout task will be assigned into a queue, + * this queue is shared between both timeout and handlers which belong to same correlation ID. + */ + @Override + public void onTimeout() { + try { + submitTask(corrID, new Runnable() { + @Override + public void run() { + RequestResponseHandler requestResponseHandler = unregisterHandler(corrID); + if (requestResponseHandler != null) { + requestResponseHandler.onTimeOut(); + } + } + }); + } catch (InterruptedException e) { + LOG.warn("could not submit timeout task for correlation ID <" + corrID + "> ", e); + } + } + } + + + /** + * Wakes Up graceful shutdown. + */ + class EmptyRegistryCallbackImpl implements CoreRegistry.EmptyRegistryCallback { + @Override + public synchronized void emptyCallback() { + LOG.info("Registry is empty, wake up the shutdown!, isGraceful flag <" + isGracefulShutdown + ">"); + if(isGracefulShutdown.get()){ + wakeUpShutdown(); + } + } + } + + /** + * wakes up waiting shutdown. + */ + private synchronized void wakeUpShutdown(){ + notifyAll(); + } + +} + diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreRegistry.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreRegistry.java new file mode 100644 index 000000000..e0a0c5b34 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/CoreRegistry.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** client lib Registry + */ +class CoreRegistry{ + private Map registry = + new ConcurrentHashMap(); + + final private EmptyRegistryCallback emptyRegistryCallback; + + + CoreRegistry(EmptyRegistryCallback emptyRegistryCallback){ + this.emptyRegistryCallback = emptyRegistryCallback; + } + + void register(String key, T obj) { + registry.put(key, obj); + } + + T unregister(String key) { + T item = (T) registry.remove(key); + if(registry.isEmpty()) { + emptyRegistryCallback.emptyCallback(); + } + return item; + } + + T get(String key){ + return (T) registry.get(key); + } + + synchronized boolean isExist(String key) { + return registry.containsKey(key); + } + + boolean isEmpty(){ + return registry.isEmpty(); + } + + public interface EmptyRegistryCallback{ + void emptyCallback(); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreAsyncResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreAsyncResponseHandler.java new file mode 100644 index 000000000..862d56dc3 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreAsyncResponseHandler.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +public interface ICoreAsyncResponseHandler extends ICoreResponseHandler{ + + /** + * Core response to incoming message + * @param message response accepted from protocol + * @param type type of response + * @return true if message is final, false otherwise + */ + boolean onResponse(String message, String type); + + /** + * Core reaction to an event of exception + * @param e the exception which have been thrown + */ + void onException(Exception e); + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreResponseHandler.java new file mode 100644 index 000000000..555640dfd --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreResponseHandler.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +public interface ICoreResponseHandler { +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreSyncResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreSyncResponseHandler.java new file mode 100644 index 000000000..996d3d8d2 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ICoreSyncResponseHandler.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +public interface ICoreSyncResponseHandler extends ICoreResponseHandler{ + + /** + * Core response to incoming message, should return completed message only + * @param message response accepted from protocol + * @param type type of response + * @return true if message is final, false otherwise + */ + T onResponse(String message, String type) throws CoreException; +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/IInvocationManager.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/IInvocationManager.java new file mode 100644 index 000000000..93cf20b3f --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/IInvocationManager.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import java.util.Properties; +import java.util.concurrent.TimeoutException; + +/** + */ +public interface IInvocationManager { + + /** + * initializes the manager + * @param prop properties to read from + * @throws CoreException thrown if madatory fields are not set right + */ + void init(Properties prop) throws CoreException; + + /** + * handles the flow of an async request + * @param request the request body + * @param listener business response handler + * @param correlationId unique id of the request + * @param rpcName rpc call name + * @throws CoreException thrown if the request failed to be sent + */ + void asyncRequest(String request, ICoreAsyncResponseHandler listener, String correlationId, String rpcName) throws CoreException; + + /** + * handles to flow of a sync request + * @param request the request body + * @param callback business response handler + * @param correlationId unique id of the request + * @param rpcName rpc call name + * @return the output object to be returned + * @throws CoreException thrown if the request failed to be sent + * @throws TimeoutException thrown if timeout has exceeded + */ + T syncRequest(String request, ICoreSyncResponseHandler callback, String correlationId, String rpcName) throws CoreException, TimeoutException; + + /** + * shuts the invocation manager down. + * @param isForceShutdown if true, shutdown will be forced, otherwise it will be gracefully + */ + void shutdown(boolean isForceShutdown); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimeoutHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimeoutHandler.java new file mode 100644 index 000000000..0f3b81a6f --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimeoutHandler.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +interface ITimeoutHandler { + + /** + * handles timeout event + */ + void onTimeout(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimerService.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimerService.java new file mode 100644 index 000000000..96b06033f --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/ITimerService.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +interface ITimerService { + + /** + * add a new timeout handler to a request + * @param correlationID the id of the request + * @param handler to be called once "timeout' time has arrived + */ + void add(String correlationID, ITimeoutHandler handler); + + /** + * cancel the timeout handler of a request + * @param correlationID the id of the request + */ + void cancel(String correlationID); + + + /** + * shuts the timer service down immediately + */ + void shutdown(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManager.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManager.java new file mode 100644 index 000000000..8179da107 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManager.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import java.util.Properties; +import java.util.concurrent.TimeoutException; + +/** + * layer for passing requests from API to Core + */ +class InvocationManager implements IInvocationManager{ + + protected CoreManager coreManager = null; + + InvocationManager(){ + } + + public void init(Properties properties) throws CoreException { + coreManager = new CoreManager(properties); + } + + /** + * + * @param request + * @param businessCallback + * @param correlationId + * @param rpcName + * @throws CoreException + */ + public void asyncRequest(String request, ICoreAsyncResponseHandler businessCallback, String correlationId, String rpcName) throws CoreException { + AsyncRequestResponseHandler requestResponseHandler = new AsyncRequestResponseHandler(correlationId, businessCallback, coreManager); + requestResponseHandler.sendRequest(request, correlationId, rpcName); + } + + public T syncRequest(String request, ICoreSyncResponseHandler businessCallback, String correlationId, String rpcName ) throws CoreException, TimeoutException { + SyncRequestResponseHandler requestResponseHandler = new SyncRequestResponseHandler(correlationId, businessCallback, coreManager); + requestResponseHandler.sendRequest(request, correlationId, rpcName); + T responseObject = (T) requestResponseHandler.getResponse(); + return responseObject; + } + + @Override + public void shutdown(boolean isForceShutdown) { + coreManager.shutdown(isForceShutdown); + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManagerFactory.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManagerFactory.java new file mode 100644 index 000000000..c9face762 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/InvocationManagerFactory.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +public abstract class InvocationManagerFactory { + private static IInvocationManager invocationManager = null; + + public static synchronized IInvocationManager getInstance(){ + if(invocationManager == null){ + invocationManager = new InvocationManager(); + } + return invocationManager; + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/MessageContext.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/MessageContext.java new file mode 100644 index 000000000..6fab66bb3 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/MessageContext.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +/** Helper class for wrapping request/response information. + */ +public class MessageContext { + + /** + * valid values of type are response/error + */ + private String type; + + /** + * RPC name + */ + private String rpc; + + /** + * correlation ID + */ + private String correlationID; + + /** + * partitioner for message bus usage + */ + private String partitioner; + + + public String getRpc() { + return rpc; + } + + public void setRpc(String rpc) { + this.rpc = rpc; + } + + public String getCorrelationID() { + return correlationID; + } + + public void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + public String getPartiton() { + return partitioner; + } + + public void setPartiton(String partitioner) { + this.partitioner = partitioner; + } + + public void setType(String type){ + this.type = type; + } + + public String getType(){ + return type; + } + + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/RequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/RequestResponseHandler.java new file mode 100644 index 000000000..8e05a2974 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/RequestResponseHandler.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +interface RequestResponseHandler { + + /** + * sends request, registers handler of response and start timer. + * @param request - Request + * @param corrId - correlation ID + * @param rpcName - RPC name + * @throws CoreException - @{@link CoreException} + */ + void sendRequest(String request, String corrId, String rpcName) throws CoreException; + + /** + * submits a handler task to task queue @{@link TaskQueue}, this task will be performed only if this handler is + * still existing in core registry @{@link CoreRegistry}, others timeout was occurred . + * @param ctx - Message Context @{@link MessageContext} + * @param response - Response from backend + */ + void handleResponse(MessageContext ctx, String response); + + /** + * handles timeout event + */ + void onTimeOut(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/SyncRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/SyncRequestResponseHandler.java new file mode 100644 index 000000000..90b0a9926 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/SyncRequestResponseHandler.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.TimeoutException; + +/** Handles sync requests + */ +class SyncRequestResponseHandler extends AbstractRequestResponseHandler { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(SyncRequestResponseHandler.class); + private T responseObject = null; + private CoreException coreException = null; + private TimeoutException timeoutException = null; + + SyncRequestResponseHandler(String corrID, + ICoreResponseHandler callback, + CoreManager coreManager){ + super(corrID, callback, coreManager); + } + + /** + * Calls API callback for getting response object. in case of complete response notifies consumer + * thread for receiving response + * @param response - Response + * @param type - Type of Response + */ + synchronized void runTask(String response, String type) { + try { + responseObject = ((ICoreSyncResponseHandler) businessCallback).onResponse(response, type); + } catch (CoreException e) { + coreException = e; + } + if(responseObject != null || coreException != null) { + notify(); + } + } + + + /** + * Returns response. goes sleep until coming either timeout event or complete response + */ + public synchronized T getResponse() throws CoreException, TimeoutException { + try{ + if(!isResponseReceived()){ + wait(); + } + if (coreException != null) { + throw coreException; + } + if ( timeoutException != null) { + throw timeoutException; + } + + } catch (InterruptedException e) { + throw new CoreException(e); + } finally{ + coreManager.unregisterHandler(corrID); + coreManager.cancelTimer(corrID); + } + return (T) responseObject; + } + + /** + * indicates if a response received + * @return + */ + private boolean isResponseReceived() { + return responseObject != null; + } + + @Override + public synchronized void onTimeOut() { + LOG.error("sync response handler on timeout correlation ID <" + corrID + ">."); + timeoutException = new TimeoutException("timeout for request with correlation-id " + corrID); + notify(); + } + + + + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueue.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueue.java new file mode 100644 index 000000000..4ceeb3f08 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueue.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +/** Responsible to ensure synchronous handling of responses and timouts. + */ +class TaskQueue implements Runnable{ + + private final BlockingQueue queue = new LinkedBlockingQueue<>(); + private final EELFLogger LOG = EELFManager.getInstance().getLogger(TaskQueue.class); + + private boolean isShutdown; + + synchronized void addTask(Runnable task) throws InterruptedException { + queue.put(task); + } + + public void run() { + Runnable task; + while(!Thread.currentThread().isInterrupted() && !isShutdown){ + try { + task = queue.take(); + task.run(); + } catch (InterruptedException e) { + LOG.error("could not take task from queue", e); + } catch (RuntimeException e) { + LOG.error("could not run task", e); + } + LOG.info("THR# <" + Thread.currentThread().getId() + "> shutdown indicator " + isShutdown); + } + LOG.info("THR# <" + Thread.currentThread().getId() + "> in shutdown process."); + } + + void stopQueue(){ + isShutdown = true; + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueueManager.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueueManager.java new file mode 100644 index 000000000..b87349411 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TaskQueueManager.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** Creates a task queue pool that reuses a fixed number of threads. + * Assigns one thread for each queue. + */ +class TaskQueueManager { + private final EELFLogger LOG = EELFManager.getInstance().getLogger(TaskQueueManager.class); + private ExecutorService executorService; + private final static String DEFAULT_POOL_SIZE = "10"; + private final static String CLIENT_POOL_SIZE = "client.pool.size"; + private TaskQueue[] queues; + private int poolInt; + + TaskQueueManager(Properties properties){ + String size = properties.getProperty(CLIENT_POOL_SIZE, DEFAULT_POOL_SIZE); + poolInt = Integer.parseInt(size); + this.executorService = Executors.newFixedThreadPool(poolInt); + initTaskQueues(); + } + + private void initTaskQueues(){ + queues = new TaskQueue[poolInt]; + for(int i=0; i listTask = executorService.shutdownNow(); + if (!executorService.awaitTermination(6, TimeUnit.SECONDS)) + System.err.println("Pool did not terminate"); + LOG.info("the amount of tasks that never commenced execution " + listTask.size()); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TimerServiceImpl.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TimerServiceImpl.java new file mode 100644 index 000000000..fa2d0804d --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/core/TimerServiceImpl.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.List; +import java.util.concurrent.*; + +class TimerServiceImpl implements ITimerService { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(TimerServiceImpl.class); + private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + private final ConcurrentHashMap timeOutEvents = new ConcurrentHashMap<>(); + private final long responseTimeout; + + TimerServiceImpl(long responseTimeout) { + this.responseTimeout = responseTimeout; + } + + @Override + public synchronized void cancel(String correlationID) { + Future timeOutEvent = timeOutEvents.remove(correlationID); + if (timeOutEvent != null){ + timeOutEvent.cancel(true); + } + } + + @Override + public synchronized void add(String correlationID, ITimeoutHandler handler) { + Future timeOutEvent = scheduler.schedule(new HandleTimeout(correlationID, handler), responseTimeout, TimeUnit.MILLISECONDS); + timeOutEvents.put(correlationID, timeOutEvent); + } + + @Override + public void shutdown() { + List listTask = scheduler.shutdownNow(); + LOG.info("the amount of tasks that never commenced execution " + listTask.size()); + } + + private class HandleTimeout implements Runnable { + + String correlationID; + ITimeoutHandler handler; + + HandleTimeout(String correlationID, ITimeoutHandler handler) { + this.correlationID = correlationID; + this.handler = handler; + } + + @Override + public void run(){ + System.out.println("Timeout event of request " + correlationID); + handler.onTimeout(); + timeOutEvents.remove(correlationID); + } + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriter.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriter.java new file mode 100644 index 000000000..a76f0a90b --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriter.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +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 java.io.IOException; + +class APPCMessageReaderWriter implements MessageReader, MessageWriter { + + private final ObjectMapper mapper; + private final EELFLogger LOG = EELFManager.getInstance().getLogger(APPCMessageReaderWriter.class); + + APPCMessageReaderWriter() { + mapper = new ObjectMapper(); + } + + public String read(String payload, MessageContext context) throws ProtocolException { + try { + ProtocolMessage protocolMessage = mapper.readValue(payload, ProtocolMessage.class); + context.setType(protocolMessage.getType()); + context.setRpc(protocolMessage.getRpcName()); + context.setCorrelationID(protocolMessage.getCorrelationID()); + context.setPartiton(protocolMessage.getPartition()); + String body = protocolMessage.getBody().toString(); + LOG.debug("Received body : <" + body + ">"); + return body; + } catch (IOException e) { + throw new ProtocolException(e); + } + + } + + public String write(String payload, MessageContext context) throws ProtocolException { + try { + ProtocolMessage protocolMessage = new ProtocolMessage(); + protocolMessage.setVersion("2.0"); + protocolMessage.setType(context.getType()); + protocolMessage.setRpcName(context.getRpc()); + protocolMessage.setCorrelationID(context.getCorrelationID()); + protocolMessage.setPartition(context.getPartiton()); + JsonNode body = mapper.readTree(payload); + protocolMessage.setBody(body); + String message = mapper.writeValueAsString(protocolMessage); + return message; + } catch (IOException e) { + throw new ProtocolException(e); + } + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocol.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocol.java new file mode 100644 index 000000000..94d2d6b85 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocol.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; + +public interface AsyncProtocol extends Protocol { + + /** + * sends a string message to underlying message bus/java API + * @param payload - meesage body + * @param context - message headers + * @throws ProtocolException + */ + void sendRequest(String payload, MessageContext context) throws ProtocolException; + + void shutdown(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocolImpl.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocolImpl.java new file mode 100644 index 000000000..82626d802 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/AsyncProtocolImpl.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +class AsyncProtocolImpl implements AsyncProtocol { + + /** + * message bus listener thread handler + */ + private Future listenerHandler; + /** + * called when messages are fetched - called for a single message + */ + private RetrieveMessageCallback callback; + /** + * message bus client used to send/fetch + */ + private MessagingService messageService; + /** + * Message reader used to extract body and context from reponse message + */ + private MessageReader messageReader; + /** + * Message writer used to construct meesage from body and context + */ + private MessageWriter messageWriter; + + /** + * shutdown indicator + */ + private boolean isShutdown = false; + + /** + * executor service for listener usage + */ + private ExecutorService executorService = Executors.newSingleThreadExecutor(); + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(AsyncProtocolImpl.class); + + + AsyncProtocolImpl() { + + messageService = new UEBMessagingService(); + messageReader = new APPCMessageReaderWriter(); + messageWriter = (MessageWriter) messageReader; + } + + public void init(Properties props, RetrieveMessageCallback callback) throws ProtocolException { + + if (callback == null) { + throw new ProtocolException("Callback param should not be null!"); + } + this.callback = callback; + + try { + messageService.init(props); + //get message bus listener thread + //start the thread after initializing services + listenerHandler = executorService.submit(new Listener()); + } catch (GeneralSecurityException | IllegalAccessException | NoSuchFieldException | IOException e) { + throw new ProtocolException(e); + } + } + + public void sendRequest(String payload, MessageContext context) throws ProtocolException { + + //get message to be sent to appc from payload and context + String message = messageWriter.write(payload, context); + try { + messageService.send(context.getPartiton(), message); + LOG.debug("Successfully send message: " + message); + } catch (IOException e) { + throw new ProtocolException(e); + } + } + + @Override + public void shutdown() { + isShutdown = true; + messageService.close(); + LOG.warn("The protocol layer in shutdown stage."); + executorService.shutdownNow(); + } + + public class Listener implements Runnable { + + + public void run() { + + while (!isShutdown) { + List messages = new ArrayList<>(); + try { + messages = messageService.fetch(); + LOG.debug("Successfully fetched " + messages.size() + " messages"); + } catch (IOException e) { + LOG.error("Fetching " + messages.size() + " messages failed"); + } + for (String message : messages) { + + MessageContext context = new MessageContext(); + String payload = null; + + try { + //get payload and context from message to be sent to core layer + payload = messageReader.read(message, context); + LOG.debug("Got body: " + payload); + //call core layer response handler + if(!isShutdown) { + callback.onResponse(payload, context); + }else{ + LOG.warn("Shutdown in progress, response will not receive. Correlation ID <" + + context.getCorrelationID() + "> response ", message); + } + } catch (ProtocolException e) { + LOG.error("Failed to read message from UEB. message is: " + message); + } + } + } + } + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Consumer.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Consumer.java new file mode 100644 index 000000000..4765a58ef --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Consumer.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import java.io.IOException; +import java.util.List; + +interface Consumer { + + /** + * Gets a batch of messages from the topic. Defaults to 1000 messages with 15s wait for messages if empty. + * + * @return A list of strings representing the messages pulled from the topic. + * @throws IOException + */ + List fetch() throws IOException; + + /** + * Gets a batch of messages from the topic. + * + * @param limit The amount of messages to fetch + * @return A list of strings representing the messages pulled from the topic. + * @throws IOException + */ + List fetch(int limit) throws IOException; + + /** + * Send dummy fetch request to register client to be able to fetch messages + * @throws IOException + */ + void registerForRead() throws IOException; + + void close(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ConsumerImpl.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ConsumerImpl.java new file mode 100644 index 000000000..913f80f44 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ConsumerImpl.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; +import com.att.nsa.cambria.client.CambriaConsumer; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +class ConsumerImpl implements Consumer { + + private static final int DEFAULT_LIMIT = 1000; + + private Collection hosts; + private String topic; + private String group; + private String groupId; + private int timeout; + + private String authKey; + private String authSecret; + + private CambriaConsumer consumer = null; + + /** + * constructor + * @param urls + * @param topicName + * @param consumerName + * @param consumerId + * @param timeout + */ + public ConsumerImpl(Collection urls, String topicName, String consumerName, String consumerId, Integer timeout, String apiKey, String apiSecret) throws MalformedURLException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { + this.hosts = urls; + this.topic = topicName; + this.group = consumerName; + this.groupId = consumerId; + this.authKey = apiKey; + this.authSecret = apiSecret; + this.timeout = timeout; + consumer = getConsumer(); + } + + + public List fetch() throws IOException { + + return fetch(DEFAULT_LIMIT); + } + + public List fetch(int limit) throws IOException { + + List out = new ArrayList(); + try { + for(String msg : consumer.fetch(timeout,limit)){ + out.add(msg); + } + } catch (IOException e) { + throw e; + } + return out; + } + + public void registerForRead() throws IOException { + + int waitForRegisteration = 1; //return from fetch after 1ms, no need to read any messages + consumer.fetch(waitForRegisteration, 1); + } + + /** + * init cambria consumer + * @return CambriaConsumer + */ + private CambriaConsumer getConsumer() throws MalformedURLException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { + + ConsumerBuilder builder = new ConsumerBuilder(); + + builder.usingHosts(hosts).onTopic(topic).knownAs(group, groupId); + builder.withSocketTimeout(timeout + 5000).waitAtServer(timeout); + builder.receivingAtMost(DEFAULT_LIMIT); + + // Add credentials if provided + if (authKey != null && authSecret != null) { + + Field apiKeyField = ConsumerBuilder.class.getDeclaredField("fApiKey"); + apiKeyField.setAccessible(true); + apiKeyField.set(builder, ""); + builder.authenticatedBy(authKey, authSecret); + } + + return builder.build(); + } + + @Override + public void close() { + consumer.close(); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageReader.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageReader.java new file mode 100644 index 000000000..19688d696 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageReader.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; + +public interface MessageReader { + + /** + * reads payload, fills the context out of payload headers, and returns the body of the payload + * @param payload incoming message + * @param context context to fill + * @return body of the payload + * @throws ProtocolException + */ + String read(String payload, MessageContext context) throws ProtocolException; +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageWriter.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageWriter.java new file mode 100644 index 000000000..0849bc4a4 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessageWriter.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +import com.fasterxml.jackson.databind.JsonNode; + +public interface MessageWriter { + + /** + * builds a message out of context and payload + * @param payload body of the message + * @param context headers of the message + * @return the message to write/send + * @throws ProtocolException + */ + String write(String payload, MessageContext context) throws ProtocolException; +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessagingService.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessagingService.java new file mode 100644 index 000000000..029378931 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/MessagingService.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Properties; + +interface MessagingService { + + /** + * initialize consumer/publisher + * @param props + */ + void init(Properties props) throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException; + + /** + * sends a string as is + * @param partition + * @param body + */ + void send(String partition, String body) throws IOException; + + /** + * retrieve messages from bus - timeout extracted from props or see impl + * @return + */ + List fetch() throws IOException; + + /** + * retrieve messages from bus - timeout extracted from props or see impl + * @param limit + * @return + */ + List fetch(int limit) throws IOException; + + void close(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Producer.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Producer.java new file mode 100644 index 000000000..f290e8a89 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Producer.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import java.io.IOException; + +interface Producer { + + /** + * send a message to a partition via ueb + * @param data + */ + void post(String Partition, String data) throws IOException; + + void close(); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProducerImpl.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProducerImpl.java new file mode 100644 index 000000000..7729db98d --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProducerImpl.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.Collection; + +class ProducerImpl implements Producer { + + private Collection hosts; + private String topic; + private CambriaBatchingPublisher producer; + + private String authKey; + private String authSecret; + + public ProducerImpl(Collection urls, String topicName, String apiKey, String apiSecret) throws MalformedURLException, GeneralSecurityException { + + topic = topicName; + hosts = urls; + authKey = apiKey; + authSecret = apiSecret; + producer = getProducer(); + } + + public void post(String partition, String data) throws IOException { + + producer.send(partition, data); + } + + /** + * get cambria producer + * @return + */ + private CambriaBatchingPublisher getProducer() throws MalformedURLException, GeneralSecurityException { + + PublisherBuilder builder = new PublisherBuilder().usingHosts(hosts); + + // Add credentials if provided + if (authKey != null && authSecret != null) { + builder.authenticatedBy(authKey, authSecret); + } + + CambriaBatchingPublisher client = null; + + client = builder.onTopic(topic).build(); + + return client; + } + + @Override + public void close() { + producer.close(); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Protocol.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Protocol.java new file mode 100644 index 000000000..eaa21d857 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/Protocol.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import java.util.Properties; + +public interface Protocol { + + /** + * init protocol properties and callback + * @param props + * @param callback + * @throws ProtocolException + */ + void init(Properties props, RetrieveMessageCallback callback) throws ProtocolException; +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolException.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolException.java new file mode 100644 index 000000000..eb0537b80 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +public class ProtocolException extends Exception { + + public ProtocolException() { + super(); + } + + public ProtocolException(String message) { + super(message); + } + + public ProtocolException(String message, Throwable cause) { + super(message, cause); + } + + public ProtocolException(Throwable cause) { + super(cause); + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolFactory.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolFactory.java new file mode 100644 index 000000000..98e7d669b --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolFactory.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import java.util.HashMap; +import java.util.Map; + +public class ProtocolFactory { + + private static ProtocolFactory instance; + private Map protocols; + + /** + * Singleton factory + */ + private ProtocolFactory(){ + + protocols = new HashMap(); + } + + /** + * get factory instance + * @return factory instance + */ + public static synchronized ProtocolFactory getInstance(){ + + if (instance == null) { + instance = new ProtocolFactory(); + } + return instance; + } + + /** + * returns instantiated protocol object + * @param type of protocol object + * @return protocol object + */ + public Protocol getProtocolObject(ProtocolType type) throws ProtocolException { + + Protocol protocol = protocols.get(type); + synchronized (this) { + if (protocol == null) { + switch (type) { + case SYNC: + throw new ProtocolException("Protocol SYNC is not implemented"); + case ASYNC: + protocol = new AsyncProtocolImpl(); + protocols.put(type, protocol); + break; + default: + throw new ProtocolException("Protocol type not found"); + } + } + } + return protocol; + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolMessage.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolMessage.java new file mode 100644 index 000000000..c02ea5607 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolMessage.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; + +class ProtocolMessage { + + private String version; + private String type; + private String rpcName; + private String correlationID; // correlation-id + private String partition; // cambria.partition + private JsonNode body; + + @JsonProperty + String getVersion() { + return version; + } + + @JsonProperty + void setVersion(String version) { + this.version = version; + } + + @JsonProperty + String getType() { + return type; + } + + @JsonProperty + void setType(String type) { + this.type = type; + } + + @JsonProperty("rpc-name") + String getRpcName() { + return rpcName; + } + + @JsonProperty("rpc-name") + void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + @JsonProperty("correlation-id") + String getCorrelationID() { + return correlationID; + } + + @JsonProperty("correlation-id") + void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + @JsonProperty("cambria.partition") + String getPartition() { + return partition; + } + + @JsonProperty("cambria.partition") + void setPartition(String partition) { + this.partition = partition; + } + + @JsonProperty + JsonNode getBody() { + return body; + } + + @JsonProperty + void setBody(JsonNode body) { + this.body = body; + } +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolType.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolType.java new file mode 100644 index 000000000..cc2eca447 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/ProtocolType.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +public enum ProtocolType { + + SYNC, ASYNC; +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/RetrieveMessageCallback.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/RetrieveMessageCallback.java new file mode 100644 index 000000000..8fc486bb8 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/RetrieveMessageCallback.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + + +import org.onap.appc.client.impl.core.MessageContext; + +public interface RetrieveMessageCallback { + + /** + * called when response received + * @param payload + * @param context + */ + void onResponse(String payload, MessageContext context); +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBMessagingService.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBMessagingService.java new file mode 100644 index 000000000..df51861b8 --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBMessagingService.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.*; + +class UEBMessagingService implements MessagingService { + + private Consumer consumer; + private Producer producer; + + private final String DEFAULT_READ_TIMEOUT_MS = "60000"; + private final String DEFAULT_READ_LIMIT = "1000"; + + private int readLimit; + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(UEBMessagingService.class); + + @SuppressWarnings("Since15") + public void init(Properties props) throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { + + if (props != null) { + String readTopic = props.getProperty(UEBPropertiesKeys.TOPIC_READ); + String writeTopic = props.getProperty(UEBPropertiesKeys.TOPIC_WRITE); + String apiKey = props.getProperty(UEBPropertiesKeys.AUTH_USER); + String apiSecret = props.getProperty(UEBPropertiesKeys.AUTH_SECRET); + String readTimeoutString = props.getProperty(UEBPropertiesKeys.TOPIC_READ_TIMEOUT, DEFAULT_READ_TIMEOUT_MS); + Integer readTimeout = Integer.parseInt(readTimeoutString); + String readLimitString = props.getProperty(UEBPropertiesKeys.READ_LIMIT, DEFAULT_READ_LIMIT); + readLimit = Integer.parseInt(readLimitString); + //get hosts pool + Collection pool = new HashSet(); + String hostNames = props.getProperty(UEBPropertiesKeys.HOSTS); + if (hostNames != null && !hostNames.isEmpty()) { + for (String name : hostNames.split(",")) { + pool.add(name); + } + } + + //generate consumer id and group - same value for both + String consumerName = UUID.randomUUID().toString(); + String consumerID = consumerName; + + //create consumer and producer + consumer = new ConsumerImpl(pool, readTopic, consumerName, consumerID, readTimeout, apiKey, apiSecret); + producer = new ProducerImpl(pool, writeTopic, apiKey, apiSecret); + + //initial consumer registration + try { + consumer.registerForRead(); + }catch(Exception e){ + LOG.error("Message consumer failed to register client "+consumerID); + } + } + } + + public void send(String partition, String body) throws IOException { + producer.post(partition, body); + } + + public List fetch() throws IOException { + return consumer.fetch(readLimit); + } + + public List fetch(int limit) throws IOException { + return consumer.fetch(limit); + } + + @Override + public void close() { + consumer.close(); + producer.close(); + } + +} diff --git a/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBPropertiesKeys.java b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBPropertiesKeys.java new file mode 100644 index 000000000..5c1916f2b --- /dev/null +++ b/appc-client/client-lib/src/main/java/org/onap/appc/client/impl/protocol/UEBPropertiesKeys.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +class UEBPropertiesKeys { + + static final String TOPIC_READ = "topic.read"; + static final String TOPIC_READ_TIMEOUT = "topic.read.timeout"; + static final String READ_LIMIT = "topic.read.limit"; + static final String TOPIC_WRITE = "topic.write"; + static final String AUTH_USER = "client.key"; + static final String AUTH_SECRET = "client.secret"; + static final String HOSTS = "poolMembers"; +} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AbstractRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AbstractRequestResponseHandler.java deleted file mode 100644 index c5d6120f0..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AbstractRequestResponseHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** Abstract request response handler class, responsible for common functionality of - * @{@link AsyncRequestResponseHandler} and @{@link SyncRequestResponseHandler} - */ -abstract class AbstractRequestResponseHandler implements RequestResponseHandler { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractRequestResponseHandler.class); - ICoreResponseHandler businessCallback; - protected String corrID; - CoreManager coreManager; - - - AbstractRequestResponseHandler(String corrID, - ICoreResponseHandler businessCallback, - CoreManager coreManager) - { - this.businessCallback = businessCallback; - this.corrID = corrID; - this.coreManager = coreManager; - } - - public synchronized void handleResponse(final MessageContext ctx, final String response) { - try { - coreManager.submitTask(ctx.getCorrelationID(), new Runnable() { - @Override - public void run() { - LOG.info("handling response of corrID <" + corrID + ">" + "response " + response); - if(coreManager.isExistHandler(corrID)) { - runTask(response, ctx.getType()); - } - - } - }); - } catch (InterruptedException e) { - LOG.error("could not handle response <" + response + "> of corrID <" + corrID + ">", e); - } - } - - /** - * - * @param response - Response - * @param type - Type of Response - */ - abstract void runTask(String response, String type); - - @Override - public void sendRequest(String request, String corrId, String rpcName) throws CoreException { - if(!coreManager.isShutdownInProgress()) { - coreManager.registerHandler(corrId, this); - coreManager.sendRequest(request, corrId, rpcName); - coreManager.startTimer(corrId); - }else{ - throw new CoreException("Shutdown is in progress. Request will not be handled"); - } - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AsyncRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AsyncRequestResponseHandler.java deleted file mode 100644 index 1bcf0af99..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/AsyncRequestResponseHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.TimeoutException; - -/** Handles async responses - */ -class AsyncRequestResponseHandler extends AbstractRequestResponseHandler { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(AsyncRequestResponseHandler.class); - - AsyncRequestResponseHandler(String corrID, - ICoreResponseHandler businessCallback, - CoreManager coreManager) - { - super(corrID, businessCallback, coreManager); - } - - /** - * Calls API callback for sending response to consumer's listener. in case of complete response cleans timer and - * unregisters the handler. - * @param response - Response - * @param type - Type of Response - */ - public void runTask(String response, String type) { - boolean finalTask = false; - try { - finalTask = ((ICoreAsyncResponseHandler) businessCallback).onResponse(response, type); - } catch (Exception e){ - LOG.error("Error on API layer, for request with correlation-id " + corrID, e); - } - if (finalTask){ - coreManager.cancelTimer(corrID); - coreManager.unregisterHandler(corrID); - } - else{ - response = null; - type = null; - } - } - - /** - * Calls to API layer for sending timeout exception. - */ - @Override - public void onTimeOut() { - LOG.info("timeout for request with correlation-id " + corrID); - ((ICoreAsyncResponseHandler)businessCallback).onException(new TimeoutException("timeout for request with correlation-id " + corrID)); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreException.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreException.java deleted file mode 100644 index a2bf6e250..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreException.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - - -public class CoreException extends Exception { - - public CoreException() { - super(); - } - - public CoreException(String message) { - super(message); - } - - public CoreException(String message, Throwable cause) { - super(message, cause); - } - - public CoreException(Throwable cause) { - super(cause); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreManager.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreManager.java deleted file mode 100644 index c1c23890e..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreManager.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import org.onap.appc.client.impl.protocol.*; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Consolidates all services(Registry, Timeout and Task Queue) for handling of requests/responses events. - */ -class CoreManager{ - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(CoreManager.class); - private final ProtocolFactory protocolFactory; - protected AsyncProtocol protocol; - private final RetrieveMessageCallback protocolCallback = null; - private final CoreRegistry registry; - private final ITimerService timerService; - private final TaskQueueManager queueManager; - private String DEFAULT_TIMEOUT = "300000"; - private final static String RESPONSE_TIMEOUT = "client.response.timeout"; - private final static String GRACEFUL_SHUTDOWN_TIMEOUT = "client.graceful.shutdown.timeout"; - private boolean isForceShutdown = false; - private AtomicBoolean isGracefulShutdown = new AtomicBoolean(false); - private long shutdownTimeout; - - CoreManager(Properties prop) throws CoreException { - protocolFactory = ProtocolFactory.getInstance(); - try { - initProtocol(prop); - }catch (ProtocolException e){ - throw new CoreException(e); - } - registry = new CoreRegistry(new EmptyRegistryCallbackImpl()); - String timeoutProp = prop.getProperty(RESPONSE_TIMEOUT, DEFAULT_TIMEOUT); - long responseTimeout = Long.parseLong(timeoutProp); - String gracefulTimeout = prop.getProperty(GRACEFUL_SHUTDOWN_TIMEOUT, DEFAULT_TIMEOUT); - shutdownTimeout = Long.parseLong(gracefulTimeout); - timerService = new TimerServiceImpl(responseTimeout); - queueManager = new TaskQueueManager(prop); - listenShutdown(); - } - - /** - * initiates protocol layer services. - * @param prop - Properties - */ - private void initProtocol(Properties prop) throws ProtocolException { - protocol = (AsyncProtocol) protocolFactory.getProtocolObject(ProtocolType.ASYNC); - protocol.init(prop, getProtocolCallback()); - } - - /** - * Creates protocol response callback - * @return - @{@link ProtocolResponseCallbackImpl} - */ - RetrieveMessageCallback getProtocolCallback(){ - return new ProtocolResponseCallbackImpl(); - } - - /** - * Registers a new handler in registry - * @param corrID - Correlation ID - * @param requestResponseHandler handler to be called when response arrives - */ - void registerHandler(String corrID, RequestResponseHandler requestResponseHandler){ - registry.register(corrID, requestResponseHandler); - } - - /** - * Remove a handler from registry service by correlation ID. - * @param corrID - Correlation ID - * @return - @{@link RequestResponseHandler} - */ - RequestResponseHandler unregisterHandler(String corrID){ - return (RequestResponseHandler) registry.unregister(corrID); - } - - /** - * Checks in registry service if a handler is existing. - * @param corrID - Correlation ID - * @return - boolean - */ - boolean isExistHandler(String corrID) { - return registry.isExist(corrID); - } - - /** - * Starts timer for timeout event when a request was send successfully. - * @param corrID - Correlation ID - */ - void startTimer(String corrID){ - timerService.add(corrID, new TimeoutHandlerImpl(corrID)); - } - - /** - * Cancels timer for fimeout event, in case when complete response was received - * @param corrID - */ - void cancelTimer(String corrID){ - timerService.cancel(corrID); - } - - /** - * Submits a new task to Queue manager. it is using for both response and timeout tasks - * @param corrID - Correlation ID - * @param task - @{@link Runnable} task. - * @throws InterruptedException - */ - void submitTask(String corrID, Runnable task) throws InterruptedException { - queueManager.submit(corrID, task); - } - - /** - * Sends request to protocol. - * @param request - Request - * @param corrId - Correlation ID - * @param rpcName - RPC name - * @throws CoreException - @{@link CoreException} - */ - void sendRequest(String request, String corrId, String rpcName) throws CoreException { - MessageContext ctx = getMessageContext(corrId, rpcName); - try { - protocol.sendRequest(request, ctx); - } catch (ProtocolException e) { - unregisterHandler(corrId); - throw new CoreException(e); - } - } - - /** - * Creates @{@link MessageContext} - * @param correlationId - Correlation ID - * @param rpcName - RPC Name - * @return - @{@link MessageContext} - */ - private MessageContext getMessageContext(String correlationId, String rpcName){ - MessageContext msgCtx = new MessageContext(); - msgCtx.setCorrelationID(correlationId); - msgCtx.setRpc(rpcName); - return msgCtx; - } - - /** - * Implements response callback from protocol and filters responses by correlation ID. - * Only registered events(by correlation ID) will be handled. - */ - private class ProtocolResponseCallbackImpl implements RetrieveMessageCallback { - @Override - public void onResponse(String response, MessageContext context) { - String corrID = context.getCorrelationID(); - if (corrID != null) { - RequestResponseHandler messageHandler = (RequestResponseHandler) registry.get(corrID); - if (messageHandler != null) { - LOG.info("On response callback corrID <" + corrID + "> handler " + messageHandler + " response " + response); - messageHandler.handleResponse(context, response); - } - } - } - } - - - /** - * listens to @{@link Runtime} shutdown event - */ - private void listenShutdown() { - Runtime.getRuntime().addShutdownHook(new Thread(){ - public void run(){ - gracefulShutdown(); - } - }); - } - - /** - * Implements shutdown for client library. - * @param isForceShutdown - true force shutdown, false graceful shutdown - */ - void shutdown(boolean isForceShutdown){ - if(isForceShutdown){ - forceShutdown(); - }else{ - gracefulShutdown(); - } - } - - /** - * Graceful shutdown. in case of all requests already were handled, calls to force shutdown. another goes to force - * shutdown only when either all request will be handled or graceful shutdown will be time out. - */ - synchronized void gracefulShutdown(){ - isGracefulShutdown.set(true); - if(registry.isEmpty()){ - forceShutdown(); - } - else{ - try { - LOG.info("Core manager::graceful shutdown is starting... this <" + this + ">"); - wait(shutdownTimeout); - LOG.info("Core manager::graceful shutdown is continue... this <" + this + ">"); - forceShutdown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - } - - /** - * Closes Protocol, stops Queue Manager and shutdowns Time Service. - */ - private void forceShutdown(){ - isForceShutdown = true; - try { - LOG.info("Starting shutdown process."); - protocol.shutdown(); - queueManager.stopQueueManager(); - timerService.shutdown(); - } catch (InterruptedException e) { - LOG.info("Client library shutdown in progress ", e); - } - } - - /** - * - * @return - true when shutdown is in process - */ - boolean isShutdownInProgress(){ - return isForceShutdown || isGracefulShutdown.get(); - } - - /** - * Timeout handler implementation. - * This handler is responsible to assign a task for handling of timeout events. - * - */ - private class TimeoutHandlerImpl implements ITimeoutHandler { - - private final String corrID; - - TimeoutHandlerImpl(String corrID) { - this.corrID = corrID; - } - - /** - * When a timeout event is occurring, the new Timeout task will be assigned into a queue, - * this queue is shared between both timeout and handlers which belong to same correlation ID. - */ - @Override - public void onTimeout() { - try { - submitTask(corrID, new Runnable() { - @Override - public void run() { - RequestResponseHandler requestResponseHandler = unregisterHandler(corrID); - if (requestResponseHandler != null) { - requestResponseHandler.onTimeOut(); - } - } - }); - } catch (InterruptedException e) { - LOG.warn("could not submit timeout task for correlation ID <" + corrID + "> ", e); - } - } - } - - - /** - * Wakes Up graceful shutdown. - */ - class EmptyRegistryCallbackImpl implements CoreRegistry.EmptyRegistryCallback { - @Override - public synchronized void emptyCallback() { - LOG.info("Registry is empty, wake up the shutdown!, isGraceful flag <" + isGracefulShutdown + ">"); - if(isGracefulShutdown.get()){ - wakeUpShutdown(); - } - } - } - - /** - * wakes up waiting shutdown. - */ - private synchronized void wakeUpShutdown(){ - notifyAll(); - } - -} - diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreRegistry.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreRegistry.java deleted file mode 100644 index e0a0c5b34..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/CoreRegistry.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** client lib Registry - */ -class CoreRegistry{ - private Map registry = - new ConcurrentHashMap(); - - final private EmptyRegistryCallback emptyRegistryCallback; - - - CoreRegistry(EmptyRegistryCallback emptyRegistryCallback){ - this.emptyRegistryCallback = emptyRegistryCallback; - } - - void register(String key, T obj) { - registry.put(key, obj); - } - - T unregister(String key) { - T item = (T) registry.remove(key); - if(registry.isEmpty()) { - emptyRegistryCallback.emptyCallback(); - } - return item; - } - - T get(String key){ - return (T) registry.get(key); - } - - synchronized boolean isExist(String key) { - return registry.containsKey(key); - } - - boolean isEmpty(){ - return registry.isEmpty(); - } - - public interface EmptyRegistryCallback{ - void emptyCallback(); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreAsyncResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreAsyncResponseHandler.java deleted file mode 100644 index 862d56dc3..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreAsyncResponseHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -public interface ICoreAsyncResponseHandler extends ICoreResponseHandler{ - - /** - * Core response to incoming message - * @param message response accepted from protocol - * @param type type of response - * @return true if message is final, false otherwise - */ - boolean onResponse(String message, String type); - - /** - * Core reaction to an event of exception - * @param e the exception which have been thrown - */ - void onException(Exception e); - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreResponseHandler.java deleted file mode 100644 index 555640dfd..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreResponseHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -public interface ICoreResponseHandler { -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreSyncResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreSyncResponseHandler.java deleted file mode 100644 index 996d3d8d2..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ICoreSyncResponseHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -public interface ICoreSyncResponseHandler extends ICoreResponseHandler{ - - /** - * Core response to incoming message, should return completed message only - * @param message response accepted from protocol - * @param type type of response - * @return true if message is final, false otherwise - */ - T onResponse(String message, String type) throws CoreException; -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/IInvocationManager.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/IInvocationManager.java deleted file mode 100644 index 93cf20b3f..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/IInvocationManager.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import java.util.Properties; -import java.util.concurrent.TimeoutException; - -/** - */ -public interface IInvocationManager { - - /** - * initializes the manager - * @param prop properties to read from - * @throws CoreException thrown if madatory fields are not set right - */ - void init(Properties prop) throws CoreException; - - /** - * handles the flow of an async request - * @param request the request body - * @param listener business response handler - * @param correlationId unique id of the request - * @param rpcName rpc call name - * @throws CoreException thrown if the request failed to be sent - */ - void asyncRequest(String request, ICoreAsyncResponseHandler listener, String correlationId, String rpcName) throws CoreException; - - /** - * handles to flow of a sync request - * @param request the request body - * @param callback business response handler - * @param correlationId unique id of the request - * @param rpcName rpc call name - * @return the output object to be returned - * @throws CoreException thrown if the request failed to be sent - * @throws TimeoutException thrown if timeout has exceeded - */ - T syncRequest(String request, ICoreSyncResponseHandler callback, String correlationId, String rpcName) throws CoreException, TimeoutException; - - /** - * shuts the invocation manager down. - * @param isForceShutdown if true, shutdown will be forced, otherwise it will be gracefully - */ - void shutdown(boolean isForceShutdown); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimeoutHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimeoutHandler.java deleted file mode 100644 index 0f3b81a6f..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimeoutHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -interface ITimeoutHandler { - - /** - * handles timeout event - */ - void onTimeout(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimerService.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimerService.java deleted file mode 100644 index 96b06033f..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/ITimerService.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -interface ITimerService { - - /** - * add a new timeout handler to a request - * @param correlationID the id of the request - * @param handler to be called once "timeout' time has arrived - */ - void add(String correlationID, ITimeoutHandler handler); - - /** - * cancel the timeout handler of a request - * @param correlationID the id of the request - */ - void cancel(String correlationID); - - - /** - * shuts the timer service down immediately - */ - void shutdown(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManager.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManager.java deleted file mode 100644 index 8179da107..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManager.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import java.util.Properties; -import java.util.concurrent.TimeoutException; - -/** - * layer for passing requests from API to Core - */ -class InvocationManager implements IInvocationManager{ - - protected CoreManager coreManager = null; - - InvocationManager(){ - } - - public void init(Properties properties) throws CoreException { - coreManager = new CoreManager(properties); - } - - /** - * - * @param request - * @param businessCallback - * @param correlationId - * @param rpcName - * @throws CoreException - */ - public void asyncRequest(String request, ICoreAsyncResponseHandler businessCallback, String correlationId, String rpcName) throws CoreException { - AsyncRequestResponseHandler requestResponseHandler = new AsyncRequestResponseHandler(correlationId, businessCallback, coreManager); - requestResponseHandler.sendRequest(request, correlationId, rpcName); - } - - public T syncRequest(String request, ICoreSyncResponseHandler businessCallback, String correlationId, String rpcName ) throws CoreException, TimeoutException { - SyncRequestResponseHandler requestResponseHandler = new SyncRequestResponseHandler(correlationId, businessCallback, coreManager); - requestResponseHandler.sendRequest(request, correlationId, rpcName); - T responseObject = (T) requestResponseHandler.getResponse(); - return responseObject; - } - - @Override - public void shutdown(boolean isForceShutdown) { - coreManager.shutdown(isForceShutdown); - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManagerFactory.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManagerFactory.java deleted file mode 100644 index c9face762..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/InvocationManagerFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -public abstract class InvocationManagerFactory { - private static IInvocationManager invocationManager = null; - - public static synchronized IInvocationManager getInstance(){ - if(invocationManager == null){ - invocationManager = new InvocationManager(); - } - return invocationManager; - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/MessageContext.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/MessageContext.java deleted file mode 100644 index 6fab66bb3..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/MessageContext.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -/** Helper class for wrapping request/response information. - */ -public class MessageContext { - - /** - * valid values of type are response/error - */ - private String type; - - /** - * RPC name - */ - private String rpc; - - /** - * correlation ID - */ - private String correlationID; - - /** - * partitioner for message bus usage - */ - private String partitioner; - - - public String getRpc() { - return rpc; - } - - public void setRpc(String rpc) { - this.rpc = rpc; - } - - public String getCorrelationID() { - return correlationID; - } - - public void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - public String getPartiton() { - return partitioner; - } - - public void setPartiton(String partitioner) { - this.partitioner = partitioner; - } - - public void setType(String type){ - this.type = type; - } - - public String getType(){ - return type; - } - - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/RequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/RequestResponseHandler.java deleted file mode 100644 index 8e05a2974..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/RequestResponseHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -interface RequestResponseHandler { - - /** - * sends request, registers handler of response and start timer. - * @param request - Request - * @param corrId - correlation ID - * @param rpcName - RPC name - * @throws CoreException - @{@link CoreException} - */ - void sendRequest(String request, String corrId, String rpcName) throws CoreException; - - /** - * submits a handler task to task queue @{@link TaskQueue}, this task will be performed only if this handler is - * still existing in core registry @{@link CoreRegistry}, others timeout was occurred . - * @param ctx - Message Context @{@link MessageContext} - * @param response - Response from backend - */ - void handleResponse(MessageContext ctx, String response); - - /** - * handles timeout event - */ - void onTimeOut(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/SyncRequestResponseHandler.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/SyncRequestResponseHandler.java deleted file mode 100644 index 90b0a9926..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/SyncRequestResponseHandler.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.TimeoutException; - -/** Handles sync requests - */ -class SyncRequestResponseHandler extends AbstractRequestResponseHandler { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(SyncRequestResponseHandler.class); - private T responseObject = null; - private CoreException coreException = null; - private TimeoutException timeoutException = null; - - SyncRequestResponseHandler(String corrID, - ICoreResponseHandler callback, - CoreManager coreManager){ - super(corrID, callback, coreManager); - } - - /** - * Calls API callback for getting response object. in case of complete response notifies consumer - * thread for receiving response - * @param response - Response - * @param type - Type of Response - */ - synchronized void runTask(String response, String type) { - try { - responseObject = ((ICoreSyncResponseHandler) businessCallback).onResponse(response, type); - } catch (CoreException e) { - coreException = e; - } - if(responseObject != null || coreException != null) { - notify(); - } - } - - - /** - * Returns response. goes sleep until coming either timeout event or complete response - */ - public synchronized T getResponse() throws CoreException, TimeoutException { - try{ - if(!isResponseReceived()){ - wait(); - } - if (coreException != null) { - throw coreException; - } - if ( timeoutException != null) { - throw timeoutException; - } - - } catch (InterruptedException e) { - throw new CoreException(e); - } finally{ - coreManager.unregisterHandler(corrID); - coreManager.cancelTimer(corrID); - } - return (T) responseObject; - } - - /** - * indicates if a response received - * @return - */ - private boolean isResponseReceived() { - return responseObject != null; - } - - @Override - public synchronized void onTimeOut() { - LOG.error("sync response handler on timeout correlation ID <" + corrID + ">."); - timeoutException = new TimeoutException("timeout for request with correlation-id " + corrID); - notify(); - } - - - - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueue.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueue.java deleted file mode 100644 index 4ceeb3f08..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueue.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -/** Responsible to ensure synchronous handling of responses and timouts. - */ -class TaskQueue implements Runnable{ - - private final BlockingQueue queue = new LinkedBlockingQueue<>(); - private final EELFLogger LOG = EELFManager.getInstance().getLogger(TaskQueue.class); - - private boolean isShutdown; - - synchronized void addTask(Runnable task) throws InterruptedException { - queue.put(task); - } - - public void run() { - Runnable task; - while(!Thread.currentThread().isInterrupted() && !isShutdown){ - try { - task = queue.take(); - task.run(); - } catch (InterruptedException e) { - LOG.error("could not take task from queue", e); - } catch (RuntimeException e) { - LOG.error("could not run task", e); - } - LOG.info("THR# <" + Thread.currentThread().getId() + "> shutdown indicator " + isShutdown); - } - LOG.info("THR# <" + Thread.currentThread().getId() + "> in shutdown process."); - } - - void stopQueue(){ - isShutdown = true; - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueueManager.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueueManager.java deleted file mode 100644 index b87349411..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TaskQueueManager.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.List; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** Creates a task queue pool that reuses a fixed number of threads. - * Assigns one thread for each queue. - */ -class TaskQueueManager { - private final EELFLogger LOG = EELFManager.getInstance().getLogger(TaskQueueManager.class); - private ExecutorService executorService; - private final static String DEFAULT_POOL_SIZE = "10"; - private final static String CLIENT_POOL_SIZE = "client.pool.size"; - private TaskQueue[] queues; - private int poolInt; - - TaskQueueManager(Properties properties){ - String size = properties.getProperty(CLIENT_POOL_SIZE, DEFAULT_POOL_SIZE); - poolInt = Integer.parseInt(size); - this.executorService = Executors.newFixedThreadPool(poolInt); - initTaskQueues(); - } - - private void initTaskQueues(){ - queues = new TaskQueue[poolInt]; - for(int i=0; i listTask = executorService.shutdownNow(); - if (!executorService.awaitTermination(6, TimeUnit.SECONDS)) - System.err.println("Pool did not terminate"); - LOG.info("the amount of tasks that never commenced execution " + listTask.size()); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TimerServiceImpl.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TimerServiceImpl.java deleted file mode 100644 index fa2d0804d..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/core/TimerServiceImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.List; -import java.util.concurrent.*; - -class TimerServiceImpl implements ITimerService { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(TimerServiceImpl.class); - private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); - private final ConcurrentHashMap timeOutEvents = new ConcurrentHashMap<>(); - private final long responseTimeout; - - TimerServiceImpl(long responseTimeout) { - this.responseTimeout = responseTimeout; - } - - @Override - public synchronized void cancel(String correlationID) { - Future timeOutEvent = timeOutEvents.remove(correlationID); - if (timeOutEvent != null){ - timeOutEvent.cancel(true); - } - } - - @Override - public synchronized void add(String correlationID, ITimeoutHandler handler) { - Future timeOutEvent = scheduler.schedule(new HandleTimeout(correlationID, handler), responseTimeout, TimeUnit.MILLISECONDS); - timeOutEvents.put(correlationID, timeOutEvent); - } - - @Override - public void shutdown() { - List listTask = scheduler.shutdownNow(); - LOG.info("the amount of tasks that never commenced execution " + listTask.size()); - } - - private class HandleTimeout implements Runnable { - - String correlationID; - ITimeoutHandler handler; - - HandleTimeout(String correlationID, ITimeoutHandler handler) { - this.correlationID = correlationID; - this.handler = handler; - } - - @Override - public void run(){ - System.out.println("Timeout event of request " + correlationID); - handler.onTimeout(); - timeOutEvents.remove(correlationID); - } - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriter.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriter.java deleted file mode 100644 index a76f0a90b..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriter.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -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 java.io.IOException; - -class APPCMessageReaderWriter implements MessageReader, MessageWriter { - - private final ObjectMapper mapper; - private final EELFLogger LOG = EELFManager.getInstance().getLogger(APPCMessageReaderWriter.class); - - APPCMessageReaderWriter() { - mapper = new ObjectMapper(); - } - - public String read(String payload, MessageContext context) throws ProtocolException { - try { - ProtocolMessage protocolMessage = mapper.readValue(payload, ProtocolMessage.class); - context.setType(protocolMessage.getType()); - context.setRpc(protocolMessage.getRpcName()); - context.setCorrelationID(protocolMessage.getCorrelationID()); - context.setPartiton(protocolMessage.getPartition()); - String body = protocolMessage.getBody().toString(); - LOG.debug("Received body : <" + body + ">"); - return body; - } catch (IOException e) { - throw new ProtocolException(e); - } - - } - - public String write(String payload, MessageContext context) throws ProtocolException { - try { - ProtocolMessage protocolMessage = new ProtocolMessage(); - protocolMessage.setVersion("2.0"); - protocolMessage.setType(context.getType()); - protocolMessage.setRpcName(context.getRpc()); - protocolMessage.setCorrelationID(context.getCorrelationID()); - protocolMessage.setPartition(context.getPartiton()); - JsonNode body = mapper.readTree(payload); - protocolMessage.setBody(body); - String message = mapper.writeValueAsString(protocolMessage); - return message; - } catch (IOException e) { - throw new ProtocolException(e); - } - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocol.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocol.java deleted file mode 100644 index 94d2d6b85..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocol.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; - -public interface AsyncProtocol extends Protocol { - - /** - * sends a string message to underlying message bus/java API - * @param payload - meesage body - * @param context - message headers - * @throws ProtocolException - */ - void sendRequest(String payload, MessageContext context) throws ProtocolException; - - void shutdown(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocolImpl.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocolImpl.java deleted file mode 100644 index 82626d802..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/AsyncProtocolImpl.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -class AsyncProtocolImpl implements AsyncProtocol { - - /** - * message bus listener thread handler - */ - private Future listenerHandler; - /** - * called when messages are fetched - called for a single message - */ - private RetrieveMessageCallback callback; - /** - * message bus client used to send/fetch - */ - private MessagingService messageService; - /** - * Message reader used to extract body and context from reponse message - */ - private MessageReader messageReader; - /** - * Message writer used to construct meesage from body and context - */ - private MessageWriter messageWriter; - - /** - * shutdown indicator - */ - private boolean isShutdown = false; - - /** - * executor service for listener usage - */ - private ExecutorService executorService = Executors.newSingleThreadExecutor(); - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(AsyncProtocolImpl.class); - - - AsyncProtocolImpl() { - - messageService = new UEBMessagingService(); - messageReader = new APPCMessageReaderWriter(); - messageWriter = (MessageWriter) messageReader; - } - - public void init(Properties props, RetrieveMessageCallback callback) throws ProtocolException { - - if (callback == null) { - throw new ProtocolException("Callback param should not be null!"); - } - this.callback = callback; - - try { - messageService.init(props); - //get message bus listener thread - //start the thread after initializing services - listenerHandler = executorService.submit(new Listener()); - } catch (GeneralSecurityException | IllegalAccessException | NoSuchFieldException | IOException e) { - throw new ProtocolException(e); - } - } - - public void sendRequest(String payload, MessageContext context) throws ProtocolException { - - //get message to be sent to appc from payload and context - String message = messageWriter.write(payload, context); - try { - messageService.send(context.getPartiton(), message); - LOG.debug("Successfully send message: " + message); - } catch (IOException e) { - throw new ProtocolException(e); - } - } - - @Override - public void shutdown() { - isShutdown = true; - messageService.close(); - LOG.warn("The protocol layer in shutdown stage."); - executorService.shutdownNow(); - } - - public class Listener implements Runnable { - - - public void run() { - - while (!isShutdown) { - List messages = new ArrayList<>(); - try { - messages = messageService.fetch(); - LOG.debug("Successfully fetched " + messages.size() + " messages"); - } catch (IOException e) { - LOG.error("Fetching " + messages.size() + " messages failed"); - } - for (String message : messages) { - - MessageContext context = new MessageContext(); - String payload = null; - - try { - //get payload and context from message to be sent to core layer - payload = messageReader.read(message, context); - LOG.debug("Got body: " + payload); - //call core layer response handler - if(!isShutdown) { - callback.onResponse(payload, context); - }else{ - LOG.warn("Shutdown in progress, response will not receive. Correlation ID <" + - context.getCorrelationID() + "> response ", message); - } - } catch (ProtocolException e) { - LOG.error("Failed to read message from UEB. message is: " + message); - } - } - } - } - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Consumer.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Consumer.java deleted file mode 100644 index 4765a58ef..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Consumer.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import java.io.IOException; -import java.util.List; - -interface Consumer { - - /** - * Gets a batch of messages from the topic. Defaults to 1000 messages with 15s wait for messages if empty. - * - * @return A list of strings representing the messages pulled from the topic. - * @throws IOException - */ - List fetch() throws IOException; - - /** - * Gets a batch of messages from the topic. - * - * @param limit The amount of messages to fetch - * @return A list of strings representing the messages pulled from the topic. - * @throws IOException - */ - List fetch(int limit) throws IOException; - - /** - * Send dummy fetch request to register client to be able to fetch messages - * @throws IOException - */ - void registerForRead() throws IOException; - - void close(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ConsumerImpl.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ConsumerImpl.java deleted file mode 100644 index 913f80f44..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ConsumerImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; -import com.att.nsa.cambria.client.CambriaConsumer; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -class ConsumerImpl implements Consumer { - - private static final int DEFAULT_LIMIT = 1000; - - private Collection hosts; - private String topic; - private String group; - private String groupId; - private int timeout; - - private String authKey; - private String authSecret; - - private CambriaConsumer consumer = null; - - /** - * constructor - * @param urls - * @param topicName - * @param consumerName - * @param consumerId - * @param timeout - */ - public ConsumerImpl(Collection urls, String topicName, String consumerName, String consumerId, Integer timeout, String apiKey, String apiSecret) throws MalformedURLException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { - this.hosts = urls; - this.topic = topicName; - this.group = consumerName; - this.groupId = consumerId; - this.authKey = apiKey; - this.authSecret = apiSecret; - this.timeout = timeout; - consumer = getConsumer(); - } - - - public List fetch() throws IOException { - - return fetch(DEFAULT_LIMIT); - } - - public List fetch(int limit) throws IOException { - - List out = new ArrayList(); - try { - for(String msg : consumer.fetch(timeout,limit)){ - out.add(msg); - } - } catch (IOException e) { - throw e; - } - return out; - } - - public void registerForRead() throws IOException { - - int waitForRegisteration = 1; //return from fetch after 1ms, no need to read any messages - consumer.fetch(waitForRegisteration, 1); - } - - /** - * init cambria consumer - * @return CambriaConsumer - */ - private CambriaConsumer getConsumer() throws MalformedURLException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { - - ConsumerBuilder builder = new ConsumerBuilder(); - - builder.usingHosts(hosts).onTopic(topic).knownAs(group, groupId); - builder.withSocketTimeout(timeout + 5000).waitAtServer(timeout); - builder.receivingAtMost(DEFAULT_LIMIT); - - // Add credentials if provided - if (authKey != null && authSecret != null) { - - Field apiKeyField = ConsumerBuilder.class.getDeclaredField("fApiKey"); - apiKeyField.setAccessible(true); - apiKeyField.set(builder, ""); - builder.authenticatedBy(authKey, authSecret); - } - - return builder.build(); - } - - @Override - public void close() { - consumer.close(); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageReader.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageReader.java deleted file mode 100644 index 19688d696..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageReader.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; - -public interface MessageReader { - - /** - * reads payload, fills the context out of payload headers, and returns the body of the payload - * @param payload incoming message - * @param context context to fill - * @return body of the payload - * @throws ProtocolException - */ - String read(String payload, MessageContext context) throws ProtocolException; -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageWriter.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageWriter.java deleted file mode 100644 index 0849bc4a4..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessageWriter.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -import com.fasterxml.jackson.databind.JsonNode; - -public interface MessageWriter { - - /** - * builds a message out of context and payload - * @param payload body of the message - * @param context headers of the message - * @return the message to write/send - * @throws ProtocolException - */ - String write(String payload, MessageContext context) throws ProtocolException; -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessagingService.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessagingService.java deleted file mode 100644 index 029378931..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/MessagingService.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Properties; - -interface MessagingService { - - /** - * initialize consumer/publisher - * @param props - */ - void init(Properties props) throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException; - - /** - * sends a string as is - * @param partition - * @param body - */ - void send(String partition, String body) throws IOException; - - /** - * retrieve messages from bus - timeout extracted from props or see impl - * @return - */ - List fetch() throws IOException; - - /** - * retrieve messages from bus - timeout extracted from props or see impl - * @param limit - * @return - */ - List fetch(int limit) throws IOException; - - void close(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Producer.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Producer.java deleted file mode 100644 index f290e8a89..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Producer.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import java.io.IOException; - -interface Producer { - - /** - * send a message to a partition via ueb - * @param data - */ - void post(String Partition, String data) throws IOException; - - void close(); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProducerImpl.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProducerImpl.java deleted file mode 100644 index 7729db98d..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProducerImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.Collection; - -class ProducerImpl implements Producer { - - private Collection hosts; - private String topic; - private CambriaBatchingPublisher producer; - - private String authKey; - private String authSecret; - - public ProducerImpl(Collection urls, String topicName, String apiKey, String apiSecret) throws MalformedURLException, GeneralSecurityException { - - topic = topicName; - hosts = urls; - authKey = apiKey; - authSecret = apiSecret; - producer = getProducer(); - } - - public void post(String partition, String data) throws IOException { - - producer.send(partition, data); - } - - /** - * get cambria producer - * @return - */ - private CambriaBatchingPublisher getProducer() throws MalformedURLException, GeneralSecurityException { - - PublisherBuilder builder = new PublisherBuilder().usingHosts(hosts); - - // Add credentials if provided - if (authKey != null && authSecret != null) { - builder.authenticatedBy(authKey, authSecret); - } - - CambriaBatchingPublisher client = null; - - client = builder.onTopic(topic).build(); - - return client; - } - - @Override - public void close() { - producer.close(); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Protocol.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Protocol.java deleted file mode 100644 index eaa21d857..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/Protocol.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import java.util.Properties; - -public interface Protocol { - - /** - * init protocol properties and callback - * @param props - * @param callback - * @throws ProtocolException - */ - void init(Properties props, RetrieveMessageCallback callback) throws ProtocolException; -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolException.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolException.java deleted file mode 100644 index eb0537b80..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -public class ProtocolException extends Exception { - - public ProtocolException() { - super(); - } - - public ProtocolException(String message) { - super(message); - } - - public ProtocolException(String message, Throwable cause) { - super(message, cause); - } - - public ProtocolException(Throwable cause) { - super(cause); - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolFactory.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolFactory.java deleted file mode 100644 index 98e7d669b..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import java.util.HashMap; -import java.util.Map; - -public class ProtocolFactory { - - private static ProtocolFactory instance; - private Map protocols; - - /** - * Singleton factory - */ - private ProtocolFactory(){ - - protocols = new HashMap(); - } - - /** - * get factory instance - * @return factory instance - */ - public static synchronized ProtocolFactory getInstance(){ - - if (instance == null) { - instance = new ProtocolFactory(); - } - return instance; - } - - /** - * returns instantiated protocol object - * @param type of protocol object - * @return protocol object - */ - public Protocol getProtocolObject(ProtocolType type) throws ProtocolException { - - Protocol protocol = protocols.get(type); - synchronized (this) { - if (protocol == null) { - switch (type) { - case SYNC: - throw new ProtocolException("Protocol SYNC is not implemented"); - case ASYNC: - protocol = new AsyncProtocolImpl(); - protocols.put(type, protocol); - break; - default: - throw new ProtocolException("Protocol type not found"); - } - } - } - return protocol; - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolMessage.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolMessage.java deleted file mode 100644 index c02ea5607..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolMessage.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.JsonNode; - -class ProtocolMessage { - - private String version; - private String type; - private String rpcName; - private String correlationID; // correlation-id - private String partition; // cambria.partition - private JsonNode body; - - @JsonProperty - String getVersion() { - return version; - } - - @JsonProperty - void setVersion(String version) { - this.version = version; - } - - @JsonProperty - String getType() { - return type; - } - - @JsonProperty - void setType(String type) { - this.type = type; - } - - @JsonProperty("rpc-name") - String getRpcName() { - return rpcName; - } - - @JsonProperty("rpc-name") - void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - @JsonProperty("correlation-id") - String getCorrelationID() { - return correlationID; - } - - @JsonProperty("correlation-id") - void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - @JsonProperty("cambria.partition") - String getPartition() { - return partition; - } - - @JsonProperty("cambria.partition") - void setPartition(String partition) { - this.partition = partition; - } - - @JsonProperty - JsonNode getBody() { - return body; - } - - @JsonProperty - void setBody(JsonNode body) { - this.body = body; - } -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolType.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolType.java deleted file mode 100644 index cc2eca447..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/ProtocolType.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -public enum ProtocolType { - - SYNC, ASYNC; -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/RetrieveMessageCallback.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/RetrieveMessageCallback.java deleted file mode 100644 index 8fc486bb8..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/RetrieveMessageCallback.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - - -import org.onap.appc.client.impl.core.MessageContext; - -public interface RetrieveMessageCallback { - - /** - * called when response received - * @param payload - * @param context - */ - void onResponse(String payload, MessageContext context); -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBMessagingService.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBMessagingService.java deleted file mode 100644 index df51861b8..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBMessagingService.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.*; - -class UEBMessagingService implements MessagingService { - - private Consumer consumer; - private Producer producer; - - private final String DEFAULT_READ_TIMEOUT_MS = "60000"; - private final String DEFAULT_READ_LIMIT = "1000"; - - private int readLimit; - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(UEBMessagingService.class); - - @SuppressWarnings("Since15") - public void init(Properties props) throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { - - if (props != null) { - String readTopic = props.getProperty(UEBPropertiesKeys.TOPIC_READ); - String writeTopic = props.getProperty(UEBPropertiesKeys.TOPIC_WRITE); - String apiKey = props.getProperty(UEBPropertiesKeys.AUTH_USER); - String apiSecret = props.getProperty(UEBPropertiesKeys.AUTH_SECRET); - String readTimeoutString = props.getProperty(UEBPropertiesKeys.TOPIC_READ_TIMEOUT, DEFAULT_READ_TIMEOUT_MS); - Integer readTimeout = Integer.parseInt(readTimeoutString); - String readLimitString = props.getProperty(UEBPropertiesKeys.READ_LIMIT, DEFAULT_READ_LIMIT); - readLimit = Integer.parseInt(readLimitString); - //get hosts pool - Collection pool = new HashSet(); - String hostNames = props.getProperty(UEBPropertiesKeys.HOSTS); - if (hostNames != null && !hostNames.isEmpty()) { - for (String name : hostNames.split(",")) { - pool.add(name); - } - } - - //generate consumer id and group - same value for both - String consumerName = UUID.randomUUID().toString(); - String consumerID = consumerName; - - //create consumer and producer - consumer = new ConsumerImpl(pool, readTopic, consumerName, consumerID, readTimeout, apiKey, apiSecret); - producer = new ProducerImpl(pool, writeTopic, apiKey, apiSecret); - - //initial consumer registration - try { - consumer.registerForRead(); - }catch(Exception e){ - LOG.error("Message consumer failed to register client "+consumerID); - } - } - } - - public void send(String partition, String body) throws IOException { - producer.post(partition, body); - } - - public List fetch() throws IOException { - return consumer.fetch(readLimit); - } - - public List fetch(int limit) throws IOException { - return consumer.fetch(limit); - } - - @Override - public void close() { - consumer.close(); - producer.close(); - } - -} diff --git a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBPropertiesKeys.java b/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBPropertiesKeys.java deleted file mode 100644 index 5c1916f2b..000000000 --- a/appc-client/client-lib/src/main/java/org/openecomp/appc/client/impl/protocol/UEBPropertiesKeys.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -class UEBPropertiesKeys { - - static final String TOPIC_READ = "topic.read"; - static final String TOPIC_READ_TIMEOUT = "topic.read.timeout"; - static final String READ_LIMIT = "topic.read.limit"; - static final String TOPIC_WRITE = "topic.write"; - static final String AUTH_USER = "client.key"; - static final String AUTH_SECRET = "client.secret"; - static final String HOSTS = "poolMembers"; -} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/ResponseManagerTest.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/ResponseManagerTest.java new file mode 100644 index 000000000..cc157e5c4 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/ResponseManagerTest.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import org.onap.appc.client.impl.core.AsyncRequestResponseHandler; +import org.onap.appc.client.impl.core.CoreException; +import org.onap.appc.client.impl.core.CoreManager; +import org.onap.appc.client.impl.core.ICoreAsyncResponseHandler; +import org.onap.appc.client.impl.core.MessageContext; +import org.onap.appc.client.impl.protocol.AsyncProtocol; +import org.onap.appc.client.impl.protocol.ProtocolException; +import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; +import org.junit.Before; + +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.mockito.Mockito.mock; + +public class ResponseManagerTest { + + private final ExecutorService executorService = Executors.newFixedThreadPool(10); + ICoreAsyncResponseHandler listener1 = new ListenerImpl(); + ICoreAsyncResponseHandler listener2 = new SleeepListenerImpl(); + ICoreAsyncResponseHandler listener3 = new ListenerImpl(); + CoreManager coreManager = null; + + public void initialize() throws CoreException { + Properties prop = new Properties(); + prop.setProperty("client.pool.size", "10"); + prop.setProperty("client.response.timeout", "7000"); + coreManager = new ResponseManagerTest.CoreManagerTest(prop); + } + + void asyncRequest(String request, ICoreAsyncResponseHandler businessCallback, String correlationId, String rpcName) throws CoreException { + AsyncRequestResponseHandler requestResponseHandler = new AsyncRequestResponseHandler(correlationId, businessCallback, coreManager); + requestResponseHandler.sendRequest(request, correlationId, rpcName); + } + + public void simpleResponseTest() throws Exception { + System.out.println("simpleResponseTest"); + asyncRequest("request 1", listener1,"vasia1", "test"); + MessageContext msgCtx = new MessageContext(); + msgCtx.setCorrelationID("vasia1"); + msgCtx.setType("response"); + coreManager.getProtocolCallback().onResponse("vasia1 response",msgCtx); + coreManager.getProtocolCallback().onResponse("vasia2 response",msgCtx); + Thread.sleep(10); + } + + public void twoResponseTest() throws Exception { + System.out.println("twoResponseTest"); + asyncRequest("twoResponseTest request 1", listener2,"vasia2", "test"); + MessageContext msgCtx = new MessageContext(); + msgCtx.setCorrelationID("vasia2"); + msgCtx.setType("response"); + coreManager.getProtocolCallback().onResponse("second of vasia2",msgCtx); + Thread.sleep(100); + asyncRequest("twoResponseTest request 2", listener1,"vasia1", "test"); + MessageContext msgCtx2 = new MessageContext(); + msgCtx2.setCorrelationID("vasia1"); + msgCtx2.setType("response"); + coreManager.getProtocolCallback().onResponse("first of vasia1",msgCtx2); + Thread.sleep(150); + } + + public void threeResponseTest() throws Exception { + System.out.println("treeResponseTest"); + asyncRequest("threeResponseTest request 2", listener1,"vasia4", "test"); + asyncRequest("threeResponseTest request 1", listener2,"vasia2", "test"); + MessageContext msgCtx2 = new MessageContext(); + msgCtx2.setCorrelationID("vasia2"); + msgCtx2.setType("response"); + coreManager.getProtocolCallback().onResponse("second of vasia2",msgCtx2); + + asyncRequest("threeResponseTest request 2", listener1,"vasia1", "test"); + MessageContext msgCtx1 = new MessageContext(); + msgCtx1.setCorrelationID("vasia1"); + msgCtx1.setType("response"); + coreManager.getProtocolCallback().onResponse("vasia1",msgCtx1); + + asyncRequest("threeResponseTest request 3", listener3,"vasia3", "test"); + MessageContext msgCtx3 = new MessageContext(); + msgCtx3.setCorrelationID("vasia3"); + msgCtx3.setType("response"); + coreManager.getProtocolCallback().onResponse("three1",msgCtx3); + + coreManager.getProtocolCallback().onResponse("three2", msgCtx3); + + coreManager.getProtocolCallback().onResponse("first1", msgCtx1); + Thread.sleep(250); + + coreManager.getProtocolCallback().onResponse("first2", msgCtx1); + Thread.sleep(10000); + } + + private class ListenerImpl implements ICoreAsyncResponseHandler{ + + public boolean onResponse(String message, String type) { + System.out.println("callback " + message); + return message != null; + } + + @Override + public void onException(Exception e) { + e.printStackTrace(); + } + } + + private class SleeepListenerImpl implements ICoreAsyncResponseHandler{ + + public boolean onResponse(String message, String type) { + try { + Thread.sleep(150); + System.out.println("sleep callback " + message); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return message != null; + } + + @Override + public void onException(Exception e) { + e.printStackTrace(); + } + } + + class CoreManagerTest extends CoreManager{ + CoreManagerTest(Properties properties) throws CoreException { + super(properties); + protocol = mock(AsyncProtocol.class); + } + protected void sendRequest2Protocol(String request, String corrId, String rpcName) throws CoreException { + } + + protected void initProtocol(Properties properties, RetrieveMessageCallback protocolCallback) throws ProtocolException { + + } + } +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/SyncFlowTest.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/SyncFlowTest.java new file mode 100644 index 000000000..2e69369b9 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/core/SyncFlowTest.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.core; + +import org.onap.appc.client.impl.core.CoreException; +import org.onap.appc.client.impl.core.CoreManager; +import org.onap.appc.client.impl.core.ICoreSyncResponseHandler; +import org.onap.appc.client.impl.core.MessageContext; +import org.onap.appc.client.impl.core.SyncRequestResponseHandler; +import org.onap.appc.client.impl.protocol.AsyncProtocol; +import org.onap.appc.client.impl.protocol.ProtocolException; +import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; +import org.junit.Assert; +import org.junit.Before; + +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeoutException; + +import static org.mockito.Mockito.mock; + +public class SyncFlowTest { + CoreManager coreManager = null; + + public void initialize() throws CoreException { + Properties prop = new Properties(); + prop.setProperty("client.pool.size", "10"); + prop.setProperty("client.response.timeout", "7000"); + coreManager = new CoreManagerTest(prop); + } + + T syncRequest(String request, ICoreSyncResponseHandler businessCallback, String correlationId, String rpcName ) throws CoreException, TimeoutException { + SyncRequestResponseHandler requestResponseHandler = new SyncRequestResponseHandler(correlationId, businessCallback, coreManager); + requestResponseHandler.sendRequest(request, correlationId, rpcName); + T responseObject = (T) requestResponseHandler.getResponse(); + return responseObject; + } + + public void blockRequestTest(){ + ICoreSyncResponseHandler handler = new ICoreSyncResponseHandlerImpl1(); + try { + syncRequest("request 1", handler, "vasia1", "test"); + }catch (Throwable e){ + e.printStackTrace(); + Assert.assertTrue(e != null); + } + + } + + public void blockRequestSucceedTest() throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(2); + final ICoreSyncResponseHandler handler = new ICoreSyncResponseHandlerImpl1(); + try { + executorService.submit(new Runnable() { + public void run() { + System.out.println("Send request"); + T response; + try { + response = syncRequest("request 1", handler, "vasia1", "test"); + System.out.println("=======" + response.toString()); + } catch (CoreException e) { + e.printStackTrace(); + } catch (TimeoutException e) { + e.printStackTrace(); + } + } + }); + }catch (Throwable e){ + Assert.assertTrue((RuntimeException)e != null); + } + Thread.sleep(2000); + executorService.submit(new Runnable() { + public void run() { + MessageContext ctx = new MessageContext(); + ctx.setCorrelationID("vasia1"); + ctx.setType("response"); + try { + System.out.println("Send response 1"); + coreManager.getProtocolCallback().onResponse("response for request 1", ctx); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + Thread.sleep(2000); + executorService.submit(new Runnable() { + public void run() { + MessageContext ctx = new MessageContext(); + ctx.setCorrelationID("vasia1"); + ctx.setType("response"); + try { + System.out.println("Send response 2"); + coreManager.getProtocolCallback().onResponse("response for request 1 final", ctx); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + Thread.sleep(1000); + + } + + class ICoreSyncResponseHandlerImpl1 implements ICoreSyncResponseHandler{ + + + public T onResponse(String message, String type) { + System.out.println("Received message = " + message) ; + if(message.contains("final")){ + return (T) new String(message); + } + return null; + } + } + + class CoreManagerTest extends CoreManager{ + CoreManagerTest(Properties properties) throws CoreException { + super(properties); + protocol = mock(AsyncProtocol.class); + } + protected void sendRequest2Protocol(String request, String corrId, String rpcName) throws CoreException { + } + + protected void initProtocol(Properties properties, RetrieveMessageCallback protocolCallback) throws ProtocolException{ + + } + } +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriterTest.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriterTest.java new file mode 100644 index 000000000..1d41a52f8 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/APPCMessageReaderWriterTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +import org.onap.appc.client.impl.protocol.APPCMessageReaderWriter; +import org.onap.appc.client.impl.protocol.ProtocolException; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.io.StringWriter; + +public class APPCMessageReaderWriterTest { + + private APPCMessageReaderWriter messageReaderWriter; + private ObjectMapper mapper; + + private static final String VERSION = "2.0"; + private static final String TYPE = "typeTest"; + private static final String CORRELATION_ID = "correlationIdTest"; + private static final String PARTITION = "partitionTest"; + private static final String RPC = "rpcTest"; + private static final String PAYLOAD = "{\"key1\":\"val1\",\"key2\":\"val2\",\"key3\":{\"key3.1\":\"val3.1\"}}"; + + @Before + public void init() throws IOException { + mapper = new ObjectMapper(); + messageReaderWriter = new APPCMessageReaderWriter(); + } + + @Test + public void writeTest() throws IOException, ProtocolException { + MessageContext context = new MessageContext(); + context.setType(TYPE); + context.setCorrelationID(CORRELATION_ID); + context.setPartiton(PARTITION); + context.setRpc(RPC); + String payload = PAYLOAD; + String message = messageReaderWriter.write(payload, context); + + JsonNode messageJson = mapper.readTree(message); + Assert.assertEquals(VERSION, messageJson.get("version").asText()); + Assert.assertEquals(context.getType(), messageJson.get("type").asText()); + Assert.assertEquals(context.getCorrelationID(), messageJson.get("correlation-id").asText()); + Assert.assertEquals(context.getPartiton(), messageJson.get("cambria.partition").asText()); + Assert.assertEquals(context.getRpc(), messageJson.get("rpc-name").asText()); + Assert.assertEquals(payload, messageJson.get("body").toString()); + } + + @Test + public void readTest() throws IOException, ProtocolException { + ObjectNode node = mapper.createObjectNode(); + node.put("version", VERSION); + node.put("type", TYPE); + node.put("correlation-id", CORRELATION_ID); + node.put("cambria.partition", PARTITION); + node.put("rpc-name", RPC); + JsonNode payload = mapper.valueToTree(PAYLOAD); + node.set("body", payload); + String message = node.toString(); + + MessageContext returnContext = new MessageContext(); + String returnPayload = messageReaderWriter.read(message, returnContext); + + Assert.assertEquals(TYPE, returnContext.getType()); + Assert.assertEquals(CORRELATION_ID, returnContext.getCorrelationID()); + Assert.assertEquals(PARTITION, returnContext.getPartiton()); + Assert.assertEquals(RPC, returnContext.getRpc()); + Assert.assertEquals(payload.toString(), returnPayload); + } + +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImpl.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImpl.java new file mode 100644 index 000000000..ceba10b58 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImpl.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +import org.onap.appc.client.impl.protocol.AsyncProtocol; +import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; +import org.onap.appc.client.impl.protocol.ProtocolException; +import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; +import org.onap.appc.client.impl.protocol.UEBPropertiesKeys; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; + +public class TestAsyncProtocolImpl { + + private static AsyncProtocol protocol; + private static AtomicBoolean gotResponse; + private static Properties props; + + private static class TestCallback implements RetrieveMessageCallback{ + + public void onResponse(String payload, MessageContext context) { + Assert.assertNotEquals(null, payload); + Assert.assertNotEquals(null, context); + protocol = null; + gotResponse.set(true); + } + } + + @BeforeClass + public static void setUp() throws IOException, ProtocolException { + + gotResponse = new AtomicBoolean(false); + + props = new Properties(); + String propFileName = "ueb.properties"; + + InputStream input = TestAsyncProtocolImpl.class.getClassLoader().getResourceAsStream(propFileName); + + props.load(input); + + protocol = new AsyncProtocolImpl(); + protocol.init(props, new TestCallback()); + } + + public void testSendRequest() throws ProtocolException { + + MessageContext context = new MessageContext(); + context.setType("Test"); + + protocol.sendRequest("{\"Test\":\"\"}", context); + + try { + Long timeToSleep = Long.parseLong((String)props.get(UEBPropertiesKeys.TOPIC_READ_TIMEOUT))*2; + Thread.sleep(timeToSleep); + } catch (InterruptedException e) { + Assert.assertFalse(e.getMessage(), false); + } + if (gotResponse.get() == false) { + Assert.assertFalse("Message was not read !", true); + } + } +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java new file mode 100644 index 000000000..267282abd --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.onap.appc.client.impl.core.MessageContext; +import org.onap.appc.client.impl.protocol.AsyncProtocol; +import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; +import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class TestAsyncProtocolImplMissingProps { + + private static AsyncProtocol protocol; + + private static class TestCallback implements RetrieveMessageCallback { + + public void onResponse(String payload, MessageContext context) { + Assert.assertFalse("bad Callback !",false); + } + } + + @Test + /** + * protocol should throw illegal argument exception due to null properties + */ + public void testSetUpMissingProps() { + + Properties props = new Properties(); + String propFileName = "ueb.missing.properties"; + + InputStream input = TestAsyncProtocolImplMissingProps.class.getClassLoader().getResourceAsStream(propFileName); + + try { + props.load(input); + } catch (IOException e) { + Assert.assertFalse(e.getMessage(),false); + } + + protocol = new AsyncProtocolImpl(); + try { + protocol.init(props, new TestCallback()); + } catch (IllegalArgumentException e) { + Assert.assertTrue(true); + } catch (Exception e) { + Assert.assertFalse(e.getMessage(),false); + } + } +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java new file mode 100644 index 000000000..22954cd75 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.client.impl.protocol.AsyncProtocol; +import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; +import org.onap.appc.client.impl.protocol.ProtocolException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class TestAsyncProtocolImplNullCallback { + + private static AsyncProtocol protocol; + + public void testSetUpNoCallback() throws IOException { + + Properties props = new Properties(); + String propFileName = "ueb.properties"; + + InputStream input = TestAsyncProtocolImpl.class.getClassLoader().getResourceAsStream(propFileName); + + props.load(input); + + protocol = new AsyncProtocolImpl(); + + try { + protocol.init(props, null); + } catch (ProtocolException e) { + Assert.assertTrue(true); + } catch (Exception e){ + Assert.assertFalse(e.getMessage(),false); + } + } +} diff --git a/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestUEBMessagingService.java b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestUEBMessagingService.java new file mode 100644 index 000000000..de192ab12 --- /dev/null +++ b/appc-client/client-lib/src/test/java/org/onap/appc/client/impl/protocol/TestUEBMessagingService.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.client.impl.protocol; + +import org.junit.*; +import org.junit.runners.MethodSorters; +import org.onap.appc.client.impl.protocol.MessagingService; +import org.onap.appc.client.impl.protocol.UEBMessagingService; + +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Properties; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestUEBMessagingService { + + private static MessagingService ueb; + + public static void setUp() throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { + + Properties props = new Properties(); + String propFileName = "ueb.properties"; + + InputStream input = TestUEBMessagingService.class.getClassLoader().getResourceAsStream(propFileName); + + props.load(input); + + ueb = new UEBMessagingService(); + ueb.init(props); + } + + public void test1Send() throws IOException { + System.out.println("Here"); + + String message = "Test Message Service"; + ueb.send(null,message); + } + + public void test2Fetch() throws IOException { + + System.out.println("Here2"); + List messages = ueb.fetch(1); + Assert.assertEquals(1,messages.size()); + } + +} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/ResponseManagerTest.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/ResponseManagerTest.java deleted file mode 100644 index cc157e5c4..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/ResponseManagerTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import org.onap.appc.client.impl.core.AsyncRequestResponseHandler; -import org.onap.appc.client.impl.core.CoreException; -import org.onap.appc.client.impl.core.CoreManager; -import org.onap.appc.client.impl.core.ICoreAsyncResponseHandler; -import org.onap.appc.client.impl.core.MessageContext; -import org.onap.appc.client.impl.protocol.AsyncProtocol; -import org.onap.appc.client.impl.protocol.ProtocolException; -import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; -import org.junit.Before; - -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static org.mockito.Mockito.mock; - -public class ResponseManagerTest { - - private final ExecutorService executorService = Executors.newFixedThreadPool(10); - ICoreAsyncResponseHandler listener1 = new ListenerImpl(); - ICoreAsyncResponseHandler listener2 = new SleeepListenerImpl(); - ICoreAsyncResponseHandler listener3 = new ListenerImpl(); - CoreManager coreManager = null; - - public void initialize() throws CoreException { - Properties prop = new Properties(); - prop.setProperty("client.pool.size", "10"); - prop.setProperty("client.response.timeout", "7000"); - coreManager = new ResponseManagerTest.CoreManagerTest(prop); - } - - void asyncRequest(String request, ICoreAsyncResponseHandler businessCallback, String correlationId, String rpcName) throws CoreException { - AsyncRequestResponseHandler requestResponseHandler = new AsyncRequestResponseHandler(correlationId, businessCallback, coreManager); - requestResponseHandler.sendRequest(request, correlationId, rpcName); - } - - public void simpleResponseTest() throws Exception { - System.out.println("simpleResponseTest"); - asyncRequest("request 1", listener1,"vasia1", "test"); - MessageContext msgCtx = new MessageContext(); - msgCtx.setCorrelationID("vasia1"); - msgCtx.setType("response"); - coreManager.getProtocolCallback().onResponse("vasia1 response",msgCtx); - coreManager.getProtocolCallback().onResponse("vasia2 response",msgCtx); - Thread.sleep(10); - } - - public void twoResponseTest() throws Exception { - System.out.println("twoResponseTest"); - asyncRequest("twoResponseTest request 1", listener2,"vasia2", "test"); - MessageContext msgCtx = new MessageContext(); - msgCtx.setCorrelationID("vasia2"); - msgCtx.setType("response"); - coreManager.getProtocolCallback().onResponse("second of vasia2",msgCtx); - Thread.sleep(100); - asyncRequest("twoResponseTest request 2", listener1,"vasia1", "test"); - MessageContext msgCtx2 = new MessageContext(); - msgCtx2.setCorrelationID("vasia1"); - msgCtx2.setType("response"); - coreManager.getProtocolCallback().onResponse("first of vasia1",msgCtx2); - Thread.sleep(150); - } - - public void threeResponseTest() throws Exception { - System.out.println("treeResponseTest"); - asyncRequest("threeResponseTest request 2", listener1,"vasia4", "test"); - asyncRequest("threeResponseTest request 1", listener2,"vasia2", "test"); - MessageContext msgCtx2 = new MessageContext(); - msgCtx2.setCorrelationID("vasia2"); - msgCtx2.setType("response"); - coreManager.getProtocolCallback().onResponse("second of vasia2",msgCtx2); - - asyncRequest("threeResponseTest request 2", listener1,"vasia1", "test"); - MessageContext msgCtx1 = new MessageContext(); - msgCtx1.setCorrelationID("vasia1"); - msgCtx1.setType("response"); - coreManager.getProtocolCallback().onResponse("vasia1",msgCtx1); - - asyncRequest("threeResponseTest request 3", listener3,"vasia3", "test"); - MessageContext msgCtx3 = new MessageContext(); - msgCtx3.setCorrelationID("vasia3"); - msgCtx3.setType("response"); - coreManager.getProtocolCallback().onResponse("three1",msgCtx3); - - coreManager.getProtocolCallback().onResponse("three2", msgCtx3); - - coreManager.getProtocolCallback().onResponse("first1", msgCtx1); - Thread.sleep(250); - - coreManager.getProtocolCallback().onResponse("first2", msgCtx1); - Thread.sleep(10000); - } - - private class ListenerImpl implements ICoreAsyncResponseHandler{ - - public boolean onResponse(String message, String type) { - System.out.println("callback " + message); - return message != null; - } - - @Override - public void onException(Exception e) { - e.printStackTrace(); - } - } - - private class SleeepListenerImpl implements ICoreAsyncResponseHandler{ - - public boolean onResponse(String message, String type) { - try { - Thread.sleep(150); - System.out.println("sleep callback " + message); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return message != null; - } - - @Override - public void onException(Exception e) { - e.printStackTrace(); - } - } - - class CoreManagerTest extends CoreManager{ - CoreManagerTest(Properties properties) throws CoreException { - super(properties); - protocol = mock(AsyncProtocol.class); - } - protected void sendRequest2Protocol(String request, String corrId, String rpcName) throws CoreException { - } - - protected void initProtocol(Properties properties, RetrieveMessageCallback protocolCallback) throws ProtocolException { - - } - } -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/SyncFlowTest.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/SyncFlowTest.java deleted file mode 100644 index 2e69369b9..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/core/SyncFlowTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.core; - -import org.onap.appc.client.impl.core.CoreException; -import org.onap.appc.client.impl.core.CoreManager; -import org.onap.appc.client.impl.core.ICoreSyncResponseHandler; -import org.onap.appc.client.impl.core.MessageContext; -import org.onap.appc.client.impl.core.SyncRequestResponseHandler; -import org.onap.appc.client.impl.protocol.AsyncProtocol; -import org.onap.appc.client.impl.protocol.ProtocolException; -import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; -import org.junit.Assert; -import org.junit.Before; - -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.mock; - -public class SyncFlowTest { - CoreManager coreManager = null; - - public void initialize() throws CoreException { - Properties prop = new Properties(); - prop.setProperty("client.pool.size", "10"); - prop.setProperty("client.response.timeout", "7000"); - coreManager = new CoreManagerTest(prop); - } - - T syncRequest(String request, ICoreSyncResponseHandler businessCallback, String correlationId, String rpcName ) throws CoreException, TimeoutException { - SyncRequestResponseHandler requestResponseHandler = new SyncRequestResponseHandler(correlationId, businessCallback, coreManager); - requestResponseHandler.sendRequest(request, correlationId, rpcName); - T responseObject = (T) requestResponseHandler.getResponse(); - return responseObject; - } - - public void blockRequestTest(){ - ICoreSyncResponseHandler handler = new ICoreSyncResponseHandlerImpl1(); - try { - syncRequest("request 1", handler, "vasia1", "test"); - }catch (Throwable e){ - e.printStackTrace(); - Assert.assertTrue(e != null); - } - - } - - public void blockRequestSucceedTest() throws InterruptedException { - ExecutorService executorService = Executors.newFixedThreadPool(2); - final ICoreSyncResponseHandler handler = new ICoreSyncResponseHandlerImpl1(); - try { - executorService.submit(new Runnable() { - public void run() { - System.out.println("Send request"); - T response; - try { - response = syncRequest("request 1", handler, "vasia1", "test"); - System.out.println("=======" + response.toString()); - } catch (CoreException e) { - e.printStackTrace(); - } catch (TimeoutException e) { - e.printStackTrace(); - } - } - }); - }catch (Throwable e){ - Assert.assertTrue((RuntimeException)e != null); - } - Thread.sleep(2000); - executorService.submit(new Runnable() { - public void run() { - MessageContext ctx = new MessageContext(); - ctx.setCorrelationID("vasia1"); - ctx.setType("response"); - try { - System.out.println("Send response 1"); - coreManager.getProtocolCallback().onResponse("response for request 1", ctx); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - Thread.sleep(2000); - executorService.submit(new Runnable() { - public void run() { - MessageContext ctx = new MessageContext(); - ctx.setCorrelationID("vasia1"); - ctx.setType("response"); - try { - System.out.println("Send response 2"); - coreManager.getProtocolCallback().onResponse("response for request 1 final", ctx); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - Thread.sleep(1000); - - } - - class ICoreSyncResponseHandlerImpl1 implements ICoreSyncResponseHandler{ - - - public T onResponse(String message, String type) { - System.out.println("Received message = " + message) ; - if(message.contains("final")){ - return (T) new String(message); - } - return null; - } - } - - class CoreManagerTest extends CoreManager{ - CoreManagerTest(Properties properties) throws CoreException { - super(properties); - protocol = mock(AsyncProtocol.class); - } - protected void sendRequest2Protocol(String request, String corrId, String rpcName) throws CoreException { - } - - protected void initProtocol(Properties properties, RetrieveMessageCallback protocolCallback) throws ProtocolException{ - - } - } -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriterTest.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriterTest.java deleted file mode 100644 index 1d41a52f8..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/APPCMessageReaderWriterTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -import org.onap.appc.client.impl.protocol.APPCMessageReaderWriter; -import org.onap.appc.client.impl.protocol.ProtocolException; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.io.StringWriter; - -public class APPCMessageReaderWriterTest { - - private APPCMessageReaderWriter messageReaderWriter; - private ObjectMapper mapper; - - private static final String VERSION = "2.0"; - private static final String TYPE = "typeTest"; - private static final String CORRELATION_ID = "correlationIdTest"; - private static final String PARTITION = "partitionTest"; - private static final String RPC = "rpcTest"; - private static final String PAYLOAD = "{\"key1\":\"val1\",\"key2\":\"val2\",\"key3\":{\"key3.1\":\"val3.1\"}}"; - - @Before - public void init() throws IOException { - mapper = new ObjectMapper(); - messageReaderWriter = new APPCMessageReaderWriter(); - } - - @Test - public void writeTest() throws IOException, ProtocolException { - MessageContext context = new MessageContext(); - context.setType(TYPE); - context.setCorrelationID(CORRELATION_ID); - context.setPartiton(PARTITION); - context.setRpc(RPC); - String payload = PAYLOAD; - String message = messageReaderWriter.write(payload, context); - - JsonNode messageJson = mapper.readTree(message); - Assert.assertEquals(VERSION, messageJson.get("version").asText()); - Assert.assertEquals(context.getType(), messageJson.get("type").asText()); - Assert.assertEquals(context.getCorrelationID(), messageJson.get("correlation-id").asText()); - Assert.assertEquals(context.getPartiton(), messageJson.get("cambria.partition").asText()); - Assert.assertEquals(context.getRpc(), messageJson.get("rpc-name").asText()); - Assert.assertEquals(payload, messageJson.get("body").toString()); - } - - @Test - public void readTest() throws IOException, ProtocolException { - ObjectNode node = mapper.createObjectNode(); - node.put("version", VERSION); - node.put("type", TYPE); - node.put("correlation-id", CORRELATION_ID); - node.put("cambria.partition", PARTITION); - node.put("rpc-name", RPC); - JsonNode payload = mapper.valueToTree(PAYLOAD); - node.set("body", payload); - String message = node.toString(); - - MessageContext returnContext = new MessageContext(); - String returnPayload = messageReaderWriter.read(message, returnContext); - - Assert.assertEquals(TYPE, returnContext.getType()); - Assert.assertEquals(CORRELATION_ID, returnContext.getCorrelationID()); - Assert.assertEquals(PARTITION, returnContext.getPartiton()); - Assert.assertEquals(RPC, returnContext.getRpc()); - Assert.assertEquals(payload.toString(), returnPayload); - } - -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImpl.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImpl.java deleted file mode 100644 index ceba10b58..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImpl.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -import org.onap.appc.client.impl.protocol.AsyncProtocol; -import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; -import org.onap.appc.client.impl.protocol.ProtocolException; -import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; -import org.onap.appc.client.impl.protocol.UEBPropertiesKeys; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; - -public class TestAsyncProtocolImpl { - - private static AsyncProtocol protocol; - private static AtomicBoolean gotResponse; - private static Properties props; - - private static class TestCallback implements RetrieveMessageCallback{ - - public void onResponse(String payload, MessageContext context) { - Assert.assertNotEquals(null, payload); - Assert.assertNotEquals(null, context); - protocol = null; - gotResponse.set(true); - } - } - - @BeforeClass - public static void setUp() throws IOException, ProtocolException { - - gotResponse = new AtomicBoolean(false); - - props = new Properties(); - String propFileName = "ueb.properties"; - - InputStream input = TestAsyncProtocolImpl.class.getClassLoader().getResourceAsStream(propFileName); - - props.load(input); - - protocol = new AsyncProtocolImpl(); - protocol.init(props, new TestCallback()); - } - - public void testSendRequest() throws ProtocolException { - - MessageContext context = new MessageContext(); - context.setType("Test"); - - protocol.sendRequest("{\"Test\":\"\"}", context); - - try { - Long timeToSleep = Long.parseLong((String)props.get(UEBPropertiesKeys.TOPIC_READ_TIMEOUT))*2; - Thread.sleep(timeToSleep); - } catch (InterruptedException e) { - Assert.assertFalse(e.getMessage(), false); - } - if (gotResponse.get() == false) { - Assert.assertFalse("Message was not read !", true); - } - } -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java deleted file mode 100644 index 267282abd..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplMissingProps.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.onap.appc.client.impl.core.MessageContext; -import org.onap.appc.client.impl.protocol.AsyncProtocol; -import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; -import org.onap.appc.client.impl.protocol.RetrieveMessageCallback; -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class TestAsyncProtocolImplMissingProps { - - private static AsyncProtocol protocol; - - private static class TestCallback implements RetrieveMessageCallback { - - public void onResponse(String payload, MessageContext context) { - Assert.assertFalse("bad Callback !",false); - } - } - - @Test - /** - * protocol should throw illegal argument exception due to null properties - */ - public void testSetUpMissingProps() { - - Properties props = new Properties(); - String propFileName = "ueb.missing.properties"; - - InputStream input = TestAsyncProtocolImplMissingProps.class.getClassLoader().getResourceAsStream(propFileName); - - try { - props.load(input); - } catch (IOException e) { - Assert.assertFalse(e.getMessage(),false); - } - - protocol = new AsyncProtocolImpl(); - try { - protocol.init(props, new TestCallback()); - } catch (IllegalArgumentException e) { - Assert.assertTrue(true); - } catch (Exception e) { - Assert.assertFalse(e.getMessage(),false); - } - } -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java deleted file mode 100644 index 22954cd75..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestAsyncProtocolImplNullCallback.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.client.impl.protocol.AsyncProtocol; -import org.onap.appc.client.impl.protocol.AsyncProtocolImpl; -import org.onap.appc.client.impl.protocol.ProtocolException; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class TestAsyncProtocolImplNullCallback { - - private static AsyncProtocol protocol; - - public void testSetUpNoCallback() throws IOException { - - Properties props = new Properties(); - String propFileName = "ueb.properties"; - - InputStream input = TestAsyncProtocolImpl.class.getClassLoader().getResourceAsStream(propFileName); - - props.load(input); - - protocol = new AsyncProtocolImpl(); - - try { - protocol.init(props, null); - } catch (ProtocolException e) { - Assert.assertTrue(true); - } catch (Exception e){ - Assert.assertFalse(e.getMessage(),false); - } - } -} diff --git a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestUEBMessagingService.java b/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestUEBMessagingService.java deleted file mode 100644 index de192ab12..000000000 --- a/appc-client/client-lib/src/test/java/org/openecomp/appc/client/impl/protocol/TestUEBMessagingService.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.client.impl.protocol; - -import org.junit.*; -import org.junit.runners.MethodSorters; -import org.onap.appc.client.impl.protocol.MessagingService; -import org.onap.appc.client.impl.protocol.UEBMessagingService; - -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Properties; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestUEBMessagingService { - - private static MessagingService ueb; - - public static void setUp() throws IOException, GeneralSecurityException, NoSuchFieldException, IllegalAccessException { - - Properties props = new Properties(); - String propFileName = "ueb.properties"; - - InputStream input = TestUEBMessagingService.class.getClassLoader().getResourceAsStream(propFileName); - - props.load(input); - - ueb = new UEBMessagingService(); - ueb.init(props); - } - - public void test1Send() throws IOException { - System.out.println("Here"); - - String message = "Test Message Service"; - ueb.send(null,message); - } - - public void test2Fetch() throws IOException { - - System.out.println("Here2"); - List messages = ueb.fetch(1); - Assert.assertEquals(1,messages.size()); - } - -} diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/RequestHandler.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/RequestHandler.java new file mode 100644 index 000000000..293b72f89 --- /dev/null +++ b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/RequestHandler.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.simulator.client; + +import java.io.File; +import java.io.IOException; + +public interface RequestHandler { + void proceedFile(File source, File log) throws IOException, ClassNotFoundException, NoSuchMethodException; + void shutdown(boolean isForceShutdown); +} diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/ResponseHandler.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/ResponseHandler.java new file mode 100644 index 000000000..5a24028e8 --- /dev/null +++ b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/ResponseHandler.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.simulator.client; + +import java.io.File; + +public interface ResponseHandler { + void validateResponse(File output); +} diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java new file mode 100644 index 000000000..243136d0e --- /dev/null +++ b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java @@ -0,0 +1,275 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.simulator.client.impl; + +import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider; +import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; +import org.onap.appc.client.lcm.api.ApplicationContext; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.api.ResponseHandler; + +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.onap.appc.simulator.client.RequestHandler; + +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.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Properties; + +public class JsonRequestHandler implements RequestHandler { + + private enum modeT { + SYNCH, + ASYNCH + } + + public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private String rpcName = null; + private String inputClassName = null; + private String actionName = null; + private String methodName = null; + String packageName = null; + private LifeCycleManagerStateful service = null; + private Properties properties; + HashMap exceptRpcMap = null; + private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonRequestHandler.class); + private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null; + + + public JsonRequestHandler(Properties prop) throws AppcClientException { + properties = prop; + packageName = properties.getProperty("ctx.model.package") + "."; + try { + service = createService(); + } catch (AppcClientException e) { + e.printStackTrace(); + } + exceptRpcMap = prepareExceptionsMap(); + } + + public JsonRequestHandler(){ + + } + + private HashMap prepareExceptionsMap() { + exceptRpcMap = new HashMap<>(); + + try (BufferedReader reader = new BufferedReader( + new FileReader(properties.getProperty( + "client.rpc.exceptions.map.file")))) { + String line; + while ((line = reader.readLine()) != null) { + String[] parts = line.split(":", 2); + if (parts.length >= 2) { + String key = parts[0]; + String value = parts[1]; + exceptRpcMap.put(key, value); + } else { + System.out.println("ignoring line: " + line); + } + } + } catch (FileNotFoundException e) { + return exceptRpcMap; + } catch (IOException e) { + e.printStackTrace(); + } + + return exceptRpcMap; + } + + @Override + public void proceedFile(File source, File log) throws IOException { + final JsonNode inputNode = OBJECT_MAPPER.readTree(source); + + try { + // proceed with inputNode and get some xxxInput object, depends on action + prepareNames(inputNode); + + Object input = prepareObject(inputNode); + + JsonResponseHandler response = new JsonResponseHandler(); + response.setFile(source.getPath().toString()); + switch (isSyncMode(inputNode)) { + case SYNCH: { + LOG.debug("Received input request will be processed in synchronously mode"); + Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass()); + response.onResponse(rpc.invoke(service, input)); + break; + } + case ASYNCH: { + LOG.debug("Received input request will be processed in asynchronously mode"); + Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class); + rpc.invoke(service, input, response); + break; + } + default: { + throw new RuntimeException("Unrecognized request mode"); + } + } + } + catch(Exception ex){ + //ex.printStackTrace(); + } + + LOG.debug("Action <" + actionName + "> from input file <" + source.getPath().toString() + "> processed"); + } + + private modeT isSyncMode(JsonNode inputNode) { + // The following solution is for testing purposes only + // the sync/async decision logic may change upon request + try { + int mode = Integer.parseInt(inputNode.findValue("input").findValue("common-header").findValue("sub-request-id").asText()); + if ((mode % 2) == 0) { + return modeT.SYNCH; + } + }catch (Exception ex) { + //use ASYNC as default, if value is not integer. + } + return modeT.ASYNCH; + } + + private LifeCycleManagerStateful createService() throws AppcClientException { + appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class); + return appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(new ApplicationContext(), properties); + } + + public void shutdown(boolean isForceShutdown){ + appcLifeCycleManagerServiceFactory.shutdownLifeCycleManager(isForceShutdown); + } + + public Object prepareObject(JsonNode input) { + try { + Class cls = Class.forName(inputClassName); + try { + // since payload is not mandatory field and not all actions contains payload + // so we have to check that during input parsing + alignPayload(input); + } catch (NoSuchFieldException e) { + LOG.debug("In " + actionName + " no payload defined"); + } + + return OBJECT_MAPPER.treeToValue(input.get("input"), cls); + } + catch(Exception ex){ + //ex.printStackTrace(); + } + return null; + } + + private void prepareNames(JsonNode input) throws NoSuchFieldException { + JsonNode inputNode = input.findValue("input"); + actionName = inputNode.findValue("action").asText(); + if (actionName.isEmpty()) { + throw new NoSuchFieldException("Input doesn't contains field "); + } + + rpcName = prepareRpcFromAction(actionName); + inputClassName = packageName + actionName + "Input"; + methodName = prepareMethodName(rpcName); + } + + private void alignPayload(JsonNode input) throws NoSuchFieldException { + JsonNode inputNode = input.findValue("input"); + JsonNode payload = inputNode.findValue("payload"); + if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty()) + throw new NoSuchFieldException("Input doesn't contains field "); + + String payloadData = payload.asText(); + if (payloadData.isEmpty()) + payloadData = payload.toString(); + ((ObjectNode)inputNode).put("payload", payloadData); + } + + private String prepareRpcFromAction(String action) { + String rpc = checkExceptionalRpcList(action); + if (rpc!= null && !rpc.isEmpty()) { + return rpc; // we found exceptional rpc, so no need to format it + } + + rpc = ""; + boolean makeItLowerCase = true; + for(int i = 0; i < action.length(); i++) + { + if(makeItLowerCase) // first character will make lower case + { + rpc+=Character.toLowerCase(action.charAt(i)); + makeItLowerCase = false; + } + else if((i+1 < action.length()) && Character.isUpperCase(action.charAt(i+1))) + { + rpc+=action.charAt(i) + "-"; + makeItLowerCase = true; + } + else + { + rpc+=action.charAt(i); + makeItLowerCase = false; + } + } + return rpc; + } + + private String checkExceptionalRpcList(String action) { + if (exceptRpcMap.isEmpty()) { + return null; + } + return exceptRpcMap.get(action); + } + + private String prepareMethodName(String inputRpcName) { + boolean makeItUpperCase = false; + String method = ""; + + for(int i = 0; i < inputRpcName.length(); i++) //to check the characters of string.. + { + if(Character.isLowerCase(inputRpcName.charAt(i)) && makeItUpperCase) // skip first character if it lower case + { + method+=Character.toUpperCase(inputRpcName.charAt(i)); + makeItUpperCase = false; + } + else if(inputRpcName.charAt(i) == '-') + { + makeItUpperCase = true; + } + else + { + method+=inputRpcName.charAt(i); + makeItUpperCase = false; + } + } + return method; + } + +} diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonResponseHandler.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonResponseHandler.java new file mode 100644 index 000000000..c19abb2fb --- /dev/null +++ b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonResponseHandler.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.simulator.client.impl; + +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.FileWriter; +import java.util.concurrent.atomic.AtomicInteger; + +public class JsonResponseHandler implements ResponseHandler { + + public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonResponseHandler.class); + + private String fileName = "default"; + private static final int ACCEPT_FAMILY = 1; + private static final int SUCCESS_FAMILY = 4; + private static final int INTERMEDIATE_MESSAGES =5; + + private AtomicInteger messageCount =new AtomicInteger(1); + + public void setFile(String name) { + fileName = name; + } + + @Override + public void onResponse(Object response) { + + String output = null; + try { + output = OBJECT_MAPPER.writeValueAsString(response); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + LOG.debug("Received response : " + output); + + int errorCode = 0; + boolean isFinal = true; + try { + JsonNode code= OBJECT_MAPPER.readTree(output).findValue("status").findValue("code"); + if (code == null) + { + LOG.error("Status code doesn't exist. Malformed response : " + output); + flushToErrorFile(output, isFinal); + return; + } + errorCode = code.asInt(); + errorCode = errorCode / 100; + switch (errorCode) { + case ACCEPT_FAMILY: + isFinal = false; // for ACCEPT that it is not a final response + break; + case INTERMEDIATE_MESSAGES: + isFinal = false; // for 5xx series messages are not a final response + break; + default: + break; + } + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + switch (errorCode) { + case ACCEPT_FAMILY: { + try { + System.out.println("== THR#" + Thread.currentThread().getId() + " Got ACCEPT on ReqID <" + + OBJECT_MAPPER.readTree(output).findValue("common-header").findValue("request-id").asText() + ">"); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + // no need to report ACCEPT into output file + break; + } + case SUCCESS_FAMILY: + flushToOutputFile(output, isFinal); + break; + case INTERMEDIATE_MESSAGES: + flushToMessageFile(output, isFinal); + break; + default: + flushToErrorFile(output, isFinal); + } + } + + @Override + public void onException(AppcClientException exception) { + flushToErrorFile("exception: " + exception, true); + } + + private void flushToOutputFile(String output, boolean isFinal) { + this.flushToFile(output, ".output", isFinal); + } + private void flushToMessageFile(String output, boolean isFinal) { + this.flushToFile(output, ".message" + messageCount.getAndIncrement(), isFinal); + + } + + private void flushToErrorFile(String output, boolean isFinal) { + this.flushToFile(output, ".error", isFinal); + } + + private void flushToFile(String output, String suffix, boolean isFinal) { + try (FileWriter fileWriter = new FileWriter(fileName + suffix);){ + LOG.info("Output file : " + fileName + suffix); + + fileWriter.write(output); + fileWriter.flush(); + if (isFinal){ + fileWriter.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("== THR#" +Thread.currentThread().getId()+ " Output file : " + fileName + suffix); + } +} diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/main/ClientRunner.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/main/ClientRunner.java new file mode 100644 index 000000000..c8da17e79 --- /dev/null +++ b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/main/ClientRunner.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.simulator.client.main; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.onap.appc.simulator.client.RequestHandler; +import org.onap.appc.simulator.client.impl.JsonRequestHandler; + +import java.io.*; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +public class ClientRunner { + + public static void main(String ... args) throws Exception { + String folder = args[0]; + if (folder == null) { + folder = System.getProperty("user.dir"); + } + System.out.println("== THR#" +Thread.currentThread().getId()+ " Reading files under the folder : " + folder); + + String inputType = args[1]; + if (inputType != null && !inputType.matches("JSON")) { + throw new RuntimeException("### ERROR ### - Unsupported file type <" + inputType + "> was provided"); + } + + Properties properties = getProperties(folder); + RequestHandler reqHandler = new JsonRequestHandler(properties); + List sources = getJsonFiles(folder); + File log = new File(folder + "/output.txt"); + int filesNum = 0; + for (File source: sources) { + reqHandler.proceedFile(source, log); + System.out.println("== THR#" +Thread.currentThread().getId()+ " File <" + source.getName() + "> processed."); + ++filesNum; + } + System.out.println("DONE with " + filesNum + " files under the folder : " + folder); + Thread.sleep(30); + System.out.println("Shutdown ..."); + reqHandler.shutdown(Boolean.parseBoolean(properties.getProperty("client.force.shutdown"))); +// System.exit(0); + } + + private static Properties getProperties(String folder) { + Properties prop = new Properties(); + + InputStream conf = null; + try { + conf = new FileInputStream(folder + "client-simulator.properties"); + } catch (FileNotFoundException e) { + + } + if (conf != null) { + try { + prop.load(conf); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); + } catch (Exception e) { + throw new RuntimeException("### ERROR ### - Could not load properties to test"); + } + } + return prop; + } + + private static List getJsonFiles(String folder) throws FileNotFoundException { + Path dir = Paths.get(folder); + FileFilter fileFilter = new WildcardFileFilter("*.json"); + return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); + } +} diff --git a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/RequestHandler.java b/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/RequestHandler.java deleted file mode 100644 index 293b72f89..000000000 --- a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/RequestHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.simulator.client; - -import java.io.File; -import java.io.IOException; - -public interface RequestHandler { - void proceedFile(File source, File log) throws IOException, ClassNotFoundException, NoSuchMethodException; - void shutdown(boolean isForceShutdown); -} diff --git a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/ResponseHandler.java b/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/ResponseHandler.java deleted file mode 100644 index 5a24028e8..000000000 --- a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/ResponseHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.simulator.client; - -import java.io.File; - -public interface ResponseHandler { - void validateResponse(File output); -} diff --git a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonRequestHandler.java b/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonRequestHandler.java deleted file mode 100644 index 243136d0e..000000000 --- a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonRequestHandler.java +++ /dev/null @@ -1,275 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.simulator.client.impl; - -import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider; -import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; -import org.onap.appc.client.lcm.api.ApplicationContext; -import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; -import org.onap.appc.client.lcm.api.ResponseHandler; - -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import org.onap.appc.simulator.client.RequestHandler; - -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.fasterxml.jackson.databind.node.ObjectNode; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Properties; - -public class JsonRequestHandler implements RequestHandler { - - private enum modeT { - SYNCH, - ASYNCH - } - - public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private String rpcName = null; - private String inputClassName = null; - private String actionName = null; - private String methodName = null; - String packageName = null; - private LifeCycleManagerStateful service = null; - private Properties properties; - HashMap exceptRpcMap = null; - private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonRequestHandler.class); - private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null; - - - public JsonRequestHandler(Properties prop) throws AppcClientException { - properties = prop; - packageName = properties.getProperty("ctx.model.package") + "."; - try { - service = createService(); - } catch (AppcClientException e) { - e.printStackTrace(); - } - exceptRpcMap = prepareExceptionsMap(); - } - - public JsonRequestHandler(){ - - } - - private HashMap prepareExceptionsMap() { - exceptRpcMap = new HashMap<>(); - - try (BufferedReader reader = new BufferedReader( - new FileReader(properties.getProperty( - "client.rpc.exceptions.map.file")))) { - String line; - while ((line = reader.readLine()) != null) { - String[] parts = line.split(":", 2); - if (parts.length >= 2) { - String key = parts[0]; - String value = parts[1]; - exceptRpcMap.put(key, value); - } else { - System.out.println("ignoring line: " + line); - } - } - } catch (FileNotFoundException e) { - return exceptRpcMap; - } catch (IOException e) { - e.printStackTrace(); - } - - return exceptRpcMap; - } - - @Override - public void proceedFile(File source, File log) throws IOException { - final JsonNode inputNode = OBJECT_MAPPER.readTree(source); - - try { - // proceed with inputNode and get some xxxInput object, depends on action - prepareNames(inputNode); - - Object input = prepareObject(inputNode); - - JsonResponseHandler response = new JsonResponseHandler(); - response.setFile(source.getPath().toString()); - switch (isSyncMode(inputNode)) { - case SYNCH: { - LOG.debug("Received input request will be processed in synchronously mode"); - Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass()); - response.onResponse(rpc.invoke(service, input)); - break; - } - case ASYNCH: { - LOG.debug("Received input request will be processed in asynchronously mode"); - Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class); - rpc.invoke(service, input, response); - break; - } - default: { - throw new RuntimeException("Unrecognized request mode"); - } - } - } - catch(Exception ex){ - //ex.printStackTrace(); - } - - LOG.debug("Action <" + actionName + "> from input file <" + source.getPath().toString() + "> processed"); - } - - private modeT isSyncMode(JsonNode inputNode) { - // The following solution is for testing purposes only - // the sync/async decision logic may change upon request - try { - int mode = Integer.parseInt(inputNode.findValue("input").findValue("common-header").findValue("sub-request-id").asText()); - if ((mode % 2) == 0) { - return modeT.SYNCH; - } - }catch (Exception ex) { - //use ASYNC as default, if value is not integer. - } - return modeT.ASYNCH; - } - - private LifeCycleManagerStateful createService() throws AppcClientException { - appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class); - return appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(new ApplicationContext(), properties); - } - - public void shutdown(boolean isForceShutdown){ - appcLifeCycleManagerServiceFactory.shutdownLifeCycleManager(isForceShutdown); - } - - public Object prepareObject(JsonNode input) { - try { - Class cls = Class.forName(inputClassName); - try { - // since payload is not mandatory field and not all actions contains payload - // so we have to check that during input parsing - alignPayload(input); - } catch (NoSuchFieldException e) { - LOG.debug("In " + actionName + " no payload defined"); - } - - return OBJECT_MAPPER.treeToValue(input.get("input"), cls); - } - catch(Exception ex){ - //ex.printStackTrace(); - } - return null; - } - - private void prepareNames(JsonNode input) throws NoSuchFieldException { - JsonNode inputNode = input.findValue("input"); - actionName = inputNode.findValue("action").asText(); - if (actionName.isEmpty()) { - throw new NoSuchFieldException("Input doesn't contains field "); - } - - rpcName = prepareRpcFromAction(actionName); - inputClassName = packageName + actionName + "Input"; - methodName = prepareMethodName(rpcName); - } - - private void alignPayload(JsonNode input) throws NoSuchFieldException { - JsonNode inputNode = input.findValue("input"); - JsonNode payload = inputNode.findValue("payload"); - if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty()) - throw new NoSuchFieldException("Input doesn't contains field "); - - String payloadData = payload.asText(); - if (payloadData.isEmpty()) - payloadData = payload.toString(); - ((ObjectNode)inputNode).put("payload", payloadData); - } - - private String prepareRpcFromAction(String action) { - String rpc = checkExceptionalRpcList(action); - if (rpc!= null && !rpc.isEmpty()) { - return rpc; // we found exceptional rpc, so no need to format it - } - - rpc = ""; - boolean makeItLowerCase = true; - for(int i = 0; i < action.length(); i++) - { - if(makeItLowerCase) // first character will make lower case - { - rpc+=Character.toLowerCase(action.charAt(i)); - makeItLowerCase = false; - } - else if((i+1 < action.length()) && Character.isUpperCase(action.charAt(i+1))) - { - rpc+=action.charAt(i) + "-"; - makeItLowerCase = true; - } - else - { - rpc+=action.charAt(i); - makeItLowerCase = false; - } - } - return rpc; - } - - private String checkExceptionalRpcList(String action) { - if (exceptRpcMap.isEmpty()) { - return null; - } - return exceptRpcMap.get(action); - } - - private String prepareMethodName(String inputRpcName) { - boolean makeItUpperCase = false; - String method = ""; - - for(int i = 0; i < inputRpcName.length(); i++) //to check the characters of string.. - { - if(Character.isLowerCase(inputRpcName.charAt(i)) && makeItUpperCase) // skip first character if it lower case - { - method+=Character.toUpperCase(inputRpcName.charAt(i)); - makeItUpperCase = false; - } - else if(inputRpcName.charAt(i) == '-') - { - makeItUpperCase = true; - } - else - { - method+=inputRpcName.charAt(i); - makeItUpperCase = false; - } - } - return method; - } - -} diff --git a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonResponseHandler.java b/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonResponseHandler.java deleted file mode 100644 index c19abb2fb..000000000 --- a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/impl/JsonResponseHandler.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.simulator.client.impl; - -import org.onap.appc.client.lcm.api.ResponseHandler; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.FileWriter; -import java.util.concurrent.atomic.AtomicInteger; - -public class JsonResponseHandler implements ResponseHandler { - - public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonResponseHandler.class); - - private String fileName = "default"; - private static final int ACCEPT_FAMILY = 1; - private static final int SUCCESS_FAMILY = 4; - private static final int INTERMEDIATE_MESSAGES =5; - - private AtomicInteger messageCount =new AtomicInteger(1); - - public void setFile(String name) { - fileName = name; - } - - @Override - public void onResponse(Object response) { - - String output = null; - try { - output = OBJECT_MAPPER.writeValueAsString(response); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - LOG.debug("Received response : " + output); - - int errorCode = 0; - boolean isFinal = true; - try { - JsonNode code= OBJECT_MAPPER.readTree(output).findValue("status").findValue("code"); - if (code == null) - { - LOG.error("Status code doesn't exist. Malformed response : " + output); - flushToErrorFile(output, isFinal); - return; - } - errorCode = code.asInt(); - errorCode = errorCode / 100; - switch (errorCode) { - case ACCEPT_FAMILY: - isFinal = false; // for ACCEPT that it is not a final response - break; - case INTERMEDIATE_MESSAGES: - isFinal = false; // for 5xx series messages are not a final response - break; - default: - break; - } - - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - - switch (errorCode) { - case ACCEPT_FAMILY: { - try { - System.out.println("== THR#" + Thread.currentThread().getId() + " Got ACCEPT on ReqID <" + - OBJECT_MAPPER.readTree(output).findValue("common-header").findValue("request-id").asText() + ">"); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - // no need to report ACCEPT into output file - break; - } - case SUCCESS_FAMILY: - flushToOutputFile(output, isFinal); - break; - case INTERMEDIATE_MESSAGES: - flushToMessageFile(output, isFinal); - break; - default: - flushToErrorFile(output, isFinal); - } - } - - @Override - public void onException(AppcClientException exception) { - flushToErrorFile("exception: " + exception, true); - } - - private void flushToOutputFile(String output, boolean isFinal) { - this.flushToFile(output, ".output", isFinal); - } - private void flushToMessageFile(String output, boolean isFinal) { - this.flushToFile(output, ".message" + messageCount.getAndIncrement(), isFinal); - - } - - private void flushToErrorFile(String output, boolean isFinal) { - this.flushToFile(output, ".error", isFinal); - } - - private void flushToFile(String output, String suffix, boolean isFinal) { - try (FileWriter fileWriter = new FileWriter(fileName + suffix);){ - LOG.info("Output file : " + fileName + suffix); - - fileWriter.write(output); - fileWriter.flush(); - if (isFinal){ - fileWriter.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("== THR#" +Thread.currentThread().getId()+ " Output file : " + fileName + suffix); - } -} diff --git a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/main/ClientRunner.java b/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/main/ClientRunner.java deleted file mode 100644 index c8da17e79..000000000 --- a/appc-client/client-simulator/src/main/java/org/openecomp/appc/simulator/client/main/ClientRunner.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.simulator.client.main; - -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.onap.appc.simulator.client.RequestHandler; -import org.onap.appc.simulator.client.impl.JsonRequestHandler; - -import java.io.*; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -public class ClientRunner { - - public static void main(String ... args) throws Exception { - String folder = args[0]; - if (folder == null) { - folder = System.getProperty("user.dir"); - } - System.out.println("== THR#" +Thread.currentThread().getId()+ " Reading files under the folder : " + folder); - - String inputType = args[1]; - if (inputType != null && !inputType.matches("JSON")) { - throw new RuntimeException("### ERROR ### - Unsupported file type <" + inputType + "> was provided"); - } - - Properties properties = getProperties(folder); - RequestHandler reqHandler = new JsonRequestHandler(properties); - List sources = getJsonFiles(folder); - File log = new File(folder + "/output.txt"); - int filesNum = 0; - for (File source: sources) { - reqHandler.proceedFile(source, log); - System.out.println("== THR#" +Thread.currentThread().getId()+ " File <" + source.getName() + "> processed."); - ++filesNum; - } - System.out.println("DONE with " + filesNum + " files under the folder : " + folder); - Thread.sleep(30); - System.out.println("Shutdown ..."); - reqHandler.shutdown(Boolean.parseBoolean(properties.getProperty("client.force.shutdown"))); -// System.exit(0); - } - - private static Properties getProperties(String folder) { - Properties prop = new Properties(); - - InputStream conf = null; - try { - conf = new FileInputStream(folder + "client-simulator.properties"); - } catch (FileNotFoundException e) { - - } - if (conf != null) { - try { - prop.load(conf); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); - } catch (Exception e) { - throw new RuntimeException("### ERROR ### - Could not load properties to test"); - } - } - return prop; - } - - private static List getJsonFiles(String folder) throws FileNotFoundException { - Path dir = Paths.get(folder); - FileFilter fileFilter = new WildcardFileFilter("*.json"); - return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); - } -} diff --git a/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonRequestHandler.java b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonRequestHandler.java new file mode 100644 index 000000000..ba3696f26 --- /dev/null +++ b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonRequestHandler.java @@ -0,0 +1,53 @@ +package org.onap.appc.simulator.client.impl; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.*; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({LifeCycleManagerStateful.class}) + +public class TestJsonRequestHandler { + + JsonResponseHandler jsonResponseHandler=new JsonResponseHandler(); + @Before + public void init(){ + jsonResponseHandler= Mockito.mock(JsonResponseHandler.class); + } + + + @Test + public void testProceedFiles() throws AppcClientException,java.io.IOException{ + String folder="src/test/resources/data"; + List sources = getJsonFiles(folder); + File source=sources.get(0); + File log = new File(folder + "/output.txt"); + JsonRequestHandler requestHandler = new JsonRequestHandler(); + Mockito.doNothing().when(jsonResponseHandler).onResponse(Matchers.anyBoolean()); + requestHandler.proceedFile(source,log); + + Assert.assertNotNull(log); + + } + + private static List getJsonFiles(String folder) throws FileNotFoundException { + Path dir = Paths.get(folder); + FileFilter fileFilter = new WildcardFileFilter("*.json"); + return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); + } + + +} \ No newline at end of file diff --git a/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonResponseHandler.java b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonResponseHandler.java new file mode 100644 index 000000000..59ffe1b31 --- /dev/null +++ b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/impl/TestJsonResponseHandler.java @@ -0,0 +1,46 @@ +package org.onap.appc.simulator.client.impl; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.junit.Assert; +import org.junit.Ignore; +import java.io.*; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + +public class TestJsonResponseHandler { + String folder="/data/output/error.json"; + JsonResponseHandler responseHandler=new JsonResponseHandler(); + + @Ignore + public void testOnResponse() throws URISyntaxException, IOException{ + responseHandler.onResponse(getNode()); + List files=getJsonFiles(folder); + Assert.assertNotNull(files); + + } + + private String readData(String inputFile) throws URISyntaxException, IOException { + File file = new File(this.getClass().getResource(inputFile).toURI()); + + byte[] bFile = new byte[(int) file.length()]; + FileInputStream fileInputStream = new FileInputStream(file); + fileInputStream.read(bFile); + fileInputStream.close(); + return new String(bFile); + } + + private String getNode() throws java.io.IOException{ + String jsonSring="{\"status\": {\"code\": \"200\"}}"; + return jsonSring; +} + public List getJsonFiles(String folder) throws FileNotFoundException { + Path dir = Paths.get(folder); + FileFilter fileFilter = new WildcardFileFilter("*.error"); + return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); + } +} diff --git a/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/main/TestClientRunner.java b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/main/TestClientRunner.java new file mode 100644 index 000000000..db648f957 --- /dev/null +++ b/appc-client/client-simulator/src/test/java/org/onap/appc/simulator/client/main/TestClientRunner.java @@ -0,0 +1,102 @@ +package org.onap.appc.simulator.client.main; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.onap.appc.simulator.client.impl.JsonRequestHandler; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.*; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JsonRequestHandler.class,ClientRunner.class}) + +public class TestClientRunner { + + JsonRequestHandler jsonRequestHandler; + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + @Before + public void init() throws AppcClientException{ + System.setOut(new PrintStream(outContent)); + jsonRequestHandler= Mockito.mock(JsonRequestHandler.class); + + } + + @After + public void cleanUpStreams() { + System.setOut(null); + } + + @Test + public void testMain() throws java.io.IOException,java.lang.Exception{ + String []arguments=new String[]{"src/test/resources/data","JSON"}; + PowerMockito.whenNew(JsonRequestHandler.class).withArguments(Mockito.anyObject()).thenReturn(jsonRequestHandler); + Mockito.doNothing().when(jsonRequestHandler).proceedFile(Matchers.anyObject(), Matchers.anyObject()); + + ClientRunner.main(arguments); + String expectedOutput=outContent.toString(); + Assert.assertEquals(expectedOutput,outContent.toString()); + } + + @Test + public void testGetPrperties(){ + String folder="src/test/resources/data"; + Properties properties=new Properties(); + properties=getProperties(folder); + Assert.assertNotNull(properties); + } + + @Test + public void testGetJsonFIles() throws FileNotFoundException{ + String folder="src/test/resources/data"; + List sources = getJsonFiles(folder); + Assert.assertNotNull(sources); + } + + private static Properties getProperties(String folder) { + Properties prop = new Properties(); + + InputStream conf = null; + try { + conf = new FileInputStream(folder + "client-simulator.properties"); + } catch (FileNotFoundException e) { + + } + if (conf != null) { + try { + prop.load(conf); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); + } catch (Exception e) { + throw new RuntimeException("### ERROR ### - Could not load properties to test"); + } + } + return prop; + } + + private static List getJsonFiles(String folder) throws FileNotFoundException { + Path dir = Paths.get(folder); + FileFilter fileFilter = new WildcardFileFilter("*.json"); + return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); + } + +} diff --git a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonRequestHandler.java b/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonRequestHandler.java deleted file mode 100644 index ba3696f26..000000000 --- a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonRequestHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.onap.appc.simulator.client.impl; - -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.*; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({LifeCycleManagerStateful.class}) - -public class TestJsonRequestHandler { - - JsonResponseHandler jsonResponseHandler=new JsonResponseHandler(); - @Before - public void init(){ - jsonResponseHandler= Mockito.mock(JsonResponseHandler.class); - } - - - @Test - public void testProceedFiles() throws AppcClientException,java.io.IOException{ - String folder="src/test/resources/data"; - List sources = getJsonFiles(folder); - File source=sources.get(0); - File log = new File(folder + "/output.txt"); - JsonRequestHandler requestHandler = new JsonRequestHandler(); - Mockito.doNothing().when(jsonResponseHandler).onResponse(Matchers.anyBoolean()); - requestHandler.proceedFile(source,log); - - Assert.assertNotNull(log); - - } - - private static List getJsonFiles(String folder) throws FileNotFoundException { - Path dir = Paths.get(folder); - FileFilter fileFilter = new WildcardFileFilter("*.json"); - return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); - } - - -} \ No newline at end of file diff --git a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonResponseHandler.java b/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonResponseHandler.java deleted file mode 100644 index 59ffe1b31..000000000 --- a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/impl/TestJsonResponseHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.onap.appc.simulator.client.impl; - -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.junit.Assert; -import org.junit.Ignore; -import java.io.*; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -public class TestJsonResponseHandler { - String folder="/data/output/error.json"; - JsonResponseHandler responseHandler=new JsonResponseHandler(); - - @Ignore - public void testOnResponse() throws URISyntaxException, IOException{ - responseHandler.onResponse(getNode()); - List files=getJsonFiles(folder); - Assert.assertNotNull(files); - - } - - private String readData(String inputFile) throws URISyntaxException, IOException { - File file = new File(this.getClass().getResource(inputFile).toURI()); - - byte[] bFile = new byte[(int) file.length()]; - FileInputStream fileInputStream = new FileInputStream(file); - fileInputStream.read(bFile); - fileInputStream.close(); - return new String(bFile); - } - - private String getNode() throws java.io.IOException{ - String jsonSring="{\"status\": {\"code\": \"200\"}}"; - return jsonSring; -} - public List getJsonFiles(String folder) throws FileNotFoundException { - Path dir = Paths.get(folder); - FileFilter fileFilter = new WildcardFileFilter("*.error"); - return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); - } -} diff --git a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/main/TestClientRunner.java b/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/main/TestClientRunner.java deleted file mode 100644 index db648f957..000000000 --- a/appc-client/client-simulator/src/test/java/org/openecomp/appc/simulator/client/main/TestClientRunner.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.onap.appc.simulator.client.main; - -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.client.lcm.exceptions.AppcClientException; -import org.onap.appc.simulator.client.impl.JsonRequestHandler; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.*; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({JsonRequestHandler.class,ClientRunner.class}) - -public class TestClientRunner { - - JsonRequestHandler jsonRequestHandler; - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - - @Before - public void init() throws AppcClientException{ - System.setOut(new PrintStream(outContent)); - jsonRequestHandler= Mockito.mock(JsonRequestHandler.class); - - } - - @After - public void cleanUpStreams() { - System.setOut(null); - } - - @Test - public void testMain() throws java.io.IOException,java.lang.Exception{ - String []arguments=new String[]{"src/test/resources/data","JSON"}; - PowerMockito.whenNew(JsonRequestHandler.class).withArguments(Mockito.anyObject()).thenReturn(jsonRequestHandler); - Mockito.doNothing().when(jsonRequestHandler).proceedFile(Matchers.anyObject(), Matchers.anyObject()); - - ClientRunner.main(arguments); - String expectedOutput=outContent.toString(); - Assert.assertEquals(expectedOutput,outContent.toString()); - } - - @Test - public void testGetPrperties(){ - String folder="src/test/resources/data"; - Properties properties=new Properties(); - properties=getProperties(folder); - Assert.assertNotNull(properties); - } - - @Test - public void testGetJsonFIles() throws FileNotFoundException{ - String folder="src/test/resources/data"; - List sources = getJsonFiles(folder); - Assert.assertNotNull(sources); - } - - private static Properties getProperties(String folder) { - Properties prop = new Properties(); - - InputStream conf = null; - try { - conf = new FileInputStream(folder + "client-simulator.properties"); - } catch (FileNotFoundException e) { - - } - if (conf != null) { - try { - prop.load(conf); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("client-simulator.properties")); - } catch (Exception e) { - throw new RuntimeException("### ERROR ### - Could not load properties to test"); - } - } - return prop; - } - - private static List getJsonFiles(String folder) throws FileNotFoundException { - Path dir = Paths.get(folder); - FileFilter fileFilter = new WildcardFileFilter("*.json"); - return new ArrayList(Arrays.asList(dir.toFile().listFiles(fileFilter))); - } - -} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/CLI.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/CLI.java new file mode 100644 index 000000000..e28b3706a --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/CLI.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.api; + +import org.onap.appc.tools.generator.impl.ModelGenerator; + +public class CLI { + public static void main(String... args) throws Exception { + String sourceFile = args[0]; + if(sourceFile == null) + throw new IllegalArgumentException("Source file is missing. Please add argument 'client '"); + + String destinationFile = args[1]; + if(destinationFile == null) + throw new IllegalArgumentException("Destination file name is missing. Please add argument 'client " + + sourceFile + + " '"); + + String templateFile = args[2]; + if(templateFile == null) + throw new IllegalArgumentException("template file name is missing. Please add argument 'client " + + sourceFile + + " "+destinationFile + + " '"); + + String builderName = args[3]; + if(builderName == null) + throw new IllegalArgumentException("builder FQDN is missing. Please add argument 'client " + + sourceFile + + " "+destinationFile + + " "+templateFile + + " '"); + String contextConfName = args[4]; + if(contextConfName == null) + throw new IllegalArgumentException("context conf file is missing. Please add argument 'client " + + sourceFile + + " "+destinationFile + + " "+templateFile + + " "+builderName + + " '"); + ModelGenerator generator = new ModelGenerator(); + generator.execute(sourceFile, destinationFile, templateFile, builderName, contextConfName); + } +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/ContextBuilder.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/ContextBuilder.java new file mode 100644 index 000000000..a1826f270 --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/ContextBuilder.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.api; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + +public interface ContextBuilder { + + Map buildContext(String sourceFile, String contextConf) throws IOException; +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/MavenPlugin.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/MavenPlugin.java new file mode 100644 index 000000000..9e160eed2 --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/api/MavenPlugin.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.api; + +import org.onap.appc.tools.generator.impl.ModelGenerator; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; + +import java.io.IOException; +import java.nio.file.Paths; + +@Mojo( + name = "generate", + defaultPhase = LifecyclePhase.GENERATE_SOURCES +) +public class MavenPlugin extends AbstractMojo { + + @Parameter(property = "templateName", required = true) + private String templateName; + + @Parameter(property = "sourceFileName") + private String sourceFileName; + + @Parameter(property = "outputFileName") + private String outputFileName; + + @Parameter(property = "contextBuilderClassName", required = true) + private String contextBuilderClassName; + + @Parameter(property = "contextConfigFileName") + private String contextConfigFileName; + + @Parameter (property = "project") + private MavenProject project; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + ModelGenerator generator = new ModelGenerator(); + try { + trace("\t === Called MavenPlugin on builder <" + contextBuilderClassName +">\n"); + generator.execute(sourceFileName,outputFileName,templateName,contextBuilderClassName,contextConfigFileName); + String workDirectory = getWorkDirectory(outputFileName); + project.addCompileSourceRoot(workDirectory); + } catch (Exception e) { + e.printStackTrace(); + throw new MojoExecutionException(e.getMessage()); + } + } + + private String getWorkDirectory(String outputFileName) throws IOException { + String workDirPath = Paths.get(outputFileName.toString()).getParent().toString(); + return workDirPath; + } + + private void trace(String message) { + getLog().info(message); + } +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/JsonContextBuilderImpl.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/JsonContextBuilderImpl.java new file mode 100644 index 000000000..6c408dd1d --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/JsonContextBuilderImpl.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.extensions; + +import org.onap.appc.tools.generator.api.ContextBuilder; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class JsonContextBuilderImpl implements ContextBuilder { + + @Override + public Map buildContext(String sourceFile, String contextConf) throws IOException { + //read json file + ObjectMapper mapper = new ObjectMapper(); + JsonNode model = mapper.readTree(new File(sourceFile)); + + //get context config file + Properties properties = new Properties(); + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + InputStream inputStream = classloader.getResourceAsStream(contextConf); + properties.load(inputStream); + + //get context related properties + ObjectNode metadata = mapper.createObjectNode(); + for (String key : properties.stringPropertyNames()) { + if (key.startsWith("ctx")) { + metadata.put(key.replaceFirst("ctx.", ""), properties.getProperty(key)); + } + } + + //create context and populate it + Map map = new HashMap<>(); + map.put("model", model); + map.put("metadata", metadata); + return map; + } +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/YangContextBuilderImpl.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/YangContextBuilderImpl.java new file mode 100644 index 000000000..67055c757 --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/extensions/YangContextBuilderImpl.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.extensions; + +import org.onap.appc.tools.generator.api.ContextBuilder; +import com.google.common.base.Optional; + +import org.opendaylight.yangtools.yang.model.api.Module; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException; +import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; +import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; +import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ModuleEffectiveStatementImpl; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Map; +import java.util.HashMap; +import java.util.Set; + +public class YangContextBuilderImpl implements ContextBuilder { + + @Override + public Map buildContext(String sourceFile, String contextConf) throws FileNotFoundException { + try ( InputStream source = new FileInputStream(sourceFile) ) {} + catch ( IOException ex) { + throw new FileNotFoundException("YANG file <" + sourceFile + ">not found"); + } + + Optional sc = null; + try ( YangTextSchemaContextResolver yangContextResolver = + YangTextSchemaContextResolver.create("yang-context-resolver")) { + yangContextResolver.registerSource(new URL("file:///" + sourceFile)); + sc = yangContextResolver.getSchemaContext(); + } catch (SchemaSourceException | IOException | YangSyntaxErrorException e) { + e.printStackTrace(); + } + + Map map = new HashMap<>(); + if ( null != sc && sc.isPresent()) { + Set modules = sc.get().getModules(); + for (Module module : modules) { + ModuleEffectiveStatementImpl impl = (ModuleEffectiveStatementImpl) module; + map.put("module", module); + } + } + + return map; + } + + // @Override + // public Map buildContext(String sourceFile, String + // contextConf) throws FileNotFoundException { + // InputStream source = new FileInputStream(sourceFile); + // if (source == null) { + // throw new FileNotFoundException("YANG file <" + sourceFile + ">not found"); + // } + // + // SchemaContext mSchema = parse(Collections.singletonList(source)); + // + // Map map = new HashMap<>(); + // map.put("module", mSchema.getModules().iterator().next()); + // return map; + // } + // + // private SchemaContext parse(List sources) { + // YangParserImpl parser = new YangParserImpl(); + // Set modules = parser.parseYangModelsFromStreams(sources); + // return parser.resolveSchemaContext(modules); + // } + +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/CodeGenWriter.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/CodeGenWriter.java new file mode 100644 index 000000000..347c24c06 --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/CodeGenWriter.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.impl; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class CodeGenWriter extends Writer { + + private FileWriter fileWriter; + private boolean delimiterBeginFound; + private Path basePath; + private String outPath; + private boolean deleteFile; + private static final String DELIMITER = "__"; + private Pattern pattern; + + + CodeGenWriter(String destination) throws IOException { + super(destination); + fileWriter = new FileWriter(destination); + basePath = Paths.get(destination); + delimiterBeginFound = false; + outPath = ""; + deleteFile = false; + pattern = Pattern.compile(DELIMITER); + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + String bufferStr = new String(cbuf).substring(off, off + len); + Matcher matcher = pattern.matcher(bufferStr); + + boolean isMatch = matcher.find(); + if (!isMatch) { + if (!delimiterBeginFound) { + fileWriter.write(cbuf, off, len); + } + else { + outPath += bufferStr; + } + } + else { + if (!delimiterBeginFound) { + delimiterBeginFound = true; + } + else { + deleteFile = true; + Path fileName = getNewFileName(); + Files.createDirectories(fileName.getParent()); + openNewFileWriter(fileName.toString()); + delimiterBeginFound = false; + outPath = ""; + } + } + } + + @Override + public void flush() throws IOException { + fileWriter.flush(); + } + + @Override + public void close() throws IOException { + fileWriter.close(); + if (deleteFile) { + Files.deleteIfExists(basePath); + } + } + + private Path getNewFileName() { + String newRelativePath = this.outPath.replace(".", File.separator); + return Paths.get(basePath.getParent().toString(), newRelativePath + ".java"); + } + + private void openNewFileWriter(String fileName) throws IOException { + flush(); + close(); + fileWriter = new FileWriter(fileName); + } +} diff --git a/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/ModelGenerator.java b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/ModelGenerator.java new file mode 100644 index 000000000..2275fdac7 --- /dev/null +++ b/appc-client/code-generator/src/main/java/org/onap/appc/tools/generator/impl/ModelGenerator.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.tools.generator.impl; + +import org.onap.appc.tools.generator.api.ContextBuilder; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; + +public class ModelGenerator { + + public void execute(String sourceFile, String destinationFile, String templateFile, String builderName, String contextConfName) throws IOException, ReflectiveOperationException { + + ContextBuilder contextBuilder = (ContextBuilder) Class.forName(builderName).newInstance(); + Map context = contextBuilder.buildContext(sourceFile, contextConfName); + + Path destinationPath = Paths.get(destinationFile); + if (!Files.isDirectory(destinationPath)) + Files.createDirectories(destinationPath.getParent()); + else { + Files.createDirectories(destinationPath); + } + + this.generate(context, templateFile, destinationFile); + System.out.println("\tFile <" + destinationFile + "> prepared successfully"); + } + + private void generate(Map context, String templateFile, String destinationFile) throws ReflectiveOperationException { + try { + Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); + cfg.setClassForTemplateLoading(ModelGenerator.class, "/"); + Template template = cfg.getTemplate(templateFile); + + Writer out = new CodeGenWriter(destinationFile); + template.process(context, out); + out.close(); + } catch (IOException | TemplateException e) { + throw new RuntimeException("Failed to generate file from template <" + templateFile + ">", e); + } + } + +} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/CLI.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/CLI.java deleted file mode 100644 index e28b3706a..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/CLI.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.api; - -import org.onap.appc.tools.generator.impl.ModelGenerator; - -public class CLI { - public static void main(String... args) throws Exception { - String sourceFile = args[0]; - if(sourceFile == null) - throw new IllegalArgumentException("Source file is missing. Please add argument 'client '"); - - String destinationFile = args[1]; - if(destinationFile == null) - throw new IllegalArgumentException("Destination file name is missing. Please add argument 'client " - + sourceFile - + " '"); - - String templateFile = args[2]; - if(templateFile == null) - throw new IllegalArgumentException("template file name is missing. Please add argument 'client " - + sourceFile - + " "+destinationFile - + " '"); - - String builderName = args[3]; - if(builderName == null) - throw new IllegalArgumentException("builder FQDN is missing. Please add argument 'client " - + sourceFile - + " "+destinationFile - + " "+templateFile - + " '"); - String contextConfName = args[4]; - if(contextConfName == null) - throw new IllegalArgumentException("context conf file is missing. Please add argument 'client " - + sourceFile - + " "+destinationFile - + " "+templateFile - + " "+builderName - + " '"); - ModelGenerator generator = new ModelGenerator(); - generator.execute(sourceFile, destinationFile, templateFile, builderName, contextConfName); - } -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/ContextBuilder.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/ContextBuilder.java deleted file mode 100644 index a1826f270..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/ContextBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.api; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; - -public interface ContextBuilder { - - Map buildContext(String sourceFile, String contextConf) throws IOException; -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/MavenPlugin.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/MavenPlugin.java deleted file mode 100644 index 9e160eed2..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/api/MavenPlugin.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.api; - -import org.onap.appc.tools.generator.impl.ModelGenerator; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; - -import java.io.IOException; -import java.nio.file.Paths; - -@Mojo( - name = "generate", - defaultPhase = LifecyclePhase.GENERATE_SOURCES -) -public class MavenPlugin extends AbstractMojo { - - @Parameter(property = "templateName", required = true) - private String templateName; - - @Parameter(property = "sourceFileName") - private String sourceFileName; - - @Parameter(property = "outputFileName") - private String outputFileName; - - @Parameter(property = "contextBuilderClassName", required = true) - private String contextBuilderClassName; - - @Parameter(property = "contextConfigFileName") - private String contextConfigFileName; - - @Parameter (property = "project") - private MavenProject project; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - ModelGenerator generator = new ModelGenerator(); - try { - trace("\t === Called MavenPlugin on builder <" + contextBuilderClassName +">\n"); - generator.execute(sourceFileName,outputFileName,templateName,contextBuilderClassName,contextConfigFileName); - String workDirectory = getWorkDirectory(outputFileName); - project.addCompileSourceRoot(workDirectory); - } catch (Exception e) { - e.printStackTrace(); - throw new MojoExecutionException(e.getMessage()); - } - } - - private String getWorkDirectory(String outputFileName) throws IOException { - String workDirPath = Paths.get(outputFileName.toString()).getParent().toString(); - return workDirPath; - } - - private void trace(String message) { - getLog().info(message); - } -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/JsonContextBuilderImpl.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/JsonContextBuilderImpl.java deleted file mode 100644 index 6c408dd1d..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/JsonContextBuilderImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.extensions; - -import org.onap.appc.tools.generator.api.ContextBuilder; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -public class JsonContextBuilderImpl implements ContextBuilder { - - @Override - public Map buildContext(String sourceFile, String contextConf) throws IOException { - //read json file - ObjectMapper mapper = new ObjectMapper(); - JsonNode model = mapper.readTree(new File(sourceFile)); - - //get context config file - Properties properties = new Properties(); - ClassLoader classloader = Thread.currentThread().getContextClassLoader(); - InputStream inputStream = classloader.getResourceAsStream(contextConf); - properties.load(inputStream); - - //get context related properties - ObjectNode metadata = mapper.createObjectNode(); - for (String key : properties.stringPropertyNames()) { - if (key.startsWith("ctx")) { - metadata.put(key.replaceFirst("ctx.", ""), properties.getProperty(key)); - } - } - - //create context and populate it - Map map = new HashMap<>(); - map.put("model", model); - map.put("metadata", metadata); - return map; - } -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/YangContextBuilderImpl.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/YangContextBuilderImpl.java deleted file mode 100644 index 67055c757..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/extensions/YangContextBuilderImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.extensions; - -import org.onap.appc.tools.generator.api.ContextBuilder; -import com.google.common.base.Optional; - -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; -import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; -import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ModuleEffectiveStatementImpl; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Map; -import java.util.HashMap; -import java.util.Set; - -public class YangContextBuilderImpl implements ContextBuilder { - - @Override - public Map buildContext(String sourceFile, String contextConf) throws FileNotFoundException { - try ( InputStream source = new FileInputStream(sourceFile) ) {} - catch ( IOException ex) { - throw new FileNotFoundException("YANG file <" + sourceFile + ">not found"); - } - - Optional sc = null; - try ( YangTextSchemaContextResolver yangContextResolver = - YangTextSchemaContextResolver.create("yang-context-resolver")) { - yangContextResolver.registerSource(new URL("file:///" + sourceFile)); - sc = yangContextResolver.getSchemaContext(); - } catch (SchemaSourceException | IOException | YangSyntaxErrorException e) { - e.printStackTrace(); - } - - Map map = new HashMap<>(); - if ( null != sc && sc.isPresent()) { - Set modules = sc.get().getModules(); - for (Module module : modules) { - ModuleEffectiveStatementImpl impl = (ModuleEffectiveStatementImpl) module; - map.put("module", module); - } - } - - return map; - } - - // @Override - // public Map buildContext(String sourceFile, String - // contextConf) throws FileNotFoundException { - // InputStream source = new FileInputStream(sourceFile); - // if (source == null) { - // throw new FileNotFoundException("YANG file <" + sourceFile + ">not found"); - // } - // - // SchemaContext mSchema = parse(Collections.singletonList(source)); - // - // Map map = new HashMap<>(); - // map.put("module", mSchema.getModules().iterator().next()); - // return map; - // } - // - // private SchemaContext parse(List sources) { - // YangParserImpl parser = new YangParserImpl(); - // Set modules = parser.parseYangModelsFromStreams(sources); - // return parser.resolveSchemaContext(modules); - // } - -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/CodeGenWriter.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/CodeGenWriter.java deleted file mode 100644 index 347c24c06..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/CodeGenWriter.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.impl; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -class CodeGenWriter extends Writer { - - private FileWriter fileWriter; - private boolean delimiterBeginFound; - private Path basePath; - private String outPath; - private boolean deleteFile; - private static final String DELIMITER = "__"; - private Pattern pattern; - - - CodeGenWriter(String destination) throws IOException { - super(destination); - fileWriter = new FileWriter(destination); - basePath = Paths.get(destination); - delimiterBeginFound = false; - outPath = ""; - deleteFile = false; - pattern = Pattern.compile(DELIMITER); - } - - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - String bufferStr = new String(cbuf).substring(off, off + len); - Matcher matcher = pattern.matcher(bufferStr); - - boolean isMatch = matcher.find(); - if (!isMatch) { - if (!delimiterBeginFound) { - fileWriter.write(cbuf, off, len); - } - else { - outPath += bufferStr; - } - } - else { - if (!delimiterBeginFound) { - delimiterBeginFound = true; - } - else { - deleteFile = true; - Path fileName = getNewFileName(); - Files.createDirectories(fileName.getParent()); - openNewFileWriter(fileName.toString()); - delimiterBeginFound = false; - outPath = ""; - } - } - } - - @Override - public void flush() throws IOException { - fileWriter.flush(); - } - - @Override - public void close() throws IOException { - fileWriter.close(); - if (deleteFile) { - Files.deleteIfExists(basePath); - } - } - - private Path getNewFileName() { - String newRelativePath = this.outPath.replace(".", File.separator); - return Paths.get(basePath.getParent().toString(), newRelativePath + ".java"); - } - - private void openNewFileWriter(String fileName) throws IOException { - flush(); - close(); - fileWriter = new FileWriter(fileName); - } -} diff --git a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/ModelGenerator.java b/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/ModelGenerator.java deleted file mode 100644 index 2275fdac7..000000000 --- a/appc-client/code-generator/src/main/java/org/openecomp/appc/tools/generator/impl/ModelGenerator.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.tools.generator.impl; - -import org.onap.appc.tools.generator.api.ContextBuilder; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import java.io.IOException; -import java.io.Writer; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Map; - -public class ModelGenerator { - - public void execute(String sourceFile, String destinationFile, String templateFile, String builderName, String contextConfName) throws IOException, ReflectiveOperationException { - - ContextBuilder contextBuilder = (ContextBuilder) Class.forName(builderName).newInstance(); - Map context = contextBuilder.buildContext(sourceFile, contextConfName); - - Path destinationPath = Paths.get(destinationFile); - if (!Files.isDirectory(destinationPath)) - Files.createDirectories(destinationPath.getParent()); - else { - Files.createDirectories(destinationPath); - } - - this.generate(context, templateFile, destinationFile); - System.out.println("\tFile <" + destinationFile + "> prepared successfully"); - } - - private void generate(Map context, String templateFile, String destinationFile) throws ReflectiveOperationException { - try { - Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); - cfg.setClassForTemplateLoading(ModelGenerator.class, "/"); - Template template = cfg.getTemplate(templateFile); - - Writer out = new CodeGenWriter(destinationFile); - template.process(context, out); - out.close(); - } catch (IOException | TemplateException e) { - throw new RuntimeException("Failed to generate file from template <" + templateFile + ">", e); - } - } - -} diff --git a/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/api/CLITest.java b/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/api/CLITest.java new file mode 100644 index 000000000..4cd6bb5f5 --- /dev/null +++ b/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/api/CLITest.java @@ -0,0 +1,57 @@ +package org.onap.appc.tools.generator.api; + +import org.junit.Assert; +import org.junit.Test; + +public class CLITest { + @Test + public void missingSourceFileTest() { + CLI cli = new CLI(); + try { + String[] input = new String[1]; + cli.main(input); + } catch (Exception e) { + Assert.assertEquals("Source file is missing. Please add argument 'client '",e.getMessage()); + } + } + @Test + public void missingDestinationFileTest() { + CLI cli = new CLI(); + try { + String[] input = {"sourceFilePath",null}; + cli.main(input); + } catch (Exception e) { + Assert.assertEquals("Destination file name is missing. Please add argument 'client sourceFilePath '",e.getMessage()); + } + } + @Test + public void missingTemplateFileTest() { + CLI cli = new CLI(); + try { + String[] input = {"sourceFilePath","destinationPath",null}; + cli.main(input); + } catch (Exception e) { + Assert.assertEquals("template file name is missing. Please add argument 'client sourceFilePath destinationPath '",e.getMessage()); + } + } + @Test + public void missingBuilderNameTest() { + CLI cli = new CLI(); + try { + String[] input = {"sourceFilePath","destinationPath","templateFileName",null}; + cli.main(input); + } catch (Exception e) { + Assert.assertEquals("builder FQDN is missing. Please add argument 'client sourceFilePath destinationPath templateFileName '",e.getMessage()); + } + } + @Test + public void missingContextConfFileNameTest() { + CLI cli = new CLI(); + try { + String[] input = {"sourceFilePath","destinationPath","templateFileName","builderFQDN",null}; + cli.main(input); + } catch (Exception e) { + Assert.assertEquals(e.getMessage(),"context conf file is missing. Please add argument 'client sourceFilePath destinationPath templateFileName builderFQDN '"); + } + } +} diff --git a/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/impl/CodeGenWriterTest.java b/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/impl/CodeGenWriterTest.java new file mode 100644 index 000000000..e0669b836 --- /dev/null +++ b/appc-client/code-generator/src/test/java/org/onap/appc/tools/generator/impl/CodeGenWriterTest.java @@ -0,0 +1,22 @@ +package org.onap.appc.tools.generator.impl; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; + + +public class CodeGenWriterTest { + @Test + public void writeTest() throws IOException { + CodeGenWriter codeGenWriter = new CodeGenWriter("destination"); + char[] cbuf = {'t','e','s','t'}; + int off = 1; + int len = 3; + codeGenWriter.write(cbuf,off,len); + codeGenWriter.flush(); + codeGenWriter.close(); + Assert.assertNotNull(codeGenWriter); + } + +} diff --git a/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/api/CLITest.java b/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/api/CLITest.java deleted file mode 100644 index 4cd6bb5f5..000000000 --- a/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/api/CLITest.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.onap.appc.tools.generator.api; - -import org.junit.Assert; -import org.junit.Test; - -public class CLITest { - @Test - public void missingSourceFileTest() { - CLI cli = new CLI(); - try { - String[] input = new String[1]; - cli.main(input); - } catch (Exception e) { - Assert.assertEquals("Source file is missing. Please add argument 'client '",e.getMessage()); - } - } - @Test - public void missingDestinationFileTest() { - CLI cli = new CLI(); - try { - String[] input = {"sourceFilePath",null}; - cli.main(input); - } catch (Exception e) { - Assert.assertEquals("Destination file name is missing. Please add argument 'client sourceFilePath '",e.getMessage()); - } - } - @Test - public void missingTemplateFileTest() { - CLI cli = new CLI(); - try { - String[] input = {"sourceFilePath","destinationPath",null}; - cli.main(input); - } catch (Exception e) { - Assert.assertEquals("template file name is missing. Please add argument 'client sourceFilePath destinationPath '",e.getMessage()); - } - } - @Test - public void missingBuilderNameTest() { - CLI cli = new CLI(); - try { - String[] input = {"sourceFilePath","destinationPath","templateFileName",null}; - cli.main(input); - } catch (Exception e) { - Assert.assertEquals("builder FQDN is missing. Please add argument 'client sourceFilePath destinationPath templateFileName '",e.getMessage()); - } - } - @Test - public void missingContextConfFileNameTest() { - CLI cli = new CLI(); - try { - String[] input = {"sourceFilePath","destinationPath","templateFileName","builderFQDN",null}; - cli.main(input); - } catch (Exception e) { - Assert.assertEquals(e.getMessage(),"context conf file is missing. Please add argument 'client sourceFilePath destinationPath templateFileName builderFQDN '"); - } - } -} diff --git a/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/impl/CodeGenWriterTest.java b/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/impl/CodeGenWriterTest.java deleted file mode 100644 index e0669b836..000000000 --- a/appc-client/code-generator/src/test/java/org/openecomp/appc/tools/generator/impl/CodeGenWriterTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.onap.appc.tools.generator.impl; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.IOException; - - -public class CodeGenWriterTest { - @Test - public void writeTest() throws IOException { - CodeGenWriter codeGenWriter = new CodeGenWriter("destination"); - char[] cbuf = {'t','e','s','t'}; - int off = 1; - int len = 3; - codeGenWriter.write(cbuf,off,len); - codeGenWriter.flush(); - codeGenWriter.close(); - Assert.assertNotNull(codeGenWriter); - } - -} diff --git a/appc-common/src/main/java/org/onap/appc/CmdLine.java b/appc-common/src/main/java/org/onap/appc/CmdLine.java new file mode 100644 index 000000000..d63bd8758 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/CmdLine.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + package org.onap.appc; + +import org.onap.appc.encryption.EncryptionTool; + +public class CmdLine { + + public static void main(String[] args) { + if(args.length <= 1 || args.length >= 3){ + printUsage(); + }else{ + String command = args[0]; + + switch(command){ + case "encrypt": + if(args[1]!= null){ + String clearText = args[1]; + String encrypted = EncryptionTool.getInstance().encrypt(clearText); + System.out.println(encrypted); + }else{ + printUsage(); + } + break; + default: + printUsage(); + break; + + } + } + + } + + private static void printUsage(){ + System.out.println("Usage: java -jar ..."); + System.out.println("\tencrypt \t\t(Encrypts your text)"); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/Constants.java b/appc-common/src/main/java/org/onap/appc/Constants.java new file mode 100644 index 000000000..e030b647d --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/Constants.java @@ -0,0 +1,212 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc; + +/** + * This class contains the definitions of all constant values used in the APPC provider, adapters, and other components. + * These constants define properties, settings, and context variables. The context variables can be referenced from + * within the directed graph(s) to access information placed their by the provider and adapters. + *

+ * Context properties are set in the graph context by the various adapters and the provider, or by the graph itself. + * These properties may also be accessed by the graph, adapters, or the provider. It is these properties that allow + * communication of state through the directed graph. All context properties have a symbolic name that starts with + * "CONTEXT_". + *

+ * + */ + +public final class Constants { + + /** + * The name for the error code attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_ERROR_CODE = "error_code"; + + /** + * The name for the error message attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + + /** + * The name for the success message attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; + + public static final String DG_ATTRIBUTE_STATUS = "SvcLogic.status"; + public static final String DG_OUTPUT_STATUS_CODE = "output.status.code"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + /** + * The property that defines the name of the DG service logic to be loaded + */ + public static final String PROPERTY_MODULE_NAME = "appc.service.logic.module.name"; + + /** + * The property that defines the topology restart DG version to be used + */ + public static final String PROPERTY_TOPOLOGY_VERSION = "appc.topology.dg.version"; + + /** + * The method name of the DG that is used to perform topology restart operations + */ + public static final String PROPERTY_TOPOLOGY_METHOD = "appc.topology.dg.method"; + + /** + * The property that supplies the application name + */ + public static final String PROPERTY_APPLICATION_NAME = "appc.application.name"; + + /** + * The execution mode for the directed graph + */ + public static final String SYNC_MODE = "sync"; + + /** + * The name of the property that contains the service request enumerated value in the graph's context + */ + public static final String CONTEXT_SERVICE = "org.onap.appc.service"; + + /** + * The name of the property that contains the VM id value in the graph's context + */ + public static final String CONTEXT_VMID = "org.onap.appc.vmid"; + + /** + * The name of the property that contains the VM id value in the graph's context + */ + public static final String CONTEXT_IDENTITY_URL = "org.onap.appc.identity.url"; + + /** + * The name of the property that contains the service request id value in the graph's context + */ + public static final String CONTEXT_REQID = "org.onap.appc.reqid"; + + /** + * The name of the property that indicates which method of the IaaS adapter to call + */ + public static final String CONTEXT_ACTION = "org.onap.appc.action"; + + /** + * The enumerated value for restart of a VM. This is a constant for one possible value of CONTEXT_SERVICE. + */ + public static final String SERVICE_RESTART = "RESTART"; + + /** + * The enumerated value for rebuild of a VM. This is a constant for one possible value of CONTEXT_SERVICE. + */ + public static final String SERVICE_REBUILD = "REBUILD"; + + /** + * The name of the adapter. We get the name from a property file so that it can be changed easily if needed. + */ + public static final String PROPERTY_ADAPTER_NAME = "org.onap.appc.provider.adaptor.name"; + + /** + * The minimum number of contexts to cache in each provider/tenant pool + */ + public static final String PROPERTY_MIN_POOL_SIZE = "org.onap.appc.provider.min.pool"; + + /** + * The maximum number of contexts to cache in each provider/tenant pool + */ + public static final String PROPERTY_MAX_POOL_SIZE = "org.onap.appc.provider.max.pool"; + + /** + * The amount of time, in seconds, that the application waits for a change of state of a server to a known valid + * state before giving up and failing the request. + */ + public static final String PROPERTY_SERVER_STATE_CHANGE_TIMEOUT = "org.onap.appc.server.state.change.timeout"; + + /** + * The amount of time, in seconds, between subsequent polls to the openstack provider to update the state of a + * resource + */ + public static final String PROPERTY_OPENSTACK_POLL_INTERVAL = "org.onap.appc.openstack.poll.interval"; + + /** + * The amount of time, in seconds, to wait between retry attempts when a connection to a provider fails. + */ + public static final String PROPERTY_RETRY_DELAY = "org.onap.appc.provider.retry.delay"; + + /** + * The maximum number of times a connection retry will be attempted before the application fails the request + */ + public static final String PROPERTY_RETRY_LIMIT = "org.onap.appc.provider.retry.limit"; + /** + * The amount of time, in seconds, that the application waits for a change of state of a stacj to a known valid + * state before giving up and failing the request. + */ + public static final String PROPERTY_STACK_STATE_CHANGE_TIMEOUT ="org.onap.appc.stack.state.change.timeout" ; + + @SuppressWarnings("nls") + public static final String STATUS_GETTER = "status-getter"; + + @SuppressWarnings("nls") + public static final String VM_FUSION_STATUS_GETTER = "fusion-vm-status-getter"; + + /** + * The name for the status vm attribute to be set in the context when executing a vmstatuscheck. + */ + + @SuppressWarnings("nls") + public static final String STATUS_OF_VM = "status-vm"; + + /** + * Yang revision value to be used while generating YANG module + */ + public static final String YANG_REVISION = "2017-03-03"; + /** + * Yang revision format to be used while formatting YANG revision date + */ + public static final String YANG_REVISION_FORMAT = "YYYY-MM-DD"; + + /** + * Base container for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_BASE_CONTAINER = "vnf-config-repo"; + + /** + *VNF config list for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_VNF_CONFIG_LIST = "vnf-config-list"; + + /** + *Base container of VNF configuration data for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_VNF_CONFIG = "vnf-config"; + + /** + * Private default constructor prevents instantiation + */ + + private Constants() { + + } +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/CacheStrategies.java b/appc-common/src/main/java/org/onap/appc/cache/CacheStrategies.java new file mode 100644 index 000000000..fadf9cb4f --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/CacheStrategies.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache; + +/** + * Enum of CacheStrategies + */ +public enum CacheStrategies { + LRU +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/CacheStrategy.java b/appc-common/src/main/java/org/onap/appc/cache/CacheStrategy.java new file mode 100644 index 000000000..af91bb28c --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/CacheStrategy.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache; + +/** + * Interface of CacheStrategy + * @param key + * @param value + */ +public interface CacheStrategy { + /** + * Get object + * @param key of the object + * @return value of the object + */ + V getObject(K key); + + /** + * Put object + * @param key of the object + * @param value of the object + */ + void putObject(K key,V value); +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/MetadataCache.java b/appc-common/src/main/java/org/onap/appc/cache/MetadataCache.java new file mode 100644 index 000000000..ea0cad28f --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/MetadataCache.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache; + +/** + * Interface of MetadataCache + * @param key + * @param value + */ +public interface MetadataCache { + /** + * Get object + * @param key of the object + * @return value of the object + */ + V getObject(K key); + + /** + * Put object + * @param key of the object + * @param value of the object + */ + void putObject(K key,V value); +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/impl/LRUCache.java b/appc-common/src/main/java/org/onap/appc/cache/impl/LRUCache.java new file mode 100644 index 000000000..b82552f20 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/impl/LRUCache.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.onap.appc.cache.CacheStrategy; + +/** + * LRU cache implements CacheStategy + * @param Key + * @param Value + */ +public class LRUCache implements CacheStrategy { + + private Map map; + + LRUCache(final Integer capacity){ + map = new LinkedHashMap(capacity, 0.75F, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest){ + return size() > capacity; + } + }; + } + + @Override + public V getObject(K key) { + return map.get(key); + } + + @Override + public void putObject(K key, V value) { + map.put(key,value); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheFactory.java b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheFactory.java new file mode 100644 index 000000000..c140c6e8b --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheFactory.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.onap.appc.cache.CacheStrategies; +import org.onap.appc.cache.MetadataCache; + +/** + * Metadata Cache Factory + */ +public class MetadataCacheFactory { + + private static class ReferenceHolder { + private ReferenceHolder() { + throw new IllegalAccessError("ReferenceHolder"); + } + + private static final MetadataCacheFactory FACTORY = new MetadataCacheFactory(); + } + + private MetadataCacheFactory() { + // do nothing + } + + public static MetadataCacheFactory getInstance(){ + return ReferenceHolder.FACTORY; + } + + public MetadataCache getMetadataCache(){ + return new MetadataCacheImpl(); + } + + /** + * Get MetadataCache + * @param cacheStrategy the CacheStrategies to be used to build MetadataCacheImpl + * @return a new instance of MetadataCacheImpl + */ + public MetadataCache getMetadataCache(CacheStrategies cacheStrategy) { + return new MetadataCacheImpl(cacheStrategy); + } + + + +} diff --git a/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java new file mode 100644 index 000000000..ca225adfe --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.onap.appc.cache.CacheStrategies; +import org.onap.appc.cache.CacheStrategy; +import org.onap.appc.cache.MetadataCache; + +/** + * Implementation of MetadataCache + * @param Key + * @param Value + */ +public class MetadataCacheImpl implements MetadataCache { + + private CacheStrategy strategy; + + MetadataCacheImpl(){ + this(CacheStrategies.LRU); + } + + MetadataCacheImpl(CacheStrategies strategy){ + this.strategy = initializeStrategy(strategy); + } + + private CacheStrategy initializeStrategy(CacheStrategies strategy) { + if (strategy != null) { + switch (strategy) { + case LRU: + return new LRUCache<>(50); + default: + // do nothing + } + } + return null; + } + + @Override + public V getObject(K key) { + return (V)strategy.getObject(key); + } + + @Override + public void putObject(K key, V value) { + strategy.putObject(key,value); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/concurrent/Signal.java b/appc-common/src/main/java/org/onap/appc/concurrent/Signal.java new file mode 100644 index 000000000..5d439d164 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/concurrent/Signal.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.concurrent; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeoutException; + +import org.onap.appc.util.StringHelper; + +/** + * This class is used to synchronize signaling of status between threads. + *

+ * In complex multi-threaded applications it is often necessary to synchronize operations between threads. This is + * especially true in complex algorithms where processing dependencies exist between different threads and the + * synchronization of the operations of those threads is required. This class is a framework to enable multi-thread + * signaling and wait/post logic that makes the thread synchronization easier. + *

+ *

+ * Basically, in thread synchronization, one thread is the "waiter" and one or more other threads are the "notifiers". + * The notifiers send signals to the waiter to inform that thread that certain conditions are true, processing has been + * completed, or to inform the waiter of the state of the other thread(s). In the basic java framework, the waiter and + * notifier are simply using the wait/notify mechanism provided, which does not allow for different conditions, state, + * or "signals" to exist. The wait/notify mechanism, in combination with the object mutex, provides basic blocking and + * releasing of a thread's dispatching state. + *

+ *

+ * This class builds upon the java wait/notify mechanism and allows for "signals" to be defined. These signals are + * simply string constants that mean something to the waiter and notifier threads. Any number of signals may be defined, + * and it is possible to wait for more than one signal to be received, wait for any one of a set to be received, or to + * test if a signal has been received without blocking. + *

+ *

+ * Some operations are blocking operations. These stop the execution of the calling thread until the specified condition + * is true. These blocking methods are all named "wait...", such as {@link #waitFor(String...)} and + * {@link #waitForAny(String...)}. The thread making the call to these blocking methods MUST be the waiter thread (the + * thread registered with the signal object). + *

+ *

+ * Some operations are non-blocking. These operations allow for the testing or setting of signal conditions and do not + * block the caller. When calling these methods ({@link #isSignaled(String)}, {@link #signal(String)}, and + * {@link #setTimeout(long)} the waiter thread mutex will be held and may block the waiter thread for the duration of + * the method call. + *

+ */ +public class Signal { + + /** + * The thread must be the thread of the waiter that is waiting for the signals to be received. It is the recipient + * of the signaled condition. This allows any number of other threads to send signals to the recipient and have the + * recipient synchronize its operation with the receipt of the appropriate signal(s). + */ + private Thread thread; + + /** + * The amount of time to wait for a signal to be receieved. Set to zero to wait forever. + */ + private long timeout = 0L; + + /** + * The collection of all received signals. Note, this need not be a synchronized collection because it will always + * be accessed while holding the mutex of the thread, therefore it is implicitly synchronized. + */ + private List receivedSignals; + + /** + * A signal object must access a thread that is waiting for the receipt of the signal(s). + */ + public Signal(Thread thread) { + this.thread = thread; + receivedSignals = new ArrayList(); + } + + /** + * Checks the waiter to see if it has been signaled + * + * @param signal + * The signal to check for + * @return True if the signal has been received, false otherwise + */ + public boolean isSignaled(String signal) { + synchronized (thread) { + return _signaled(signal); + } + } + + /** + * Sends the indicated signal to the waiter. + * + * @param signal + * The signal that is to be sent to the waiting thread and to notify it to process the signal. + */ + public void signal(String signal) { + synchronized (thread) { + if (!_signaled(signal)) { + receivedSignals.add(signal); + } + thread.notify(); + } + } + + /** + * Blocks the waiting thread until all of the indicated signals have been received, or the wait times out. + * + * @param signals + * The signals to be received. The waiter is blocked forever or until all of the signals are received. + * @throws TimeoutException + * If the wait has timed out waiting for a response + */ + public void waitFor(String... signals) throws TimeoutException { + long limit = System.currentTimeMillis() + timeout; + synchronized (thread) { + while (true) { + boolean complete = true; + for (String signal : signals) { + if (!_signaled(signal)) { + complete = false; + } + } + + if (complete) { + receivedSignals.removeAll(Arrays.asList(signals)); + return; + } + + if (timeout > 0) { + if (System.currentTimeMillis() > limit) { + throw new TimeoutException(String.format("Signals %s not received in the allotted timeout.", + StringHelper.asList(signals))); + } + } + + try { + thread.wait(timeout); + } catch (InterruptedException e) { + /* + * Interrupted exceptions are ignored + */ + } + } + } + } + + /** + * This method blocks the waiter until at least one of the indicated signals have been received. + * + * @param signals + * A list of signals, any one of which will satisfy the wait condition + * @return The signal that satisfied the wait + * @throws TimeoutException + * If none of the signals have been received within the allotted time + */ + public String waitForAny(String... signals) throws TimeoutException { + long limit = System.currentTimeMillis() + timeout; + synchronized (thread) { + while (true) { + for (String signal : signals) { + if (!_signaled(signal)) { + receivedSignals.remove(signal); + return signal; + } + } + + if (timeout > 0) { + if (System.currentTimeMillis() > limit) { + throw new TimeoutException( + String.format("One of signals \"%s\" not received in the allotted timeout.", + StringHelper.asList(signals))); + } + } + + try { + thread.wait(timeout); + } catch (InterruptedException e) { + /* + * Interrupted exceptions are ignored + */ + } + } + } + } + + /** + * This private method is used to handle the check for signaled status. Note that this method assumes the caller + * holds the thread mutex. + * + * @param signals + * The list of signals to check for + * @return True if any one of the signals has been received. + */ + private boolean _signaled(String... signals) { + for (String signal : signals) { + if (receivedSignals.contains(signal)) { + return true; + } + } + return false; + } + + /** + * Sets the timeout value for waiting for signals to be received + * + * @param timeout + */ + public void setTimeout(long timeout) { + this.timeout = timeout; + } +} diff --git a/appc-common/src/main/java/org/onap/appc/configuration/Configuration.java b/appc-common/src/main/java/org/onap/appc/configuration/Configuration.java new file mode 100644 index 000000000..a0acf12cc --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/configuration/Configuration.java @@ -0,0 +1,243 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.configuration; + +import java.util.Properties; + +import org.slf4j.Logger; + + + +/** + * This interface defines the common configuration support that is available to the application. + *

+ * Where properties are common to all CDP components (server, coordinator, and EPM), the property symbolic values are + * defined as part of this interface. Where they are unique to each component, they must be defined within that + * component. + *

+ */ +public interface Configuration { + + String PROPERTY_BOOTSTRAP_FILE_NAME = "org_onap_appc_bootstrap_file"; // + String DEFAULT_BOOTSTRAP_FILE_NAME = "appc.properties"; + String PROPERTY_BOOTSTRAP_FILE_PATH = "org_onap_appc_bootstrap_path"; // + String DEFAULT_BOOTSTRAP_FILE_PATH = "/opt/openecomp/appc/data/properties,${user.home},etc,../etc"; + String PROPERTY_RESOURCE_BUNDLES = "org.onap.appc.resources"; + String DEFAULT_RESOURCE_BUNDLES = "org/onap/appc/i18n/MessageResources"; + + /** + * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for + * {@link Boolean#valueOf(String)} are used. + * + * @param key + * The property key + * @return The value of the property expressed as a boolean, or false if it does not exist. + */ + boolean getBooleanProperty(String key); + + /** + * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for + * {@link Boolean#valueOf(String)} are used. + * + * @param key + * The property key + * @param defaultValue + * The default value to be returned if the property does not exist + * @return The value of the property expressed as a boolean, or false if it does not exist. + */ + boolean getBooleanProperty(String key, boolean defaultValue); + + /** + * Returns the indicated property value expressed as a floating point double-precision value (double). The standard + * rules for {@link Double#valueOf(String)} are used. + * + * @param key + * The property to retrieve + * @return The value of the property, or 0.0 if not found or invalid + */ + double getDoubleProperty(String key); + + /** + * Returns the indicated property value expressed as a floating point double-precision value (double). The standard + * rules for {@link Double#valueOf(String)} are used. + * + * @param key + * The property to retrieve + * @param defaultValue + * The default value to be returned if the property does not exist + * @return The value of the property, or 0.0 if not found or invalid + */ + double getDoubleProperty(String key, double defaultValue); + + /** + * Returns the property indicated expressed as an integer. The standard rules for + * {@link Integer#parseInt(String, int)} using a radix of 10 are used. + * + * @param key + * The property name to retrieve. + * @return The value of the property, or 0 if it does not exist or is invalid. + */ + int getIntegerProperty(String key); + + /** + * Returns the property indicated expressed as an integer. The standard rules for + * {@link Integer#parseInt(String, int)} using a radix of 10 are used. + * + * @param key + * The property name to retrieve. + * @param defaultValue + * The default value to be returned if the property does not exist + * @return The value of the property, or 0 if it does not exist or is invalid. + */ + int getIntegerProperty(String key, int defaultValue); + + /** + * Returns the specified property as a long integer value, if it exists, or zero if it does not. + * + * @param key + * The key of the property desired. + * @return The value of the property expressed as an integer long value, or zero if the property does not exist or + * is not a valid integer long. + */ + long getLongProperty(String key); + + /** + * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist + * or is invalid. + * + * @param key + * The key of the property desired. + * @param defaultValue + * the value to be returned if the property is not valid or does not exist. + * @return The value of the property expressed as an integer long value, or the default value if the property does + * not exist or is not a valid integer long. + */ + long getLongProperty(String key, long defaultValue); + + /** + * This method can be called to retrieve a properties object that is immutable. Any attempt to modify the properties + * object returned will result in an exception. This allows a caller to view the current configuration as a set of + * properties. + * + * @return An unmodifiable properties object. + */ + Properties getProperties(); + + /** + * This method is called to obtain a property as a string value + * + * @param key + * The key of the property + * @return The string value, or null if it does not exist. + */ + String getProperty(String key); + + /** + * This method is called to obtain a property as a string value + * + * @param key + * The key of the property + * @param defaultValue + * The default value to be returned if the property does not exist + * @return The string value, or null if it does not exist. + */ + String getProperty(String key, String defaultValue); + + /** + * Returns true if the named property is defined, false otherwise. + * + * @param key + * The key of the property we are interested in + * @return True if the property exists. + */ + boolean isPropertyDefined(String key); + + /** + * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only + * if it has the value "true" or "false" (ignoring case). + * + * @param key + * The property to be checked + * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string + */ + boolean isValidBoolean(String key); + + /** + * Returns an indication if the indicated property represents a valid double-precision floating point number. + * + * @param key + * The property to be examined + * @return True if the property is a valid representation of a double, or false if it does not exist or contains + * illegal characters. + */ + boolean isValidDouble(String key); + + /** + * Returns an indication if the property is a valid integer value or not. + * + * @param key + * The key of the property to check + * @return True if the value is a valid integer string, or false if it does not exist or contains illegal + * characters. + */ + boolean isValidInteger(String key); + + /** + * Determines is the specified property exists and is a valid representation of an integer long value. + * + * @param key + * The property to be checked + * @return True if the property is a valid representation of an integer long value, and false if it either does not + * exist or is not valid. + */ + boolean isValidLong(String key); + + /** + * This method allows the caller to set all properties from a provided properties object into the configuration + * property set. + *

+ * The primary difference between this method and the factory method + * {@link ConfigurationFactory#getConfiguration(Properties)} is that this method does not clear and reload the + * configuration. Rather, this method merges the provided properties object contents into the existing properties, + * replacing any same-named keys with the values from this object. + *

+ * + * @param properties + * The properties object to copy all properties from + */ + void setProperties(Properties properties); + + /** + * This method allows a caller to insert a new property definition into the configuration object. This allows the + * application to adjust or add to the current configuration. If the property already exists, it is replaced with + * the new value. + * + * @param key + * The key of the property to be defined + * @param value + * The value of the property to be defined + */ + void setProperty(String key, String value); +} diff --git a/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java b/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java new file mode 100644 index 000000000..ee2648847 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java @@ -0,0 +1,421 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.configuration; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.text.DateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Properties; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; +import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; + +import org.onap.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * The configuration factory is used to obtain access to an already created and initialized singleton configuration + * object as well as to create and initialize the singleton if not already set up. + *

+ * This class is responsible for the creation of the configuration object used to manage the configuration of the + * application. The configuration object implementation must implement the Configuration interface. This + * allows for the factory to create different specializations in the future if needed and not break any application + * code. + *

+ *

+ * The configuration object is basically a wrapper around a properties object. The configuration is therefore specified + * as a set of properties that are loaded and processed from different sources with different precedences. It is + * important that the configuration object always be able to supply default values for any configuration properties that + * must be supplied, and not rely on the user always supplying these values. This also relieves the application itself + * from having to interpret missing or invalid properties and applying defaults. By having all of the defaults in one + * place, the application code can be simpler (not having to worry about defaults or invalid properties), and the + * defaults can be changed much easier (they are all in one place and not distributed throughout the codebase). + *

+ *

+ * Since the configuration is managed as a property object, we can use a characteristic of the Properties + * class to our advantage. Namely, if we put a property into a Properties object that already exists, the + * Properties object replaces it with the new value. This does not affect any other properties that may + * already be defined in the properties object. This gives us the ability to initialize the properties with default + * values for all of the application settings, then override just those that we need to override, possibly from multiple + * sources and in increasing order of precedence. + *

+ *

+ * This means that properties are in effect "merged" together from multiple sources in a prescribed precedence order. In + * fact, the precedence order that this factory implements is defined as: + *

+ *
    + *
  1. Default values from a system resource file.
  2. + *
  3. User-supplied properties file, if any.
  4. + *
  5. Application-supplied properties, if any.
  6. + *
  7. Command-line properties (if any)
  8. + *
+ *

+ * The name and location of the properties file that is loaded can also be set, either in the defaults, overridden by + * the system command line via -D, or as a system environment variable. There are two properties that can be specified + * to define the name and path. These are: + *

+ *
+ *
org.onap.appc.bootstrap.file
+ *
This property defines the name of the file that will be loaded. If not specified, the default value is + * "appc.properties". This can be specified in either (or both) the default properties or the command line. The command + * line specification will always override.
+ *
org.onap.appc.bootstrap.path
+ *
This is a comma-delimited (,) path of directories to be searched to locate the specified file. The first + * occurrence of the file is the one loaded, and no additional searching is performed. The path can be specified in + * either, or both, the default values and the command line specification. If specified on the command line, the value + * overrides the default values. If omitted, the default path is $/opt/openecomp/appc/data/properties,${user.home},.
+ *
+ * + * @since Mar 18, 2014 + * @version $Id$ + */ +public final class ConfigurationFactory { + + private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + /** + * This is a string constant for the comma character. It's intended to be used a common string delimiter. + */ + private static final String COMMA = ","; + + /** + * The default Configuration object that implements the Configuration interface and represents our + * system configuration settings. + */ + private static DefaultConfiguration config = null; + + /** + * The default properties resource to be loaded + */ + private static final String DEFAULT_PROPERTIES = "org/onap/appc/default.properties"; + + /** + * This collection allows for special configurations to be created and maintained, organized by some identification + * (such as an object reference to the StackBuilder to which they apply), and then obtained from the configuration + * factory when needed. + */ + private static HashMap localConfigs = new HashMap<>(); + + /** + * The reentrant shared lock used to serialize access to the properties. + */ + private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + /** + * This is a constant array of special property names that will be copied from the configuration back to the System + * properties object if they are defined in the configuration AND they do not already exist in the System properties + * object. These are intended as a convenience for setting the AFT properties for the Discovery client where it may + * be difficult or impossible to set VM arguments for the container. + */ + private static final String[] specialProperties = { + "AFT_LATITUDE", "AFT_LONGITUDE", "AFT_ENVIRONMENT", "SCLD_PLATFORM" + }; + + private ConfigurationFactory() { + } + + /** + * This method is used to obtain the common configuration object (as well as set it up if not already). + * + * @return The configuration object implementation + */ + public static Configuration getConfiguration() { + + /* + * First, attempt to access the properties as a read lock holder + */ + ReadLock readLock = lock.readLock(); + readLock.lock(); + try { + + /* + * If the properties don't exist, release the read lock and acquire the write lock. Once we get the write + * lock, we need to re-check to see that the configuration needs to be set up (because another thread may + * have beat us to it). After we get a configuration set up, release the write lock and re-obtain the read + * lock to access the properties. + */ + if (config == null) { + readLock.unlock(); + WriteLock writeLock = lock.writeLock(); + writeLock.lock(); + try { + if (config == null) { + config = new DefaultConfiguration(); + initialize(null); + } + } catch (Exception t) { + logger.error("getConfiguration", t); + } finally { + writeLock.unlock(); + } + readLock.lock(); + } + return config; + } finally { + readLock.unlock(); + } + } + + /** + * This method will obtain the local configuration for the specified object if it exists, or will create it from the + * current global configuration. This allows the configuration to be tailored for a specific process or operation, + * and uniquely identified by some value (such as the object that represents the special use of the configuration). + * + * @param owner + * The owner or identification of the owner of the special configuration + * @return The special configuration object, or a clone of the global configuration so that it can be altered if + * needed. + */ + public static Configuration getConfiguration(final Object owner) { + ReadLock readLock = lock.readLock(); + readLock.lock(); + try { + DefaultConfiguration local = (DefaultConfiguration) localConfigs.get(owner); + if (local == null) { + readLock.unlock(); + WriteLock writeLock = lock.writeLock(); + writeLock.lock(); + try { + local = (DefaultConfiguration) localConfigs.get(owner); + if (local == null) { + DefaultConfiguration global = (DefaultConfiguration) getConfiguration(); + try { + local = (DefaultConfiguration) global.clone(); + } catch (CloneNotSupportedException e) { + logger.error("getConfiguration", e); + } + localConfigs.put(owner, local); + } + } finally { + writeLock.unlock(); + } + readLock.lock(); + } + return local; + } finally { + readLock.unlock(); + } + } + + /** + * This method allows the caller to alter the configuration, supplying the specified configuration properties which + * override the application default values. + *

+ * The configuration is re-constructed (if already constructed) or created new (if not already created) and the + * default properties are loaded into the configuration. + *

+ *

+ * The primary purpose of this method is to allow the application configuration properties to be reset or refreshed + * after the application has already been initialized. This method will lock the configuration for the duration + * while it is being re-built, and should not be called on a regular basis. + *

+ * + * @param props + * The properties used to configure the application. + * @return Access to the configuration implementation + */ + public static Configuration getConfiguration(final Properties props) { + WriteLock writeLock = lock.writeLock(); + writeLock.lock(); + try { + config = new DefaultConfiguration(); + initialize(props); + return config; + } finally { + writeLock.unlock(); + } + } + + /** + * This method will clear the current configuration and then re-initialize it with the default values, + * application-specific configuration file, user-supplied properties (if any), and then command-line settings. + *

+ * This method MUST be called holding the configuration lock! + *

+ *

+ * This method is a little special in that logging messages generated during the method must be cached and delayed + * until after the logging framework has been initialized. After that, the delayed logging buffer can be dumped to + * the log file and cleared. + *

+ * + * @param props + * Application-supplied configuration values, if any + */ + private static void initialize(final Properties props) { + DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); + Date now = new Date(); + logger.info("------------------------------------------------------------------------------"); + + logger.info(Msg.CONFIGURATION_STARTED, format.format(now)); + + /* + * Clear any existing properties + */ + config.clear(); + logger.info(Msg.CONFIGURATION_CLEARED); + + /* + * Load the defaults (if any are present) + */ + InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_PROPERTIES); + if (in != null) { + logger.info(Msg.LOADING_DEFAULTS, DEFAULT_PROPERTIES); + try { + config.setProperties(in); + } finally { + try { + in.close(); + } catch (IOException e) { + // not much we can do since logger may not be configured yet + e.printStackTrace(System.out); + } + } + for (String key : config.getProperties().stringPropertyNames()) { + logger.info(Msg.PROPERTY_VALUE, key, config.getProperty(key)); + } + } else { + logger.info(Msg.NO_DEFAULTS_FOUND, DEFAULT_PROPERTIES); + } + + /* + * Look for application configuration property file. By default, we will look for the file "cdp.properties" on + * the user home path, then on "./etc" (relative to current path), then on "../etc" (relative to current path). + * If we do not find any property file, then we continue. Otherwise, we load the first property file we find and + * then continue. In order to allow default values for the filename and paths to be searched, we first attempt + * to obtain these from our configuration object (which should be primed with default values and/or overridden + * with application-specified values). We then use the values obtained from that to get any user supplied values + * on the command line. + */ + String filename = + config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, Configuration.DEFAULT_BOOTSTRAP_FILE_NAME); + filename = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, filename); + String env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME); + if (env != null && env.trim().length() > 0) { + filename = env; + } + + String path = + config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, Configuration.DEFAULT_BOOTSTRAP_FILE_PATH); + path = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, path); + env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH); + if (env != null && env.trim().length() > 0) { + path = env; + } + + logger.info(Msg.SEARCHING_CONFIGURATION_OVERRIDES, path, filename); + + String[] pathElements = path.split(COMMA); + boolean found = false; + for (String pathElement : pathElements) { + File file = new File(pathElement, filename); + if (file.exists() && file.canRead() && !file.isDirectory()) { + + logger.info(Msg.LOADING_CONFIGURATION_OVERRIDES, file.getAbsolutePath()); + Properties fileProperties = new Properties(); + BufferedInputStream stream = null; + try { + stream = new BufferedInputStream(new FileInputStream(file)); + fileProperties.load(stream); + for (String key : fileProperties.stringPropertyNames()) { + logger.debug(Msg.PROPERTY_VALUE, key, fileProperties.getProperty(key)); + config.setProperty(key, fileProperties.getProperty(key)); + } + found = true; + break; + } catch (IOException e) { + logger.error(EELFResourceManager.format(e)); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + // not much we can do since logger may not be configured + // yet + e.printStackTrace(System.out); + } + } + } + } + + if (!found) { + logger.warn(Msg.NO_OVERRIDE_PROPERTY_FILE_LOADED, filename, path); + } + + /* + * Apply any application-specified properties + */ + if (props != null) { + logger.info(Msg.LOADING_APPLICATION_OVERRIDES); + for (String key : props.stringPropertyNames()) { + logger.debug(Msg.PROPERTY_VALUE, key, props.getProperty(key)); + config.setProperty(key, props.getProperty(key)); + } + } else { + logger.info(Msg.NO_APPLICATION_OVERRIDES); + } + + /* + * Merge in the System.properties to pick-up any command line arguments (-Dkeyword=value) + */ + logger.info(Msg.MERGING_SYSTEM_PROPERTIES); + config.setProperties(System.getProperties()); + + /* + * As a convenience, copy the "specialProperties" that are not defined in System.properties from the + * configuration back to the system properties object. + */ + for (String key : config.getProperties().stringPropertyNames()) { + for (String specialProperty : specialProperties) { + if (key.equals(specialProperty) && !System.getProperties().containsKey(key)) { + System.setProperty(key, config.getProperty(key)); + logger.info(Msg.SETTING_SPECIAL_PROPERTY, key, config.getProperty(key)); + } + } + } + + /* + * Initialize the resource manager by loading the requested bundles, if any are defined. Resource bundles may be + * specified as a comma-delimited list of names. These resource names are base names of resource bundles, do not + * include the language or country code, or the ".properties" extension. The actual loading of the resource + * bundles is done lazily when requested the first time. If the bundle does not exist, or cannot be loaded, it + * is ignored. + */ + String resourcesList = + config.getProperty(Configuration.PROPERTY_RESOURCE_BUNDLES, Configuration.DEFAULT_RESOURCE_BUNDLES); + String[] resources = resourcesList.split(","); + for (String resource : resources) { + logger.info(Msg.LOADING_RESOURCE_BUNDLE, resource.trim()); + EELFResourceManager.loadMessageBundle(resource.trim()); + } + } +} diff --git a/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java b/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java new file mode 100644 index 000000000..3e86c0788 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java @@ -0,0 +1,557 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.configuration; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.security.Provider; +import java.security.Provider.Service; +import java.security.Security; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.onap.appc.encryption.EncryptionTool; +import org.onap.appc.util.UnmodifiableProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class provides the implementation of the Configuration interface. It is created by the + * ConfigurationFactory and initialized with the configuration values for the process. + * + * @version $Id$ + * @since Mar 18, 2014 + */ +public final class DefaultConfiguration implements Configuration, Cloneable { + + private static final Logger logger = LoggerFactory.getLogger(DefaultConfiguration.class); + + /** + * The framework configuration properties. + */ + private Properties properties = new Properties(); + + /** + * Construct the configuration object. + */ + DefaultConfiguration() { + // do nothing + } + + /** + * Clears all properties + */ + public void clear() { + properties.clear(); + } + + /** + * @see java.lang.Object#clone() + */ + @Override + protected Object clone() throws CloneNotSupportedException { + DefaultConfiguration clone = (DefaultConfiguration) super.clone(); + + clone.properties = new Properties(this.properties); + clone.properties.putAll(this.properties); + + return clone; + } + + /** + * Decrypts an encrypted value, if it is encrypted, and returns the clear text. Performs no operation on the string + * if it is not encrypted. + * + * @param value The value to (optionally) be decrypted + * @return The clear text + */ + @SuppressWarnings("nls") + private static String decrypt(String value) { + if (value != null && value.startsWith(EncryptionTool.ENCRYPTED_VALUE_PREFIX)) { + try { + return EncryptionTool.getInstance().decrypt(value); + } catch (Exception e) { + StringBuilder out = new StringBuilder(); + for (Provider p : Security.getProviders()) { + for (Service s : p.getServices()) { + String algo = s.getAlgorithm(); + out.append(String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", + algo, p.getName(), s.getClassName())); + } + } + logger.debug(out.toString()); + logger.warn(String.format("Could not decrypt the configuration value [%s]", value), e); + } + } + return value; + } + + /** + * Decrypts all elements in the properties object + */ + private void decryptAllProperties() { + if (properties != null) { + for (Entry e : properties.entrySet()) { + if (e.getValue() != null) { + e.setValue(decrypt(e.getValue().toString())); + } + } + } + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + + if (obj == null) { + return false; + } + + if (this.getClass() != obj.getClass()) { + return false; + } + + DefaultConfiguration other = (DefaultConfiguration) obj; + + return (this.properties.size() == other.properties.size()) + && (this.properties.entrySet().containsAll(other.properties.entrySet())) + && (other.properties.entrySet().containsAll(this.properties.entrySet())); + + } + + /** + * This method will use the properties object to expand any variables that may be present in the template provided. + * Variables are represented by the string "${name}", where "name" is the name of a property defined in either the + * current configuration object, or system properties if undefined. If the value cannot be found, the variable is + * removed and an empty string is used to replace the variable. + * + * @param template The template to be expanded + * @return The expanded template where each variable is replaced with its value + */ + @SuppressWarnings("nls") + private String expandVariables(String template) { + if (template == null) { + return null; + } + + // Decrypt the template if needed + // template = decrypt(template); DH: Do not assign values to parameters, bad form! Also, Sonar complains + // bitterly + + StringBuilder builder = new StringBuilder(decrypt(template)); + Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}"); + Matcher matcher = pattern.matcher(builder); + while (matcher.find()) { + String variable = matcher.group(1); + String value = properties.getProperty(variable); + if (value == null) { + value = System.getProperty(variable); + } + if (value == null) { + value = ""; + } + builder.replace(matcher.start(), matcher.end(), value); + + matcher.reset(); + } + return builder.toString().trim(); + } + + /** + * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for + * Boolean.parseBoolean() are used. + * + * @param key The property key + * @return The value of the property expressed as a boolean, or false if it does not exist. + */ + @SuppressWarnings("nls") + @Override + public boolean getBooleanProperty(String key) { + return Boolean.valueOf(getProperty(key, "false")); + } + + /** + * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for + * Boolean.valueOf(String) are used. + * + * @param key The property key + * @param defaultValue The default value to be returned if the property does not exist + * @return The value of the property expressed as a boolean, or false if it does not exist. + * @see org.onap.appc.configuration.Configuration#getBooleanProperty(java.lang.String, boolean) + */ + @Override + public boolean getBooleanProperty(String key, boolean defaultValue) { + if (isPropertyDefined(key)) { + return getBooleanProperty(key); + } + return defaultValue; + } + + /** + * Returns the indicated property value expressed as a floating point double-precision value (double). + * + * @param key The property to retrieve + * @return The value of the property, or 0.0 if not found + * @see org.onap.appc.configuration.Configuration#getDoubleProperty(java.lang.String) + */ + @SuppressWarnings("nls") + @Override + public double getDoubleProperty(String key) { + try { + return Double.valueOf(getProperty(key, "0.0")); + } catch (NumberFormatException e) { + return 0.0; + } + } + + /** + * This method is called to obtain a property as a string value + * + * @param key The key of the property + * @param defaultValue The default value to be returned if the property does not exist + * @return The string value, or null if it does not exist. + * @see org.onap.appc.configuration.Configuration#getDoubleProperty(java.lang.String, double) + */ + @Override + public double getDoubleProperty(String key, double defaultValue) { + if (isPropertyDefined(key)) { + return getDoubleProperty(key); + } + return defaultValue; + } + + /** + * Returns the property indicated expressed as an integer. The standard rules for + * {@link Integer#parseInt(String, int)} using a radix of 10 are used. + * + * @param key The property name to retrieve. + * @return The value of the property, or 0 if it does not exist or is invalid. + * @see org.onap.appc.configuration.Configuration#getIntegerProperty(java.lang.String) + */ + @SuppressWarnings("nls") + @Override + public int getIntegerProperty(String key) { + try { + return Integer.parseInt(getProperty(key, "0"), 10); + } catch (NumberFormatException e) { + return 0; + } + } + + /** + * Returns the property indicated expressed as an integer. The standard rules for Integer.parseInt(String, int) + * using a radix of 10 are used. + * + * @param key The property name to retrieve. + * @param defaultValue The default value to be returned if the property does not exist + * @return The value of the property, or 0 if it does not exist or is invalid. + * @see org.onap.appc.configuration.Configuration#getIntegerProperty(java.lang.String, int) + */ + @Override + public int getIntegerProperty(String key, int defaultValue) { + if (isPropertyDefined(key)) { + return getIntegerProperty(key); + } + return defaultValue; + } + + /** + * Returns the specified property as a long integer value, if it exists, or zero if it does not. + * + * @param key The key of the property desired. + * @return The value of the property expressed as an integer long value, or zero if the property does not exist or + * is not a valid integer long. + * @see org.onap.appc.configuration.Configuration#getLongProperty(java.lang.String) + */ + @SuppressWarnings("nls") + @Override + public long getLongProperty(String key) { + try { + return Long.parseLong(getProperty(key, "0"), 10); + } catch (NumberFormatException e) { + return 0; + } + } + + /** + * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist + * or is invalid. + * + * @param key The key of the property desired. + * @param defaultValue the value to be returned if the property is not valid or does not exist. + * @return The value of the property expressed as an integer long value, or the default value if the property does + * not exist or is not a valid integer long. + * @see org.onap.appc.configuration.Configuration#getLongProperty(java.lang.String, long) + */ + @Override + public long getLongProperty(String key, long defaultValue) { + if (isPropertyDefined(key)) { + return getLongProperty(key); + } + return defaultValue; + } + + /** + * This method can be called to retrieve a properties object that is immutable. Any attempt to modify the properties + * object returned will result in an exception. This allows a caller to view the current configuration as a set of + * properties. + * + * @return An unmodifiable properties object. + * @see org.onap.appc.configuration.Configuration#getProperties() + */ + @Override + public Properties getProperties() { + return new UnmodifiableProperties(properties); + } + + /** + * This method is called to obtain a property as a string value + * + * @param key The key of the property + * @return The string value, or null if it does not exist. + */ + @Override + public String getProperty(String key) { + String value = properties.getProperty(key); + if (value == null) { + return null; + } + return expandVariables(value.trim()); + } + + /** + * This method is called to obtain a property as a string value + * + * @param key The key of the property + * @param defaultValue The default value to be returned if the property does not exist + * @return The string value, or null if it does not exist. + * @see org.onap.appc.configuration.Configuration#getProperty(java.lang.String, java.lang.String) + */ + @Override + public String getProperty(String key, String defaultValue) { + if (isPropertyDefined(key)) { + return getProperty(key); + } + + if (defaultValue == null) { + return null; + } + + return expandVariables(defaultValue.trim()); + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return properties == null ? 0 : properties.hashCode(); + } + + /** + * Returns true if the named property is defined, false otherwise. + * + * @param key The key of the property we are interested in + * @return True if the property exists. + */ + @Override + public boolean isPropertyDefined(String key) { + return properties.containsKey(key); + } + + /** + * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only + * if it has the value "true" or "false" (ignoring case). + * + * @param key The property to be checked + * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string + * @see org.onap.appc.configuration.Configuration#isValidBoolean(java.lang.String) + */ + @SuppressWarnings("nls") + @Override + public boolean isValidBoolean(String key) { + String value = getProperty(key); + if (value != null) { + value = value.toLowerCase(); + return value.matches("true|false"); + } + return false; + } + + /** + * Returns an indication if the indicated property represents a valid double-precision floating point number. + * + * @param key The property to be examined + * @return True if the property is a valid representation of a double, or false if it does not exist or contains + * illegal characters. + * @see org.onap.appc.configuration.Configuration#isValidDouble(java.lang.String) + */ + @Override + public boolean isValidDouble(String key) { + String value = getProperty(key); + if (value != null) { + try { + Double.valueOf(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } + return false; + } + + /** + * Returns an indication if the property is a valid integer value or not. + * + * @param key The key of the property to check + * @return True if the value is a valid integer string, or false if it does not exist or contains illegal + * characters. + * @see org.onap.appc.configuration.Configuration#isValidInteger(java.lang.String) + */ + @Override + public boolean isValidInteger(String key) { + String value = getProperty(key); + if (value != null) { + try { + Integer.parseInt(value.trim(), 10); + return true; + } catch (NumberFormatException e) { + return false; + } + } + return false; + } + + /** + * Determines is the specified property exists and is a valid representation of an integer long value. + * + * @param key The property to be checked + * @return True if the property is a valid representation of an integer long value, and false if it either does not + * exist or is not valid. + * @see org.onap.appc.configuration.Configuration#isValidLong(java.lang.String) + */ + @Override + public boolean isValidLong(String key) { + String value = getProperty(key); + if (value != null) { + try { + Long.parseLong(value.trim(), 10); + return true; + } catch (NumberFormatException e) { + return false; + } + } + return false; + } + + /** + * This method allows an implementation to load configuration properties that may override default values. + * + * @param is An input stream that contains the properties to be loaded + */ + public void setProperties(InputStream is) { + try { + properties.load(is); + } catch (IOException e) { + logger.warn("setProperties with inputStream got exception", e); + } + } + + /** + * This method allows an implementation to load configuration properties that may override default values. + * + * @param props An optional Properties object to be merged into the configuration, replacing any same-named + * properties. + * @see org.onap.appc.configuration.Configuration#setProperties(java.util.Properties) + */ + @Override + public void setProperties(Properties props) { + properties.putAll(props); + decryptAllProperties(); + } + + /** + * This method allows a caller to insert a new property definition into the configuration object. This allows the + * application to adjust or add to the current configuration. If the property already exists, it is replaced with + * the new value. + * + * @param key The key of the property to be defined + * @param value The value of the property to be defined + * @see org.onap.appc.configuration.Configuration#setProperty(java.lang.String, java.lang.String) + */ + @Override + public void setProperty(String key, String value) { + properties.setProperty(key, decrypt(value)); + } + + /** + * @see java.lang.Object#toString() + */ + @SuppressWarnings("nls") + @Override + public String toString() { + return String.format("Configuration: %d properties, keys:[%s]", + properties.size(), properties.keySet().toString()); + } + + /** + * This is a helper method to read the manifest of the jar file that this class was loaded from. Note that this will + * only work if the code is packaged in a jar file. If it is an open deployment, such as under eclipse, this will + * not work and there is code added to detect that case. + * + * @return The manifest object from the jar file, or null if the code is not packaged in a jar file. + */ + @SuppressWarnings({ + "unused", "nls" + }) + private Manifest getManifest() { + ProtectionDomain domain = getClass().getProtectionDomain(); + CodeSource source = domain.getCodeSource(); + URL location = source.getLocation(); + String path = location.getPath(); + int index = path.indexOf('!'); + if (index != -1) { + path = path.substring(0, index); + } + if (path.endsWith(".jar")) { + try (JarFile jar = new JarFile(location.getFile())) { + return jar.getManifest(); + } catch (IOException e) { + logger.error("getManifest", e); + } + } + + return null; + } +} diff --git a/appc-common/src/main/java/org/onap/appc/configuration/package.html b/appc-common/src/main/java/org/onap/appc/configuration/package.html new file mode 100644 index 000000000..c6889da9a --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/configuration/package.html @@ -0,0 +1,174 @@ + + + + +Configuration + + + +

+ CDP Configuration support is provided by a common framework to load + and manage configuration properties from multiple sources. The basic + concept is to load a set of default properties from a known resource + file located on the class path, and then override these defaults + with optional settings that can be provided by a user through either + additional property files or via the command line (as VM arguments). + The loading of defaults from a resource property file (named com/att/cdp/default.properties) + ensures that values are defined for properties the application needs + in order to operate. +

+

+ One of these default values that can be set is the name of the + property file that allows the user to supply settings, as well as + the path where the file can be found. In general, the default name + of the property file will be "cdp.properties", + and the path that will be searched is "${user.home};etc;../etc". + However, these values can be changed through the use of the + default.properties resource file. The property that specifies the + property file name is named com.att.cdp.bootstrap.file, + while the property named com.att.cdp.bootstrap.path + specifies the search path. +

+

+ After the default.properties are loaded, but prior to searching for + the application configuration file, the configuration factory checks + for properties com.att.cdp.bootstrap.path and com.att.cdp.bootstrap.file + in the System properties object (meaning they were set by the + command line). If these values are defined in the system properties + object, they are used. If not, these values are obtained from the + default properties just loaded. This allows the specification of + either the file name or path, or both, to be overridden during start + up by using command-line arguments. +

+

The search path is scanned for the + first occurrence of the specified property file. The first + occurrence is loaded and scanning is stopped at that point. The + configuration factory does not load all occurrences it finds, only + the first occurrence it finds.

+

The configuration properties are + loaded and processed according to a defined precedence order, such + that properties defined with a higher precedence override the same + property at a lower precedence. The precedence order is defined as + follows:

+

Precedence Order

+
    +
  1. Default properties are initially loaded into the + configuration. These default properties are the lowest level + precedence, and will be overridden by any properties specified at + higher levels. These are loaded from resources that are packaged + as part of the various application components. Each component + (Server, Coordinator, EPM, or CLI) may have different default + properties. The default properties are loaded from a resource + named com/att/cdp/default.properties. The default + properties can specify the name of the application property file + to be used to configure the application, as well as the path to + search. Additionally, these properties can be supplied via the + command line to override the default settings if needed.

    +
  2. +
  3. The configuration factory allows for the application to + supply an initial properties object to initialize the + configuration. This properties object could be loaded or created + in any way necessary for the application. This is totally up to + the application to define, if it is needed. If no + application-specific property object is supplied, this step is + skipped. If a property object is supplied, it is used to replace + or set any properties that may have been defined by the defaults.
    +
    +
  4. +
  5. The configuration factory will then search for a bootstrap + file on a bootstrap path. The actual bootstrap file name and path + can be specified as properties on the command line, or will + default to a file name of cdp.properties and a + path of ${user.home};etc;../etc. If desired, the + user can specify the exact name of the property file to be loaded + as well as the path using -Dcom.att.cdp.bootstrap.file=<filename> + and -Dcom.att.cdp.bootstrap.path=<path>. + These properties are set to default values by the default + properties loaded in step #1 above. The first occurrence of a + property file is the file loaded and used. Any other occurrences + are not processed.

    +
  6. +
  7. The System properties are then merged into the + configuration. This allows the highest level of precedence, + command-line VM arguments (-Dname=value) to be + merged into the configuration property object. These settings + override all lower level settings of the same name, as well as + merge all system properties into the configuration object. +
  8. +
+

Variables

+

+ The configuration support allows for variables to be inserted into + any property that is defined. Variables are named using the format ${name}, + where the "name" is the name of a property that is defined + in the configuration, or a system property (such as user.home). + Variables can nest, such that a variable can be replaced with + another variable, which is then reevaluated to obtain the value. + This allows for indirection as well as variable substitution, if + needed. +

+

Using the Configuration Support

+

+ The configuration support was designed to be easy to use. The + configuration implementation is abstracted away from the application + so that it could be changed easily in the future if needed, or if we + needed to load different implementations for different reasons. This + means that the application always accesses the configuration through + an interface, named Configuration. The + implementation of that configuration interface is obtained by a + static method on the ConfigurationFactory class. + The configuration factory will both create the configuration if not + already created on the first access, as well as return the current + configuration if already created. Additionally, the + ConfigurationFactory provides mechanisms to recreate the + configuration after the application is initialized should the need + arise to update its configuration. +

+

An example of the code needed to + obtain access to the configuration is:

+
Configuration config = ConfigurationFactory.getConfiguration();
+

Please refer to the javadoc or the + source code in cdp-common for other ways that the configuration and + configuration factory can be used.

+

Reloading Properties

+

The configuration support allows + for properties to be re-loaded and re-evaluated after the + application is running. This is designed to allow a configuration to + be refreshed should the need arise. This could allow on-demand + refresh (via a command, for example), or automatically based on + sensing a change in the configuration file.

+

+ When the ConfigurationFactory method getConfiguration(Properties) + is called, the current configuration is cleared and rebuilt using + the process defined above. The supplied property object is used in + step #2 of the process. While the properties are being re-built, no + access to the properties are allowed. Any attempt to access + properties while the re-build operation is in effect will block the + caller until completed. This is accomplished using read and write + shared locks. +

+ + +>>>>>>> app-controller/master:appc-common/src/main/java/org/onap/appc/configuration/package.html diff --git a/appc-common/src/main/java/org/onap/appc/encryption/EncryptionException.java b/appc-common/src/main/java/org/onap/appc/encryption/EncryptionException.java new file mode 100644 index 000000000..519933598 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/encryption/EncryptionException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryption; + +public class EncryptionException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 8259594446628138378L; + + public EncryptionException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/encryption/EncryptionTool.java b/appc-common/src/main/java/org/onap/appc/encryption/EncryptionTool.java new file mode 100644 index 000000000..5d6d7ab33 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/encryption/EncryptionTool.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryption; + +import java.security.Provider; +import java.security.Provider.Service; +import java.security.Security; + +import javax.crypto.Cipher; + +import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; +import org.jasypt.util.text.BasicTextEncryptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is used to encapsulate the encryption and decryption support in one place and to provide a utility to + * encrypt and decrypt data. + */ +public class EncryptionTool { + + /** + * This lock object is used ONLY if the singleton has not been set up. + */ + private static final Object lock = new Object(); + + /** + * The salt is used to initialize the PBE (password Based Encrpytion) algorithm. + */ + private static final byte[] DEFAULT_SALT = { + (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 + }; + + /** + * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt + * it + */ + @SuppressWarnings("nls") + public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; + + /** + * The instance of the encryption utility object + */ + private static EncryptionTool instance = null; + + /** + * The iteration count used to initialize the PBE algorithm and to generate the key spec + */ + private static final int ITERATION_COUNT = 20; + + /** + * The logger for this class. + */ + private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); + + /** + * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a + * symmetrical cipher. + */ + private static char[] secret = { + 'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', '/', '%', 'Y', '\\', 'f', + 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w', + 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V' + }; + + /** + * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 + * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. + */ + @SuppressWarnings("nls") + private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; + + /** + * The decryption cipher object + */ + private Cipher decryptCipher = null; + + /** + * The encryption cipher object + */ + private Cipher encryptCipher = null; + + private BasicTextEncryptor encryptor; + + /** + * Get an instance of the EncryptionTool + * + * @return The encryption tool to be used + */ + public static final EncryptionTool getInstance() { + if (instance == null) { + synchronized (lock) { + if (instance == null) { + instance = new EncryptionTool(); + } + } + } + return instance; + } + + /** + * Create the EncryptionTool instance + */ + @SuppressWarnings("nls") + private EncryptionTool() { + String out = "Found the following security algorithms:"; + for (Provider p : Security.getProviders()) { + for (Service s : p.getServices()) { + String algo = s.getAlgorithm(); + out += + String.format("\n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), + s.getClassName()); + } + } + LOG.debug(out); + } + + /** + * Decrypt the provided encrypted text + * + * @param cipherText + * THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is. + * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted. + */ + @SuppressWarnings("nls") + public synchronized String decrypt(String cipherText) { + if (isEncrypted(cipherText)) { + String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); + byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); + byte[] decryptByte = xorWithSecret(plainByte); + return new String(decryptByte); + } else { + return cipherText; + } + + } + + /** + * Encrypt the provided clear text + * + * @param clearText + * The clear text to be encrypted + * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned. + * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the + * clear text is encrypted and returned. + */ + @SuppressWarnings("nls") + public synchronized String encrypt(String clearText) { + if (clearText != null) { + byte[] encByte = xorWithSecret(clearText.getBytes()); + String encryptedValue = new String(Base64.encodeBase64(encByte)); + return ENCRYPTED_VALUE_PREFIX + encryptedValue; + } else { + return null; + } + } + + /** + * Is a value encrypted? A value is considered to be encrypted if it begins with the + * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. + * + * @param value + * the value to check. + * @return true/false; + */ + private static boolean isEncrypted(final String value) { + return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); + } + + /** + * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer + * and returns a byte array the same size as input + * + * @param inp + * The byte array to be XORed with secret + * @return A byte array the same size as inp or null if input is null. + */ + private byte[] xorWithSecret(byte[] inp) { + if (inp == null) { + return null; + } + + byte[] secretBytes = new String(secret).getBytes(); + int size = inp.length; + + byte[] out = new byte[size]; + for (int i = 0; i < size; i++) { + out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); + } + return out; + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/encryption/HexHelper.java b/appc-common/src/main/java/org/onap/appc/encryption/HexHelper.java new file mode 100644 index 000000000..250a17efb --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/encryption/HexHelper.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryption; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * HexHelper utility used for encryption/decryption + */ +public final class HexHelper { + + @SuppressWarnings({ + "javadoc", "nls" + }) + public static final String CM_PATH = "@(#) [viewpath]/[item]"; + + @SuppressWarnings({ + "nls", "javadoc" + }) + public static final String CM_PROJECT = "@(#) [environment] [baseline]"; + + @SuppressWarnings({ + "javadoc", "nls" + }) + public static final String CM_VERSION = "@(#) [version] [crtime]"; + + private static final char[] HEX_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', + 'E', 'F' }; + + /** + * The logger for this class. + */ + private static final Logger LOG = LoggerFactory.getLogger(HexHelper.class); + + private static Map TextToHex; + + static { + TextToHex = new HashMap<>(); + TextToHex.put(Character.valueOf('0'), Integer.valueOf(0)); + TextToHex.put(Character.valueOf('1'), Integer.valueOf(1)); + TextToHex.put(Character.valueOf('2'), Integer.valueOf(2)); + TextToHex.put(Character.valueOf('3'), Integer.valueOf(3)); + TextToHex.put(Character.valueOf('4'), Integer.valueOf(4)); + TextToHex.put(Character.valueOf('5'), Integer.valueOf(5)); + TextToHex.put(Character.valueOf('6'), Integer.valueOf(6)); + TextToHex.put(Character.valueOf('7'), Integer.valueOf(7)); + TextToHex.put(Character.valueOf('8'), Integer.valueOf(8)); + TextToHex.put(Character.valueOf('9'), Integer.valueOf(9)); + TextToHex.put(Character.valueOf('A'), Integer.valueOf(10)); + TextToHex.put(Character.valueOf('B'), Integer.valueOf(11)); + TextToHex.put(Character.valueOf('C'), Integer.valueOf(12)); + TextToHex.put(Character.valueOf('D'), Integer.valueOf(13)); + TextToHex.put(Character.valueOf('E'), Integer.valueOf(14)); + TextToHex.put(Character.valueOf('F'), Integer.valueOf(15)); + } + + /** + * Default private constructor prevents instantiation + */ + private HexHelper() { + // no-op + } + + /** + * Converts an array of bytes to the equivalent string representation using hexadecimal notation and returning that + * representation in a StringBuffer. + * + * @param bytes + * The bytes to be converted to a hexadecimal string + * @return The string representation + */ + public static StringBuffer convertBytesToHexSB(byte[] bytes) { + StringBuffer sb = new StringBuffer(bytes.length * 2); + int byteLen = bytes.length; + for (int index = 0; index < byteLen; index++) { + char tempChar; + // Get the first 4 bits (high) Do bitwise logical AND to get rid of + // low nibble. Shift results to right by 4 and get char + // representation + tempChar = HEX_TABLE[((bytes[index] & 0xf0) >>> 4)]; + sb.append(tempChar); + + // Get the last 4 bits (low) Do bitwise logical AND to get rid of + // high nibble. Get char representation + tempChar = HEX_TABLE[(bytes[index] & 0x0f)]; + sb.append(tempChar); + } + return sb; + } + + /** + * Converts a hexadecimal string representation of a binary value to an array of bytes + * + * @param hexValue + * The hex representation string to be converted + * @return The array of bytes that contains the binary value + */ + @SuppressWarnings("nls") + public static byte[] convertHexToBytes(String hexValue) { + byte[] bytes = null; + byte high; + byte low; + char hexChar; + + StringBuffer buffer = new StringBuffer(hexValue.toUpperCase()); + if (buffer.length() % 2 != 0) { + LOG.warn("Invalid HEX value length. " + + "The length of the value has to be a multiple of 2. Prepending '0' value."); + buffer.insert(0, '0'); + } + int hexLength = buffer.length(); + int byteLength = hexLength / 2; + + bytes = new byte[byteLength]; + for (int index = 0; index < hexLength; index += 2) { + hexChar = buffer.charAt(index); + high = (TextToHex.get(Character.valueOf(hexChar))).byteValue(); + high = (byte) (high << 4); + hexChar = buffer.charAt(index + 1); + low = (TextToHex.get(Character.valueOf(hexChar))).byteValue(); + high = (byte) (high | low); + bytes[index / 2] = high; + } + return bytes; + } +} diff --git a/appc-common/src/main/java/org/onap/appc/exceptions/APPCException.java b/appc-common/src/main/java/org/onap/appc/exceptions/APPCException.java new file mode 100644 index 000000000..0efed763c --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/exceptions/APPCException.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +/** + * This is a base class for all APPC defined exceptions. + */ + +public class APPCException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be + * initialized by a call to initCause. + */ + public APPCException() { + } + + /** + * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently + * be initialized by a call to initCause. + * + * @param message + * the detail message. The detail message is saved for later retrieval by the getMessage() method. + */ + public APPCException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified cause and a detail message of (cause==null ? null : + * cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for example, + * java.security.PrivilegedActionException). + * + * @param cause + * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + */ + public APPCException(Throwable cause) { + super(cause); + } + + /** + * + Constructs a new exception with the specified detail message and cause. + *

+ * Note that the detail message associated with cause is not automatically incorporated in this exception's detail + * message. + *

+ * + * @param message + * the detail message (which is saved for later retrieval by the getMessage() method). + * @param cause + * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + */ + public APPCException(String message, Throwable cause) { + super(message, cause); + } + + /** + * + Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and + * writable stack trace enabled or disabled. + * + * @param message + * the detail message. + * @param cause + * the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression + * whether or not suppression is enabled or disabled + * @param writableStackTrace + * whether or not the stack trace should be writable + */ + public APPCException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/exceptions/InvalidInputException.java b/appc-common/src/main/java/org/onap/appc/exceptions/InvalidInputException.java new file mode 100644 index 000000000..4a82ba83b --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/exceptions/InvalidInputException.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +public class InvalidInputException extends Exception { + public InvalidInputException(String message){ + super(message); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/exceptions/InvalidStateException.java b/appc-common/src/main/java/org/onap/appc/exceptions/InvalidStateException.java new file mode 100644 index 000000000..d29b93117 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/exceptions/InvalidStateException.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +public class InvalidStateException extends Exception { + public InvalidStateException(String message) { + super(message); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/exceptions/UnknownProviderException.java b/appc-common/src/main/java/org/onap/appc/exceptions/UnknownProviderException.java new file mode 100644 index 000000000..89b29e652 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/exceptions/UnknownProviderException.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +/** + * This exception indicates that the named provider could not be found or was unidentifiable. + */ +public class UnknownProviderException extends APPCException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be + * initialized by a call to initCause. + */ + public UnknownProviderException() { + } + + /** + * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently + * be initialized by a call to initCause. + * + * @param message + * the detail message. The detail message is saved for later retrieval by the getMessage() method. + */ + public UnknownProviderException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified cause and a detail message of (cause==null ? null : + * cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for example, + * java.security.PrivilegedActionException). + * + * @param cause + * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + */ + public UnknownProviderException(Throwable cause) { + super(cause); + } + + /** + * + Constructs a new exception with the specified detail message and cause. + *

+ * Note that the detail message associated with cause is not automatically incorporated in this exception's detail + * message. + *

+ * + * @param message + * the detail message (which is saved for later retrieval by the getMessage() method). + * @param cause + * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + */ + public UnknownProviderException(String message, Throwable cause) { + super(message, cause); + } + + /** + * + Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and + * writable stack trace enabled or disabled. + * + * @param message + * the detail message. + * @param cause + * the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression + * whether or not suppression is enabled or disabled + * @param writableStackTrace + * whether or not the stack trace should be writable + */ + public UnknownProviderException(String message, + Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/i18n/Msg.java b/appc-common/src/main/java/org/onap/appc/i18n/Msg.java new file mode 100644 index 000000000..b6a0657a0 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/i18n/Msg.java @@ -0,0 +1,824 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.i18n; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * The messages issued by APPC components. + *

+ * This message definition is shared by all APPC components. + *

+ * + */ +@SuppressWarnings("nls") +public enum Msg implements EELFResolvableErrorEnum { + + /** + * ECOMP Application Controller (APP-C) initialization started at {0} + */ + CONFIGURATION_STARTED, + + /** + * Prior configuration has been cleared + */ + CONFIGURATION_CLEARED, + + /** + * Loading configuration properties from file "{0}" + */ + LOADING_CONFIGURATION_OVERRIDES, + + /** + * Configuration defaults loaded from resource file "{0}" + */ + LOADING_DEFAULTS, + + /** + * No default property resource "{0}" was found! + */ + NO_DEFAULTS_FOUND, + + /** + * Property "{0}" ="{1}" + */ + PROPERTY_VALUE, + + /** + * No configuration file named [{0}] was found on the configuration search path [{1}]. \ If a configuration file + * should have been loaded, check the file name and search path specified. CDP will proceed using the \ default + * values and command-line overrides (if any). + */ + NO_OVERRIDE_PROPERTY_FILE_LOADED, + + /** + * Searching path "{0}" for configuration settings "{1}" + */ + SEARCHING_CONFIGURATION_OVERRIDES, + + /** + * Loading application-specific override properties + */ + LOADING_APPLICATION_OVERRIDES, + + /** + * No application-specific override properties were provided! + */ + NO_APPLICATION_OVERRIDES, + + /** + * Merging system properties into configuration + */ + MERGING_SYSTEM_PROPERTIES, + + /** + * Setting property "{0}={1}" in system properties + */ + SETTING_SPECIAL_PROPERTY, + + /** + * Loading resource bundle "{0}" + */ + LOADING_RESOURCE_BUNDLE, + + /** + * Logging has already been initialized, check the container logging definitions to ensure they represent your + * desired logging configuration. + */ + LOGGING_ALREADY_INITIALIZED, + + /** + * Searching path "{0}" for log configuration file "{1}" + */ + SEARCHING_LOG_CONFIGURATION, + + /** + * Loading default logging configuration from system resource file "{0}" + */ + LOADING_DEFAULT_LOG_CONFIGURATION, + + /** + * No log configuration could be found or defaulted! + */ + NO_LOG_CONFIGURATION, + + /** + * An unsupported logging framework is bound to SLF4J. Only Logback or Log4J are supported. + */ + UNSUPPORTED_LOGGING_FRAMEWORK, + + /** + * Loading logging configuration from file "{0}" + */ + LOADING_LOG_CONFIGURATION, + + /** + * Provider {0} cannot be found or cannot be resolved to a valid provider. + */ + UNKNOWN_PROVIDER, + + /** + * Server name "{0}" with id "{1}" in tenant "{2}" and region "{3}" did not change state within the alloted time. + * Current state is "{4}" and the desired state(s) are "{5}" + */ + SERVER_STATE_CHANGE_TIMEOUT, + + /** + * Server name "{0}" with id "{1}" in tenant "{2}" has a state of deleted and cannot be {3}. + */ + SERVER_DELETED, + + /** + * Server name "{0}" with id "{1}" in tenant "{2}" has an unknown state of "{3}". + */ + UNKNOWN_SERVER_STATE, + + /** + * {0} component {1} is being initialized... + */ + COMPONENT_INITIALIZING, + + /** + * {0} component {1} has completed initialization + */ + COMPONENT_INITIALIZED, + + /** + * {0} component {1} is terminating... + */ + COMPONENT_TERMINATING, + + /** + * {0} component {1} has terminated + */ + COMPONENT_TERMINATED, + + /** + * Operation {0} is not supported or implemented at this time. + */ + IAAS_ADAPTER_UNSUPPORTED_OPERATION, + + /** + * Operation {0} called. Input document:\n{1} + */ + IAAS_ADAPTER_RPC_CALLED, + + /** + * Unable to locate the {0} service in the OSGi container + */ + NO_SERVICE_FOUND, + + /** + * Dump of context parameters for module {0}, RPC {1}, and version {2} + */ + CONTEXT_PARAMETERS_DISPLAY, + + /** + * Response properties from execution of module '{0}', RPC '{1}', and version '{2}' are: + */ + RESPONSE_PARAMETERS_DISPLAY, + + /** + * Service {0}:{1} was provided a null (empty) or invalid argument, '{2}' = '{3}' + */ + NULL_OR_INVALID_ARGUMENT, + + /** + * Service {0}:{1} is processing service '{2}' with request id '{3}' + */ + PROCESSING_REQUEST, + + /** + * Service {0}:{1} received request for service '{2}' but that service is invalid or unknown. + */ + INVALID_SERVICE_REQUEST, + + /** + * {0} registering service {1} using class {2} + */ + REGISTERING_SERVICE, + + /** + * {0} unregistering service {1} + */ + UNREGISTERING_SERVICE, + + /** + * {0} IAAS Adapter initializing provider {1} as {2} + */ + LOADING_PROVIDER_DEFINITIONS, + + /** + * {0} IAAS Adapter restart of server requested + */ + RESTARTING_SERVER, + + /** + * {0} IAAS Adapter rebuild of server requested + */ + REBUILDING_SERVER, + + /** + * {0} IAAS Adapter migrate of server requested + */ + MIGRATING_SERVER, + + /** + * {0} IAAS Adapter evacuate of server requested + */ + EVACUATING_SERVER, + + /** + * {0} IAAS Adapter create snapshot of server requested + */ + SNAPSHOTING_SERVER, + + /** + * {0} IAAS Adapter look for server requested + */ + LOOKING_SERVER_UP, + + /** + * {0} IAAS Adapter cannot perform requested service, VM url '{1}' is invalid + */ + INVALID_SELF_LINK_URL, + + /** + * Located server '{0}' on tenant '{1}' and in state '{2}' + */ + SERVER_FOUND, + + /** + * No server found in provider with self-link URL [{0}] + */ + SERVER_NOT_FOUND, + + /** + * Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}] + */ + SERVER_OPERATION_EXCEPTION, + + /** + * One or more properties for [{0}] are missing, null, or empty. They are: + */ + MISSING_REQUIRED_PROPERTIES, + + /** + * The server [{0}] (id={1}) in tenant {2} is in error state, {3} is not allowed + */ + SERVER_ERROR_STATE, + + /** + * The image {0} could not be located for {1} + */ + IMAGE_NOT_FOUND, + + /** + * Time out waiting for {0} with name {1} (and id {2}) to reach one of {3} states, current state is {4} + */ + STATE_CHANGE_TIMEOUT, + + /** + * Exception {0} waiting for {1} with name {2} (and id {3}) to reach one of {4} states, current state is {5} + * cause={6} + */ + STATE_CHANGE_EXCEPTION, + + /** + * Server {0} is being stopped... + */ + STOP_SERVER, + + /** + * Server {0} is being started... + */ + START_SERVER, + + /** + * Server {0} is being resumed... + */ + RESUME_SERVER, + + /** + * Server {0} is being unpaused... + */ + UNPAUSE_SERVER, + + /** + * Server {0} is being rebuilt... + */ + REBUILD_SERVER, + + /** + * Connection to provider {0} at identity {1} using tenant name {2} (id {3}) failed, reason={4}, retrying in {5} + * seconds, attempt {6} of {7}. + */ + CONNECTION_FAILED_RETRY, + + /** + * Connection to provider {0} at service {1} failed after all retry attempts. + */ + CONNECTION_FAILED, + + /** + * {0} IAAS Adapter stop server requested + */ + STOPPING_SERVER, + + /** + * {0} IAAS Adapter start server requested + */ + STARTING_SERVER, + + /** + * Server {0} (id {1}) failed to rebuild, reason {2} + */ + REBUILD_SERVER_FAILED, + + /** + * Application {0} graph {1} response did not set the {2} parameter. This parameter is required for synchronization + * with the controller. Absence of this parameter is assumed to be a failure. Please correct the DG. + */ + PARAMETER_IS_MISSING, + + /** + * Application {0} graph {1} did not set parameter {2} to a valid numeric value ({3}). Please correct the DG. + */ + PARAMETER_NOT_NUMERIC, + + /** + * Application {0} graph {1} completed with failure: error code = {2}, message = {3} + */ + DG_FAILED_RESPONSE, + + /** + * Application {0} received exception {1} attempting to call graph {2}, exception message = {3} + */ + EXCEPTION_CALLING_DG, + + /** + * Application {0} was unable to locate graph {1} + */ + GRAPH_NOT_FOUND, + + /** + * Application {0} graph {1} responded with {3} properties + */ + DEBUG_GRAPH_RESPONSE_HEADER, + + /** + * {0}:{1} - {2} = {3} + */ + DEBUG_GRAPH_RESPONSE_DETAIL, + + /** + * Application {0} request {1} was supplied a property '{2}' with the value '{3}' that does not meet the required + * form(s): + */ + INVALID_REQUIRED_PROPERTY, + + /** + * Server {0} (id {1}) failed to migrate during {2} phase, reason {3} + */ + MIGRATE_SERVER_FAILED, + + /** + * Server {0} (id {1}) failed to evacuate, reason {2} + */ + EVACUATE_SERVER_FAILED, + + /** + * Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3} + */ + EVACUATE_SERVER_REBUILD_FAILED, + + /** + * APP-C instance is too busy + */ + APPC_TOO_BUSY, + + /** + * Concurrent access to server "{0}" + */ + VF_SERVER_BUSY, + + /** + * Server "{0}" does not support command "{1}" in the current state "{2}" + */ + VF_ILLEGAL_COMMAND, + + /** + * Server "{0}" cannot handle command "{1}" because of its doubtful state + */ + VF_UNDEFINED_STATE, + + /** + * No resource found with ID "{0}" in A&AI system + */ + APPC_NO_RESOURCE_FOUND, + + /** + * The request "{0}" for server "{1}" has exceeded its TTL limit of "{3}" seconds + */ + APPC_EXPIRED_REQUEST, + + /** + * Workflow for vnfType = "{0}" and command = "{1}" not found. + */ + APPC_WORKFLOW_NOT_FOUND, + + /** + * Null vnfId and command provided + */ + APPC_INVALID_INPUT, + + /** + * Operation '{0}' for VNF type '{1}' from Source '{2}' with RequestID '{3}' was started at '{4}' and ended at '{5}' + * with status code '{6}' + */ + APPC_AUDIT_MSG, + + /** + * APP-C is unable to communicate with A&AI + */ + AAI_CONNECTION_FAILED, + + /** + * APP-C is unable to update COMPONENT_ID {0} to {1} for reason {2} + */ + AAI_UPDATE_FAILED, + + /** + * APP-C is unable to retrieve VF/VFC {0} data for Transaction ID{1}as a result of A&AI communication failure or its + * internal error. + */ + AAI_GET_DATA_FAILED, + + /** + * A&AI at identity {0} using VNF_ID {1} failed, reason={2}, retrying in {3} seconds, attempt {4} of {5} + */ + AAI_CONNECTION_FAILED_RETRY, + + /** + * APP-C is unable to delete COMPONENT_ID {0} for reason {1} + */ + AAI_DELETE_FAILED, + + /** + * APP-C is unable to query AAI for VNF_ID {0} + */ + AAI_QUERY_FAILED, + + /** + * VNF {0} is configured + */ + VNF_CONFIGURED, + + /** + * VNF {0} is being configured + */ + VNF_CONFIGURATION_STARTED, + + /** + * VNF {0} configuration failed for reason {1} + */ + VNF_CONFIGURATION_FAILED, + + /** + * VNF {0} is being tested + */ + VNF_TEST_STARTED, + + /** + * VNF {0} was tested + */ + VNF_TESTED, + + /** + * VNF {0} test failed for reason {1} + */ + VNF_TEST_FAILED, + + /** + * VNF {0} test failed for reason {1} + */ + VNF_NOT_FOUND, + + /** + * VNF {0} Healthcheck operation failed for reason {1} + */ + VNF_HEALTHCECK_FAILED, + + /** + * VM {0} Healthcheck operation failed for reason {1} + */ + VM_HEALTHCECK_FAILED, + + /** + * Server {0} (id {1}) failed to stop during {2} phase, reason {3} + */ + STOP_SERVER_FAILED, + + /** + * Server {0} (id {1}) failed to terminate during {2} phase, reason {3} + */ + TERMINATE_SERVER_FAILED, + + /** + * {0} IAAS Adapter terminate server requested + */ + TERMINATING_SERVER, + + /** + * Server {0} is being terminated... + */ + TERMINATE_SERVER, + + /** + * Migrate {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... + */ + MIGRATE_COMPLETE, + + /** + * Restart {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... + */ + RESTART_COMPLETE, + + /** + * Rebuild {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... + */ + REBUILD_COMPLETE, + + /** + * Located stack '{0}' on tenant '{1}' and in state '{2}' + */ + STACK_FOUND, + + /** + * {0} IAAS Adapter terminate stack requested + */ + + TERMINATING_STACK, + + /** + * stack {0} is being terminated... + */ + TERMINATE_STACK, + /** + * No stack found in provider with self-link URL [{0}] + */ + + STACK_NOT_FOUND, + + /** + * Exception {0} was caught attempting {1} of stack [{2}] on tenant [{3}] + */ + STACK_OPERATION_EXCEPTION, + + /** + * Stack {0} (id {1}) failed to terminate during {2} phase, reason {3} + */ + + TERMINATE_STACK_FAILED, + + /** + * Exception {0} was caught attempting to close provider context for {1}. + */ + + CLOSE_CONTEXT_FAILED, + + /** + * {0} IAAS Adapter snapshoting stack + */ + SNAPSHOTING_STACK, + + /** + * Stack {0} snapshoted, snapshot ID = [{1}]. + */ + STACK_SNAPSHOTED, + + /** + * {0} IAAS Adapter restoring stack + */ + RESTORING_STACK, + + /** + * Stack {0} is restored to snapshot {1}. + */ + STACK_RESTORED, + + /** + * {0} IAAS Adapter checking server + */ + CHECKING_SERVER, + + /** + * Parameter {0} is missing in svc request of {1}. + */ + MISSING_PARAMETER_IN_REQUEST, + + /** + * Cannot establish connection to server {0} port {1} with user {2}. + */ + CANNOT_ESTABLISH_CONNECTION, + + /** + * Operation '{0}' for VNF type '{1}' from Source '{2}' with RequestID '{3}' on '{4}' with action '{5}' + * ended in {6}ms with result '{7}' + */ + APPC_METRIC_MSG, + + /** + * Parsing failied for{0} + */ + INPUT_PAYLOAD_PARSING_FAILED, + + /** + * Error occurred for due to {0} + */ + APPC_EXCEPTION, + + /** + * SSH Data Exception occurred due to {0} + */ + SSH_DATA_EXCEPTION, + + /** + * Json processing exception occurred due to {0} + */ + JSON_PROCESSING_EXCEPTION, + + /** + * Operation {0} succeed for {1} + */ + SUCCESS_EVENT_MESSAGE, + + /** + * Dependency model not found for VNF type {0} due to {1} + */ + DEPENDENCY_MODEL_NOT_FOUND, + + /** + * Invalid Dependency model for VNF Type {0} due to {1} + */ + INVALID_DEPENDENCY_MODEL, + + /** + * Failed to retrieve VNFC DG + */ + FAILURE_RETRIEVE_VNFC_DG, + + /** + * Network check for Server {0} failed for Port {1} + * + */ + SERVER_NETWORK_ERROR, + + /** + * Hypervisor check for Server {0} failed. Status is DOWN or UNKNOWN + * + */ + HYPERVISOR_DOWN_ERROR, + + /** + * Unable to determine Hypervisor status for Server {0}. failed. + * + */ + HYPERVISOR_STATUS_UKNOWN, + + /** + * Hypervisor Network check for Server {0} failed. Not reachable by APPC + * + */ + HYPERVISOR_NETWORK_ERROR, + + /** + * Restart application operation failed on server : {0}, reason {1} + */ + APPLICATION_RESTART_FAILED, + + /** + * Start application operation failed on server : {0}, reason {1} + */ + APPLICATION_START_FAILED, + + /** + * Start application operation failed on server : {0}, reason {1} + */ + APPLICATION_STOP_FAILED, + + /** + * Application on server {0} is being restarted... + */ + RESTART_APPLICATION, + + /** + * Application on server {0} is being started... + */ + START_APPLICATION, + + /** + * Application on server {0} is being started... + */ + STOP_APPLICATION, + + /** + * APPC LCM operations are disabled + */ + LCM_OPERATIONS_DISABLED, + + /** + * Application {0} received exception {1} while attempting to execute oam operation {2}, exception message = {3}|\ + */ + OAM_OPERATION_EXCEPTION, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_ENTERING_MAINTENANCE_MODE, + + /** + * Application {0} is in {1} + */ + OAM_OPERATION_MAINTENANCE_MODE, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_STARTING, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_STARTED, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_STOPPING, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_STOPPED, + /** + * A {1} API is not allowed when {0} is in the {2} state + */ + INVALID_STATE_TRANSITION, + + /** + * Application {0} was unable to find the Request Handler service + */ + REQUEST_HANDLER_UNAVAILABLE, + + /** + * Application {0} is {1} + */ + OAM_OPERATION_RESTARTING, + + /** + * Application {0} is {1} for restart + */ + OAM_OPERATION_RESTARTED, + + /** + * {0} + */ + OAM_OPERATION_INVALID_INPUT, + + /** + * Unsupported identity service version, unable to retrieve ServiceCatalog + * for identity service {0} + */ + IAAS_UNSUPPORTED_IDENTITY_SERVICE + ; + /* + * Static initializer to ensure the resource bundles for this class are loaded... + */ + static { + EELFResourceManager.loadMessageBundle("org/onap/appc/i18n/MessageResources"); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/logging/LoggingConstants.java b/appc-common/src/main/java/org/onap/appc/logging/LoggingConstants.java new file mode 100644 index 000000000..30ff91d68 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/logging/LoggingConstants.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.logging; + +/** + * Constant definition of logging + */ +public class LoggingConstants { + private LoggingConstants() { + throw new IllegalAccessError("LoggingConstants"); + } + + /** + * Constants of MDC property keys + */ + public static class MDCKeys { + private MDCKeys() { + throw new IllegalAccessError("MDCKeys"); + } + + public static final String ERROR_CODE = "ErrorCode"; + public static final String ERROR_DESCRIPTION = "ErrorDescription"; + public static final String STATUS_CODE = "StatusCode"; + public static final String RESPONSE_CODE = "ResponseCode"; + public static final String RESPONSE_DESCRIPTION = "ResponseDescription"; + public static final String TARGET_ENTITY = "TargetEntity"; + public static final String TARGET_SERVICE_NAME = "TargetServiceName"; + public static final String PARTNER_NAME = "PartnerName"; + public static final String SERVER_NAME = "ServerName"; + public static final String BEGIN_TIMESTAMP = "BeginTimestamp"; + public static final String END_TIMESTAMP = "EndTimestamp"; + public static final String ELAPSED_TIME = "ElapsedTime"; + public static final String CLASS_NAME = "ClassName"; + public static final String TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; + } + + /** + * Constants of status code values + */ + public static class StatusCodes { + private StatusCodes() { + throw new IllegalAccessError("StatusCodes"); + } + public static final String COMPLETE = "COMPLETE"; + public static final String ERROR = "ERROR"; + } + + /** + * Constants of APPC target names + */ + public static class TargetNames { + private TargetNames() { + throw new IllegalAccessError("TargetNames"); + } + public static final String APPC = "APPC"; + public static final String AAI = "A&AI"; + public static final String DB = "DataBase"; + public static final String APPC_PROVIDER = "APPC Provider"; + public static final String APPC_OAM_PROVIDER = "APPC OAM Provider"; + public static final String STATE_MACHINE = "StateMachine"; + public static final String WORKFLOW_MANAGER = "WorkflowManager"; + public static final String REQUEST_VALIDATOR = "RequestValidator"; + public static final String LOCK_MANAGER = "LockManager"; + public static final String REQUEST_HANDLER = "RequestHandler"; + } + + /** + * Constants of targeted service names + */ + public static class TargetServiceNames { + private TargetServiceNames() { + throw new IllegalAccessError("TargetServiceNames"); + } + + /** + * Constants of AAI service names + */ + public static class AAIServiceNames { + private AAIServiceNames() { + throw new IllegalAccessError("AAIServiceNames"); + } + public static final String QUERY = "query"; + public static final String GET_VNF_DATA = "getVnfData"; + } + + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java b/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java new file mode 100644 index 000000000..1e4156e02 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.logging; + +import org.onap.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; +import org.slf4j.MDC; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.TimeZone; + +/** + * Logging utilities + */ +public class LoggingUtils { + + private final static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + private final static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private final static EELFLogger metricLogger = EELFManager.getInstance().getMetricsLogger(); + + private LoggingUtils() { + throw new IllegalAccessError("LoggingUtils"); + } + + public static void logErrorMessage(String errorCode, String errorDescription, String targetEntity, + String targetServiceName, String additionalMessage, String className) { + logError(errorCode, errorDescription, targetEntity, targetServiceName, additionalMessage, className); + } + + public static void logErrorMessage(String targetEntity, String targetServiceName, String additionalMessage, + String className) { + logError("", "", targetEntity, targetServiceName, additionalMessage, className); + } + + public static void logErrorMessage(String targetServiceName, String additionalMessage, String className) { + logError("", "", LoggingConstants.TargetNames.APPC, targetServiceName, + additionalMessage, className); + } + + private static void logError(String errorCode, String errorDescription, String targetEntity, + String targetServiceName, String additionalMessage, String className) { + populateErrorLogContext(errorCode, errorDescription, targetEntity, targetServiceName, className); + errorLogger.error(additionalMessage == null ? "" : additionalMessage); + cleanErrorLogContext(); + } + + public static void logAuditMessage(Instant beginTimeStamp, Instant endTimeStamp, String code, + String responseDescription, String className) { + populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); + auditLogger.info(EELFResourceManager.format(Msg.APPC_AUDIT_MSG, + MDC.get(MDC_SERVICE_NAME), + MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), + MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), + MDC.get(MDC_KEY_REQUEST_ID), + MDC.get(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP), + MDC.get(LoggingConstants.MDCKeys.END_TIMESTAMP), + MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE))); + cleanAuditErrorContext(); + } + + public static void auditInfo(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, + String className,EELFResolvableErrorEnum resourceId, String... arguments) { + populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); + auditLogger.info(resourceId,arguments); + cleanAuditErrorContext(); + } + + public static void auditWarn(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, + String className,EELFResolvableErrorEnum resourceId, String... arguments) { + populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); + auditLogger.warn(resourceId,arguments); + cleanAuditErrorContext(); + } + + + + public static void logMetricsMessage(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, + String targetServiceName, String statusCode, String responseCode, + String responseDescription, String className) { + populateMetricLogContext(beginTimeStamp, endTimeStamp, targetEntity, targetServiceName, statusCode, + responseCode, responseDescription, className); + metricLogger.info(EELFResourceManager.format(Msg.APPC_METRIC_MSG, + MDC.get(MDC_SERVICE_NAME), + MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), + MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), + MDC.get(MDC_KEY_REQUEST_ID), + MDC.get(LoggingConstants.MDCKeys.TARGET_ENTITY), + MDC.get(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME), + MDC.get(LoggingConstants.MDCKeys.ELAPSED_TIME), + MDC.get(LoggingConstants.MDCKeys.STATUS_CODE))); + cleanMetricContext(); + } + + private static void populateAuditLogContext(Instant beginTimeStamp, Instant endTimeStamp, String code, + String responseDescription, String className) { + populateTimeContext(beginTimeStamp, endTimeStamp); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, code); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "100".equals(code) || "400".equals(code) ? + LoggingConstants.StatusCodes.COMPLETE : + LoggingConstants.StatusCodes.ERROR); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + } + + private static void cleanAuditErrorContext() { + cleanTimeContext(); + MDC.remove(LoggingConstants.MDCKeys.STATUS_CODE); + MDC.remove(LoggingConstants.MDCKeys.RESPONSE_CODE); + MDC.remove(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION); + MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); + } + + private static void populateErrorLogContext(String errorCode, String errorDescription, String targetEntity, + String targetServiceName, String className) { + populateErrorContext(errorCode, errorDescription); + populateTargetContext(targetEntity, targetServiceName!=null?targetServiceName:""); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + } + + private static void cleanErrorLogContext() { + cleanErrorContext(); + cleanTargetContext(); + MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); + } + + private static void populateMetricLogContext(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, + String targetServiceName, String statusCode, String responseCode, + String responseDescription, String className) { + populateTimeContext(beginTimeStamp, endTimeStamp); + populateTargetContext(targetEntity, targetServiceName); + populateResponseContext(statusCode, responseCode, responseDescription); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + } + + private static void cleanMetricContext() { + cleanTimeContext(); + cleanTargetContext(); + cleanResponseContext(); + MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); + } + + private static void populateTargetContext(String targetEntity, String targetServiceName) { + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, targetEntity!=null?targetEntity:""); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, targetServiceName!=null?targetServiceName:""); + } + + private static void cleanTargetContext() { + MDC.remove(LoggingConstants.MDCKeys.TARGET_ENTITY); + MDC.remove(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME); + } + + private static void populateTimeContext(Instant beginTimeStamp, Instant endTimeStamp) { + String beginTime = ""; + String endTime = ""; + String elapsedTime = ""; + + if (beginTimeStamp != null && endTimeStamp != null) { + elapsedTime = String.valueOf(ChronoUnit.MILLIS.between(beginTimeStamp, endTimeStamp)); + beginTime = generateTimestampStr(beginTimeStamp); + endTime = generateTimestampStr(endTimeStamp); + } + + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, beginTime); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, endTime); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, elapsedTime); + } + + private static String generateTimestampStr(Instant timeStamp) { + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + TimeZone tz = TimeZone.getTimeZone("UTC"); + df.setTimeZone(tz); + return df.format(Date.from(timeStamp)); + } + + private static void cleanTimeContext() { + MDC.remove(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP); + MDC.remove(LoggingConstants.MDCKeys.END_TIMESTAMP); + MDC.remove(LoggingConstants.MDCKeys.ELAPSED_TIME); + } + + private static void populateResponseContext(String statusCode, String responseCode, String responseDescription) { + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, statusCode!=null?statusCode:""); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, responseCode); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); + } + + private static void cleanResponseContext() { + MDC.remove(LoggingConstants.MDCKeys.STATUS_CODE); + MDC.remove(LoggingConstants.MDCKeys.RESPONSE_CODE); + MDC.remove(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION); + } + + private static void populateErrorContext(String errorCode, String errorDescription) { + MDC.put(LoggingConstants.MDCKeys.ERROR_CODE, errorCode); + MDC.put(LoggingConstants.MDCKeys.ERROR_DESCRIPTION, errorDescription); + } + + private static void cleanErrorContext() { + MDC.remove(LoggingConstants.MDCKeys.ERROR_CODE); + MDC.remove(LoggingConstants.MDCKeys.ERROR_DESCRIPTION); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/metadata/MetadataService.java b/appc-common/src/main/java/org/onap/appc/metadata/MetadataService.java new file mode 100644 index 000000000..29586ea15 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/metadata/MetadataService.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata; + +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + + +public interface MetadataService { + String getVnfModel(DependencyModelIdentifier modelIdentifier); +} diff --git a/appc-common/src/main/java/org/onap/appc/metadata/impl/MetadataServiceImpl.java b/appc-common/src/main/java/org/onap/appc/metadata/impl/MetadataServiceImpl.java new file mode 100644 index 000000000..0321b7e81 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/metadata/impl/MetadataServiceImpl.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +import javax.sql.rowset.CachedRowSet; + +import org.onap.appc.cache.MetadataCache; +import org.onap.appc.cache.impl.MetadataCacheFactory; +import org.onap.appc.metadata.MetadataService; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +import java.sql.SQLException; +import java.util.ArrayList; + + +public class MetadataServiceImpl implements MetadataService { + + private DbLibService dbLibService; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MetadataServiceImpl.class); + + private MetadataCache cache; + + public MetadataServiceImpl(){ + initialize(); + } + + private void initialize(){ + cache = MetadataCacheFactory.getInstance().getMetadataCache(); + // TODO initialze dbLibService + } + + public void setDbLibService(DbLibService dbLibService) { + this.dbLibService = dbLibService; + } + + @Override + public String getVnfModel(DependencyModelIdentifier modelIdentifier) { + logger.debug("Reading Vnf Model data from cache for vnfType : "+ modelIdentifier.getVnfType() +" and catalog version : " +modelIdentifier.getCatalogVersion()); + String vnfModel = cache.getObject(modelIdentifier); + if(vnfModel ==null || vnfModel.length() ==0){ + logger.debug("Vnf Model not available in cache. Reading from database."); + vnfModel = readVnfModel(modelIdentifier); + if(vnfModel !=null && vnfModel.length()>0){ + logger.debug("Adding retrieved Vnf Model to cache."); + addVnfModel(modelIdentifier,vnfModel); + } + } + return vnfModel; + } + + private void addVnfModel(DependencyModelIdentifier modelIdentifier, String vnfModel) { + cache.putObject(modelIdentifier,vnfModel); + } + + private String readVnfModel(DependencyModelIdentifier modelIdentifier) { + + logger.debug("Reading Vnf Model data from database for RESOURCE_NAME : "+ modelIdentifier.getVnfType() +" and RESOURCE_VERSION : " +modelIdentifier.getCatalogVersion()); + StringBuilder query = new StringBuilder(); + String vnfModel =null; + query.append("SELECT ARTIFACT_CONTENT FROM sdnctl.ASDC_ARTIFACTS WHERE RESOURCE_NAME = ? ") ; + ArrayList argList = new ArrayList<>(); + argList.add(modelIdentifier.getVnfType()); + + if (modelIdentifier.getCatalogVersion()==null){ + query.append(" ORDER BY SUBSTRING_INDEX(RESOURCE_VERSION, '.', 1)*1 DESC , " + + "SUBSTRING_INDEX(SUBSTRING_INDEX(RESOURCE_VERSION, '.', 2),'.', -1) *1 DESC , " + + "SUBSTRING_INDEX(RESOURCE_VERSION, '.', -1)*1 DESC ;"); + }else{ + query.append("AND RESOURCE_VERSION = ? ;"); + argList.add(modelIdentifier.getCatalogVersion()); + } + try { + final CachedRowSet data = dbLibService.getData(query.toString(), argList, "sdnctl"); + if (data.first()) { + vnfModel = data.getString("ARTIFACT_CONTENT"); + if (vnfModel == null || vnfModel.isEmpty()) { + logger.error("Invalid dependency model for vnf type : "+ modelIdentifier.getVnfType() +" and catalog version : " +modelIdentifier.getCatalogVersion()); + throw new RuntimeException("Invalid or Empty VNF Model"); + } + logger.debug("Retrieved Vnf Model : " + vnfModel); + }else { + logger.warn("VNF Model not found in datastore for RESOURCE_NAME : "+ modelIdentifier.getVnfType() +" AND RESOURCE_VERSION : " +modelIdentifier.getCatalogVersion()); + } + } catch (SQLException e) { + throw new RuntimeException("Database error occurred"); + } + return vnfModel; + } +} diff --git a/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java b/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java new file mode 100644 index 000000000..ddd035644 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata.objects; + +/** + * Object of identifier for dependency model. + * Currently uses VNF type and catalog version + */ +public class DependencyModelIdentifier { + static final String TO_STRING_FORMAT = "DependencyModelIdentifier : vnfType = %s , catalogVersion = %s"; + static final int prime = 31; + + private String vnfType; + private String catalogVersion; + + /** + * Constructor + * @param vnfType String of the VNF type + * @param catalogVersion String of the catalog version + */ + public DependencyModelIdentifier(String vnfType, String catalogVersion) { + this.vnfType = vnfType; + this.catalogVersion = catalogVersion; + } + + @Override + public int hashCode() { + int result = 1; + result = result * prime + (this.vnfType == null ? 0 :this.vnfType.hashCode()); + result = result * prime + (this.catalogVersion == null ? 0 :this.catalogVersion.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (obj ==null) { + return false; + } + if (!(obj instanceof DependencyModelIdentifier)) { + return false; + } + + DependencyModelIdentifier modelIdentifier = (DependencyModelIdentifier)obj; + if (this.vnfType == null) { + if (modelIdentifier.vnfType !=null) { + return false; + } + } else if (!this.vnfType.equals(modelIdentifier.vnfType)) { + return false; + } + + if (this.catalogVersion == null) { + if (modelIdentifier.catalogVersion !=null) { + return false; + } + } else if (!this.catalogVersion.equals(modelIdentifier.catalogVersion)) { + return false; + } + + return true; + } + + @Override + public String toString() { + return String.format(TO_STRING_FORMAT, vnfType, catalogVersion); + } + + public String getVnfType() { + return vnfType; + } + + public String getCatalogVersion() { + return catalogVersion; + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/Allocator.java b/appc-common/src/main/java/org/onap/appc/pool/Allocator.java new file mode 100644 index 000000000..4b9f15a90 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/Allocator.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.Closeable; + +/** + * This interface is used to supply an object that will be called by the pool manager whenever a new widget must be + * allocated. + * @param + * The generic type that we are caching. + */ + +public interface Allocator { + + /** + * Allocate an object of type and return it to the pool + * + * @param pool + * The pool that the object is to be allocated to + * @return An object of type T + */ + T allocate(Pool pool); +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/CacheManagement.java b/appc-common/src/main/java/org/onap/appc/pool/CacheManagement.java new file mode 100644 index 000000000..9eb45776f --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/CacheManagement.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.pool; + +public interface CacheManagement { + + /** + * @return The object that is actually being wrapped and cached + */ + Object getWrappedObject(); + +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java b/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java new file mode 100644 index 000000000..d7d243d4f --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is implemented as a + * dynamic proxy, so that it appears to be the same class of object to the client as the interface being cached. The + * generic type being cached MUST be an interface. + * @param + * The generic type that we create a cached element for. This type is used to wrap instances of this type and + * expose access to the {@link java.io.Closeable} interface by using a dynamic proxy. + */ + +public class CachedElement implements Closeable, InvocationHandler, CacheManagement { + + /** + * The pool that is managing this cached element + */ + private Pool pool; + + /** + * The element that we are caching in the pool + */ + private T element; + + /** + * A thread-safe atomic indicator that tells us that the wrapped element has been released to the pool already, and + * not to do it again. + */ + private AtomicBoolean released = new AtomicBoolean(false); + + /** + * Create a new instance of a cached element dynamic proxy for use in the pool. + *

+ * This returns an instance of the proxy to the caller that appears to be the same interface(s) as the object being + * cached. The dynamic proxy then intercepts all open and close semantics and directs that element to the pool. + *

+ *

+ * If the object being proxied does not implement the {@link CacheManagement} interface, then that interface is + * added to the dynamic proxy being created. This interface is actually implemented by the invocation handler (this + * object) for the proxy and allows direct access to the wrapped object inside the proxy. + *

+ * + * @param pool + * The pool that we are caching these elements within + * @param element + * The element actually being cached + * @param interfaces + * The interface list of interfaces the element must implement (usually one) + * @return The dynamic proxy + */ + @SuppressWarnings("unchecked") + public static T newInstance(Pool pool, T element, Class[] interfaces) { + ClassLoader cl = element.getClass().getClassLoader(); + CachedElement ce = new CachedElement<>(pool, element); + boolean found = false; + for (Class intf : interfaces) { + if (intf.getName().equals(CacheManagement.class.getName())) { + found = true; + break; + } + } + + int length = found ? interfaces.length : interfaces.length + 1; + Class[] proxyInterfaces = new Class[length]; + System.arraycopy(interfaces, 0, proxyInterfaces, 0, interfaces.length); + + if (!found) { + proxyInterfaces[interfaces.length] = CacheManagement.class; + } + + return (T) Proxy.newProxyInstance(cl, proxyInterfaces, ce); + } + + /** + * Construct a cached element and assign it to the pool as a free element + * + * @param pool + * The pool that the element will be managed within + * @param element + * The element we are caching + */ + @SuppressWarnings("unchecked") + public CachedElement(Pool pool, T element) { + this.pool = pool; + this.element = element; + + try { + pool.release((T) this); + } catch (PoolDrainedException e) { + e.printStackTrace(); + } + } + + /** + * This method delegates the close call to the actual wrapped element. + *

+ * NOTE: This is not the same method that is called by the dynamic proxy. This method is in place to satisfy the + * signature of the {@link java.io.Closeable} interface. If it were to be called directly, then we will delegate the + * close to the underlying context. However, when the cached element is called as a synamic proxy, entry is in the + * {@link #invoke(Object, Method, Object[])} method. + *

+ * + * @see java.io.Closeable#close() + */ + @Override + public void close() throws IOException { + element.close(); + } + + /** + * This method is the magic part of dynamic proxies. When the caller makes a method call based on the interface + * being proxied, this method is given control. This informs us of the method and arguments of the call. The object + * reference is that of the dynamic proxy itself, which is us. + *

+ * Here we will check to see if the user is trying to close the "element" (the dynamic proxy acts like the wrapped + * element). If he is, then we don't really close it, but instead release the element that we are wrapping back to + * the free pool. Once this has happened, we mark the element as "closed" (from the perspective of this dynamic + * proxy) so that we wont try to release it again. + *

+ *

+ * If the method is the equals method then we assume that we are comparing the cached element in one + * dynamic proxy to the cached element in another. We execute the comparison between the cached elements, and not + * the dynamic proxies themselves. This preserves the allusion to the caller that the dynamic proxy is the object + * being wrapped. + *

+ *

+ * For convenience, we also implement the getWrappedObject method so that the dynamic proxy can be + * called to obtain the actual wrapped object if desired. Note, to use this method, the caller would have to invoke + * it through reflection. + *

+ *

+ * If the method being invoked is not one that we intercept, then we simply delegate that method onto the wrapped + * object. + *

+ * + * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) + */ + @SuppressWarnings({ + "unchecked", "nls" + }) + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Exception { + Object result = null; + + switch (method.getName()) { + case "close": + if (released.compareAndSet(false, true)) { + if (!pool.isDrained()) { + pool.release((T) proxy); + } + } + break; + case "equals": + CacheManagement cm = (CacheManagement) proxy; + T other = (T) cm.getWrappedObject(); + result = element.equals(other); + break; + case "getWrappedObject": + return element; + default: + result = method.invoke(element, args); + break; + } + + return result; + } + + /** + * This method is used to be able to access the wrapped object underneath the dynamic proxy + * + * @see org.onap.appc.pool.CacheManagement#getWrappedObject() + */ + @Override + public T getWrappedObject() { + return element; + } + + @SuppressWarnings("nls") + @Override + public String toString() { + return element == null ? "null" : element.toString(); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/Destructor.java b/appc-common/src/main/java/org/onap/appc/pool/Destructor.java new file mode 100644 index 000000000..46bcd2cd0 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/Destructor.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.Closeable; + +/** + * @param + * The generic type we are caching + */ + +public interface Destructor { + + /** + * Called to destroy the object when it is no longer being used by the pool + * + * @param obj + * The object to be destroyed + * @param pool + * The pool that the object is being removed from + */ + void destroy(T obj, Pool pool); +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/Pool.java b/appc-common/src/main/java/org/onap/appc/pool/Pool.java new file mode 100644 index 000000000..6d850ae42 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/Pool.java @@ -0,0 +1,372 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.Closeable; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.List; +import java.util.ListIterator; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * This class is used to manage a pool of things. + *

+ * The class is parameterized so that the type of objects maintained in the pool is definable by some provided type. + * This type must implement the Comparable interface so that it can be managed in the pool. + *

+ * + * @param + * The type of element being pooled + */ + +public class Pool { + private Deque free; + private List allocated; + private int minPool; + private int maxPool; + private Allocator allocator; + private Destructor destructor; + private ReadWriteLock lock; + private AtomicBoolean drained; + private Properties properties; + + /** + * Create the pool + * + * @param minPool + * The minimum size of the pool + * @param maxPool + * The maximum size of the pool, set to zero (0) for unbounded + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + public Pool(int minPool, int maxPool) throws PoolSpecificationException { + + if (minPool < 0) { + throw new PoolSpecificationException(String.format("The minimum pool size must be a " + + "positive value or zero, %d is not valid.", minPool)); + } + if (maxPool != 0 && maxPool < minPool) { + throw new PoolSpecificationException(String.format("The maximum pool size must be a " + + "positive value greater than the minimum size, or zero. %d is not valid.", maxPool)); + } + + this.minPool = minPool; + this.maxPool = maxPool; + + properties = new Properties(); + free = new ArrayDeque(); + allocated = new ArrayList(); + lock = new ReentrantReadWriteLock(); + drained = new AtomicBoolean(false); + } + + /** + * Returns the amount of objects on the free collection + * + * @return The number of objects on the free collection + */ + public int getFreeSize() { + Lock readLock = lock.readLock(); + readLock.lock(); + try { + return free.size(); + } finally { + readLock.unlock(); + } + } + + /** + * Returns the value for a specified property of this pool, if defined. + * + * @param key + * The key of the desired property + * @return The value of the property, or null if not defined + */ + public String getProperty(String key) { + return properties.getProperty(key); + } + + /** + * Sets the value of the specified property or replaces it if it already exists + * + * @param key + * The key of the property to be set + * @param value + * The value to set the property to + */ + public void setProperty(String key, String value) { + properties.setProperty(key, value); + } + + /** + * @return The properties object for the pool + */ + public Properties getProperties() { + return properties; + } + + /** + * Returns the number of objects that are currently allocated + * + * @return The allocate collection size + */ + public int getAllocatedSize() { + Lock readLock = lock.readLock(); + readLock.lock(); + try { + return allocated.size(); + } finally { + readLock.unlock(); + } + } + + /** + * @return the value of allocator + */ + public Allocator getAllocator() { + return allocator; + } + + /** + * @param allocator + * the value for allocator + */ + public void setAllocator(Allocator allocator) { + this.allocator = allocator; + } + + /** + * @return the value of destructor + */ + public Destructor getDestructor() { + return destructor; + } + + /** + * @return the value of minPool + */ + public int getMinPool() { + return minPool; + } + + /** + * @return the value of maxPool + */ + public int getMaxPool() { + return maxPool; + } + + /** + * @param destructor + * the value for destructor + */ + public void setDestructor(Destructor destructor) { + this.destructor = destructor; + } + + /** + * Drains the pool, releasing and destroying all pooled objects, even if they are currently allocated. + */ + public void drain() { + if (drained.compareAndSet(false, true)) { + Lock writeLock = lock.writeLock(); + writeLock.lock(); + try { + int size = getAllocatedSize(); + /* + * We can't use the "release" method call here because we are modifying the list we are iterating + */ + ListIterator it = allocated.listIterator(); + while (it.hasNext()) { + T obj = it.next(); + it.remove(); + free.addFirst(obj); + } + size = getFreeSize(); + trim(size); + } finally { + writeLock.unlock(); + } + } + } + + /** + * Returns an indication if the pool has been drained + * + * @return True indicates that the pool has been drained. Once a pool has been drained, it can no longer be used. + */ + public boolean isDrained() { + return drained.get(); + } + + /** + * Reserves an object of type T from the pool for the caller and returns it + * + * @return The object of type T to be used by the caller + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @SuppressWarnings("unchecked") + public T reserve() throws PoolExtensionException, PoolDrainedException { + if (isDrained()) { + throw new PoolDrainedException("The pool has been drained and cannot be used."); + } + + T obj = null; + Lock writeLock = lock.writeLock(); + writeLock.lock(); + try { + int freeSize = getFreeSize(); + int allocatedSize = getAllocatedSize(); + + if (freeSize == 0) { + if (allocatedSize == 0) { + extend(minPool == 0 ? 1 : minPool); + } else if (allocatedSize >= maxPool && maxPool > 0) { + throw new PoolExtensionException(String.format("Unable to add " + + "more elements, pool is at maximum size of %d", maxPool)); + } else { + extend(1); + } + } + + obj = free.removeFirst(); + allocated.add(obj); + } finally { + writeLock.unlock(); + } + + /* + * Now that we have the real object, lets wrap it in a dynamic proxy so that we can intercept the close call and + * just return the context to the free pool. obj.getClass().getInterfaces(). We need to find ALL interfaces that + * the object (and all superclasses) implement and have the proxy implement them too + */ + Class cls = obj.getClass(); + Class[] array; + List> interfaces = new ArrayList>(); + while (!cls.equals(Object.class)) { + array = cls.getInterfaces(); + for (Class item : array) { + if (!interfaces.contains(item)) { + interfaces.add(item); + } + } + cls = cls.getSuperclass(); + } + array = new Class[interfaces.size()]; + array = interfaces.toArray(array); + return CachedElement.newInstance(this, obj, array); + } + + /** + * releases the allocated object back to the free pool to be used by another request. + * + * @param obj + * The object to be returned to the pool + * @throws PoolDrainedException + * If the caller is trying to release an element to a drained pool + */ + public void release(T obj) throws PoolDrainedException { + if (isDrained()) { + throw new PoolDrainedException("The pool has been drained and cannot be used."); + } + Lock writeLock = lock.writeLock(); + writeLock.lock(); + try { + if (allocated.remove(obj)) { + free.addFirst(obj); + } + } finally { + writeLock.unlock(); + } + } + + /** + * Extend the free pool by some number of elements + * + * @param count + * The number of elements to add to the pool + * @throws PoolExtensionException + * if the pool cannot be extended because no allocator has been specified. + */ + private void extend(int count) throws PoolExtensionException { + if (allocator == null) { + throw new PoolExtensionException(String.format("Unable to extend pool " + + "because no allocator has been specified")); + } + Lock writeLock = lock.writeLock(); + writeLock.lock(); + try { + for (int index = 0; index < count; index++) { + T obj = allocator.allocate(this); + if (obj == null) { + throw new PoolExtensionException( + "The allocator failed to allocate a new context to extend the pool."); + } + free.push(obj); + } + } finally { + writeLock.unlock(); + } + } + + /** + * Used to trim the free collection by some specified number of elements, or the free element count, whichever is + * less. The elements are removed from the end of the free element deque, thus trimming the oldest elements first. + * + * @param count + * The number of elements to trim + */ + private void trim(int count) { + Lock writeLock = lock.writeLock(); + writeLock.lock(); + try { + int trimCount = count; + if (getFreeSize() < count) { + trimCount = getFreeSize(); + } + for (int i = 0; i < trimCount; i++) { + T obj = free.removeLast(); + if (destructor != null) { + destructor.destroy(obj, this); + } + } + } finally { + writeLock.unlock(); + } + } +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/PoolDrainedException.java b/appc-common/src/main/java/org/onap/appc/pool/PoolDrainedException.java new file mode 100644 index 000000000..260dc7b45 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/PoolDrainedException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +/** + * This exception is thrown whenever an attempt is made to access a pool of resources where the pool has been drained. + * Once drained, the pool is no longer usable. + * + */ +public class PoolDrainedException extends PoolException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * PoolDrainedException constructor + * + * @param msg + * The error message + */ + public PoolDrainedException(String msg) { + super(msg); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/PoolException.java b/appc-common/src/main/java/org/onap/appc/pool/PoolException.java new file mode 100644 index 000000000..76d798be1 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/PoolException.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +/** + * A pool exception is a specialization of checked exceptions that define various pool abnormal states or requests. + * + */ +public class PoolException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * PoolException constructor + */ + public PoolException() { + } + + /** + * PoolException constructor + * + * @param message + * The error message + */ + public PoolException(String message) { + super(message); + } + + /** + * PoolException constructor + * + * @param cause + * The cause of the exception + */ + public PoolException(Throwable cause) { + super(cause); + } + + /** + * PoolException constructor + * + * @param message + * The error message + * @param cause + * The cause of the exception + */ + public PoolException(String message, Throwable cause) { + super(message, cause); + } + + /** + * PoolException constructor + * + * @param message + * The error message + * @param cause + * The cause of the exception + * @param enableSuppression + * whether or not suppression is enabled or disabled + * @param writableStackTrace + * whether or not the stack trace should be writable + */ + public PoolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/PoolExtensionException.java b/appc-common/src/main/java/org/onap/appc/pool/PoolExtensionException.java new file mode 100644 index 000000000..c95c407c2 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/PoolExtensionException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +/** + * An error occurred trying to extend the pool + * + */ +public class PoolExtensionException extends PoolException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * PoolExtensionException constructor + * + * @param msg + * The error message + */ + public PoolExtensionException(String msg) { + super(msg); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/pool/PoolSpecificationException.java b/appc-common/src/main/java/org/onap/appc/pool/PoolSpecificationException.java new file mode 100644 index 000000000..361e50a54 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/pool/PoolSpecificationException.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +/** + * This exception is thrown whenever the pool is not specified correctly + * + */ +public class PoolSpecificationException extends PoolException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * PoolSpecificationException constructor + * + * @param msg + * The error message + */ + public PoolSpecificationException(String msg) { + super(msg); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java b/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java new file mode 100644 index 000000000..c1906362e --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.Map; + + +public class JsonUtil { + /** + * @param valueAsString a valid json Map represented as String + * @return a flat map that each entry key derived from hierarchy path in the json object and flatted to a dotted separated string. + * e.g. "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} + * when it required that the input will not be flatted the json string should be formatted as below example: + * e.g. "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}" will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}} + * @throws IOException when the object is not valid json Map + */ + public static Map convertJsonStringToFlatMap(String valueAsString) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + Map readValueMap = objectMapper.readValue(valueAsString,Map.class); + return org.onap.appc.util.ObjectMapper.map(readValueMap); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java b/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java new file mode 100644 index 000000000..44095fb71 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import org.apache.commons.lang3.StringUtils; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class MessageFormatter { + private final static String paramNameRegexGroupName = "paramName"; + private final static String paramRegex = "\\$\\{(?[^}$]+)\\}"; //start with ${ and after there is one or more characters that are not $ and not } and ended with } + + + public static String format(String messageTemplate, Map params) { + if (StringUtils.isEmpty(messageTemplate)) + return ""; + if (params == null || params.isEmpty()) + return messageTemplate; + + String formattedMessage = messageTemplate; + if (formattedMessage.contains("$")) { + for (Map.Entry entry : params.entrySet()) { + formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}", String.valueOf(entry.getValue())); + } + } + + return formattedMessage; + } + + public static List getParamsNamesList(String messageTemplate) { + List paramsNames = null; + if(!StringUtils.isEmpty(messageTemplate)){ + paramsNames = new ArrayList(); + Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate); + while (m.find()) { + String paramName = m.group(paramNameRegexGroupName); + paramsNames.add(paramName); + } + } + return paramsNames; + } + public static Set getParamsNamesSet(String messageTemplate) { + List paramsNamesList = getParamsNamesList(messageTemplate); + Set paramsNamesSet = null; + if(paramsNamesList != null && !paramsNamesList.isEmpty()){ + paramsNamesSet = new HashSet(); + for(String paramName : paramsNamesList){ + paramsNamesSet.add(paramName); + } + } + return paramsNamesSet; + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/ObjectMapper.java b/appc-common/src/main/java/org/onap/appc/util/ObjectMapper.java new file mode 100644 index 000000000..df0b24a78 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/ObjectMapper.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import java.lang.reflect.Array; +import java.util.Map; + +public class ObjectMapper { + + private ObjectMapper() { + } + + private static void dispatch(PathContext context, Object obj) { + + if (obj == null) { + return; + } + + final Class cls = obj.getClass(); + + if (cls.isPrimitive() + || String.class.isAssignableFrom(cls) + || Number.class.isAssignableFrom(cls) + || Boolean.class.isAssignableFrom(cls)) { + handlePrimitive(context, obj); + } else if (cls.isArray()) { + handleArray(context, obj); + } else if (Map.class.isAssignableFrom(cls)) { + handleMap(context, (Map) obj); + } else if (Iterable.class.isAssignableFrom(cls)) { + handleCollection(context, Iterable.class.cast(obj)); + } else { + throw new IllegalArgumentException(obj.getClass().getName()); + } + } + + public static Map map(Object obj) { + PathContext context = new PathContext(); + dispatch(context, obj); + return context.entries(); + } + + private static void handleMap(PathContext context, Map val) { + for (Map.Entry entry : val.entrySet()) { + context.pushToken(entry.getKey().toString()); + dispatch(context, entry.getValue()); + context.popToken(); + } + } + + private static void handleCollection(PathContext context, Iterable val) { + int index = 0; + for (Object elem : val) { + handleElement(context, index++, elem); + } + } + + private static void handleArray(PathContext context, Object val) { + for (int i = 0, n = Array.getLength(val); i < n; i++) { + handleElement(context, i, Array.get(val, i)); + } + } + + private static void handleElement(PathContext context, int index, Object val) { + if (val == null) { + return; + } + + String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString(); + + context.pushModifier(modifier); + dispatch(context, val); + context.popModifier(); + } + + private static void handlePrimitive(PathContext context, Object val) { + context.entry(context.getPath(), val.toString()); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/PathContext.java b/appc-common/src/main/java/org/onap/appc/util/PathContext.java new file mode 100644 index 000000000..79b75d1a4 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/PathContext.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.Map; + +class PathContext { + + private StringBuilder path = new StringBuilder(128); + + private LinkedList indexes = new LinkedList<>(); + private Map entries = new LinkedHashMap<>(); + private int offset = 0; + + private final String delimiter; + + PathContext() { + this("."); + } + + PathContext(String delimiter) { + this.delimiter = delimiter; + } + + private void push(String elem, boolean delimit) { + if (elem == null) { + throw new IllegalArgumentException(); + } + + int length = elem.length(); + + if (delimit && !indexes.isEmpty()) { + path.append(delimiter); + length += delimiter.length(); + } + + path.append(elem); + offset += length; + indexes.addLast(Integer.valueOf(length)); + } + + private void pop() { + if (indexes.isEmpty()) { + throw new IllegalStateException(); + } + offset -= indexes.removeLast(); + path.setLength(offset); + } + + void pushToken(String token) { + push(token, true); + } + + void popToken() { + pop(); + } + + void pushModifier(String modifier) { + push(modifier, false); + } + + void popModifier() { + pop(); + } + + String getPath() { + return path.substring(0, offset); + } + + void entry(String name, String value) { + entries.put(name, value); + } + + Map entries() { + return Collections.unmodifiableMap(entries); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/StringHelper.java b/appc-common/src/main/java/org/onap/appc/util/StringHelper.java new file mode 100644 index 000000000..2e68cbba4 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/StringHelper.java @@ -0,0 +1,595 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.util; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class contains several static helper methods that can be used to perform string manipulation algorithms. + * + */ + +public final class StringHelper { + + public static final String DASH = "-"; + public static final String DOT = "."; + public static final String ELLIPSES = "..."; + public static final String LINE_FEED = "\n"; + public static final String SLASH = "/"; + public static final String COMMA = ","; + + /** + * Converts the specified string pattern to a regular expression string. If the supplied string is null or empty, + * then a regular expression that matches all strings (.*) is returned. + *

+ * The expression passed to this method should not already be a regular expression. If it contains problematic + * meta-characters for this routine (such as period, asterisk, and plus), they will be escaped and matched literally + * in the resulting regular expression returned. + *

+ * + * @param value + * The pattern that we need to convert to a regular expression + * @return The regular expression that is equivalent to the pattern + */ + public static String convertToRegex(String value) { + if (value == null || value.trim().length() == 0) { + return ".*"; + } + boolean appendEOL = false; + StringBuffer buffer = new StringBuffer(value.trim()); + + /* + * If there are any period characters, we need to escape them so that they are exactly matched + */ + Pattern pattern = Pattern.compile("\\."); + Matcher matcher = pattern.matcher(buffer); + int position = 0; + while (matcher.find(position)) { + buffer.replace(matcher.start(), matcher.end(), "\\."); + position = matcher.end() + 1; + } + + /* + * If there are any asterisks or pluses, which we need to interpret as wildcard characters, we need to convert + * them into .* or . + */ + pattern = Pattern.compile("\\*|\\+"); + matcher = pattern.matcher(buffer); + position = 0; + while (matcher.find(position)) { + String metachar = buffer.substring(matcher.start(), matcher.end()); + if (metachar.equals("*")) { + buffer.replace(matcher.start(), matcher.end(), ".*"); + position = matcher.end() + 1; + if (matcher.end() < buffer.length() - 1) { + appendEOL = true; + } + } else if (metachar.equals("+")) { + buffer.replace(matcher.start(), matcher.end(), "."); + position = matcher.end(); + if (matcher.end() == buffer.length()) { + appendEOL = true; + } + } + } + + /* + * If the string contains a .* meta-character sequence anywhere in the middle of the string (i.e., there are + * other characters following the .* meta-characters), OR the string ends with the .+ sequence, then we need to + * append the "end-of-line" boundary condition to the end of the string to get predictable results. + */ + if (appendEOL) { + buffer.append("$"); + } + return buffer.toString(); + } + + /** + * Takes a string that may possibly be very long and return a string that is at most maxLength. If the string is + * longer than maxLength, the last three characters will be the ellipses (...) to indicate that the string was + * shortened. + * + * @param possiblyLongString + * @param maxLength + * must be at least 4 (one character plus ellipses) + * @return possibly shortened string + */ + public static String getShortenedString(String possiblyLongString, int maxLength) { + if ((possiblyLongString != null) && (maxLength > ELLIPSES.length()) + && (possiblyLongString.length() > maxLength)) { + return possiblyLongString.substring(0, maxLength - ELLIPSES.length()) + ELLIPSES; + + } + return possiblyLongString; + } + + /** + * Determines that a provided string is not null and not empty (length = 0 after trimming) + * + * @param theString + * The string to be tested + * @return true if the string IS NOT null and is NOT empty + */ + public static boolean isNotNullNotEmpty(String theString) { + return ((theString != null) && (!theString.trim().isEmpty())); + } + + /** + * Determines that a provided string IS null or an empty string (length = 0 after trimming) + * + * @param theString + * The string to be tested + * @return true if the string IS null OR is empty + */ + public static boolean isNullOrEmpty(String theString) { + return ((theString == null) || (theString.trim().isEmpty())); + } + + /** + * Returns an indication if the first string is equal to the second string, allowing for either or both strings to + * be null. + * + * @param a + * The first string to be compared + * @param b + * The second string to be compared + * @return True if both strings are null, or both strings are non-null AND they are equal. False otherwise. + */ + public static boolean equals(String a, String b) { + return equals(a, b, false); + } + + /** + * Returns an indication if the first string is equal to the second string, allowing for either or both strings to + * be null, and ignoring case. + * + * @param a + * The first string to be compared + * @param b + * The second string to be compared + * @return True if both strings are null, or both strings are non-null AND they are equal (without regard to case). + * False otherwise. + */ + public static boolean equalsIgnoreCase(String a, String b) { + return equals(a, b, true); + } + + /** + * Compares two strings (allowing either or both to be null), and allowing for optional case sensitive or + * insensitive comparison. + * + * @param a + * The first string to be compared + * @param b + * The second string to be compared + * @param caseInsensitive + * True if the comparison is to be case in-sensitive. + * @return True if both strings are null, or both strings are non-null and they are equal + */ + private static boolean equals(String a, String b, boolean caseInsensitive) { + if (a == null && b == null) { + return true; + } + if (a != null && b != null) { + if (caseInsensitive) { + return a.equalsIgnoreCase(b); + } else { + return a.equals(b); + } + } + + return false; + } + + /** + * This method is used to mangle a name. + *

+ * This method will first remove all unacceptable characters from the name and translate all characters to lower + * case. This is done to eliminate any potentially troublesome characters. If the resulting string is empty, then a + * random string of characters for the minimum desired length is returned. If the string is too short to meet the + * minimum length requirement, it is padded with random characters. + *

+ *

+ * Once the string has been scrubbed and possibly padded, it may be truncated (if longer than the maximum value) and + * the result is returned. To make the string as unique as possible, the algorithm removes excess letters from the + * center of the string, concatenating the first nad last parts of the name together. The assumption is that users + * tend to start the names of multiple things in similar ways, and get more descriptive as the name progresses. If + * for example, several objects were named "A test Object", "A test Object1", and "A test Object2", shortening the + * name only from the left does not generate a unique name. + *

+ * + * @param name + * The name to be mangled + * @param minLen + * minimum number of characters for the name + * @param maxLen + * maximum number of characters for the name + * @return The mangled name, or an empty string if the value is null or an empty string. + */ + public static String mangleName(String name, int minLen, int maxLen) { + StringBuffer buffer = new StringBuffer(name == null ? "" : name); + Pattern pattern = Pattern.compile("[^a-z0-9]+", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(buffer); + int position = 0; + while (matcher.find(position)) { + buffer.delete(matcher.start(), matcher.end()); + position = matcher.start(); + } + + if (buffer.length() < minLen) { + for (int i = buffer.length(); i <= minLen; i++) { + buffer.append("A"); + } + } + + /* + * Remove out of the center of the name to preserve start and end and result in a string of max len + */ + if (buffer.length() > maxLen) { + int excess = buffer.length() - maxLen; + int left = maxLen / 2; + + buffer.delete(left, excess + left); + } + + return buffer.toString().toLowerCase(); + } + + /** + * This method is used to normalize a string value. + *

+ * This method will ensure that the string value is trimmed of all leading and trailing whitespace if not null. If + * it is null or an empty string, then it will return null. + *

+ * + * @param value + * The value to be normalized + * @return The normalized (no leading or trailing whitespace) value, or null if the string was null or an empty + * string (or all whitespace). This method will never return an empty string. + */ + public static String normalizeString(String value) { + if (value != null) { + String temp = value.trim(); + if (temp.length() > 0) { + return temp; + } + } + return null; + } + + /** + * This method is used to strip all carriage returns and line feed characters from a string + * + * @param value + * @return The original value less all carriage returns and line feeds + */ + public static String stripCRLF(String value) { + + if (value == null) { + return null; + } + String[] tokens = value.split("\r\n|\n\r|\r|\n"); + StringBuffer buffer = new StringBuffer(); + for (String token : tokens) { + buffer.append(token.trim()); + } + return buffer.toString(); + } + + /** + * Converts UNIX-style line endings to DOS-style. Replaces LF with CR+LF as long as the LF does not already exist + * paired with a CR. + * + * @param content + * The content to be converted + * @return The converted content. + */ + public static String toDOSLines(String content) { + if (content == null) { + return null; + } + + StringBuffer buffer = new StringBuffer(content); + Pattern pattern = Pattern.compile("^(\n)[^\r]|[^\r](\n)[^\r]|[^\r](\n)$"); + Matcher matcher = pattern.matcher(buffer); + int position = 0; + while (matcher.find(position)) { + int index = matcher.start(1); + if (index == -1) { + index = matcher.start(2); + } + if (index == -1) { + index = matcher.start(3); + } + + buffer.replace(index, index + 1, "\r\n"); + position = index + 1; + } + + return buffer.toString(); + } + + /** + * This method will convert a string contents to use the UNIX-style line endings. That is, all occurrences of CR + * (Carriage Return) and LF (Line Feed) are reduced to just use LF. + * + * @param content + * The buffer to be processed + * @return The converted contents + */ + public static String toUnixLines(String content) { + if (content == null) { + return null; + } + + StringBuffer buffer = new StringBuffer(content); + Pattern pattern = Pattern.compile("\r\n|\n\r"); + Matcher matcher = pattern.matcher(buffer); + int position = 0; + while (matcher.find(position)) { + buffer.replace(matcher.start(), matcher.end(), "\n"); + position = matcher.start(); + } + + return buffer.toString(); + } + + /** + * This method is used to translate characters in the input sequence that match the characters in the match list to + * the corresponding character in the replacement list. If the replacement list is shorter than the match list, then + * the character from the replacement list is taken as the modulo of the match character position and the length of + * the replacement list. + * + * @param sequence + * The input sequence to be processed + * @param match + * The list of matching characters to be searched + * @param replacement + * The list of replacement characters, positional coincident with the match list. If shorter than the + * match list, then the position "wraps" around on the replacement list. + * @return The translated string contents. + */ + public static Object translate(String sequence, String match, String replacement) { + + if (sequence == null) { + return sequence; + } + + StringBuffer buffer = new StringBuffer(sequence); + + for (int index = 0; index < buffer.length(); index++) { + char ch = buffer.charAt(index); + + int position = match.indexOf(ch); + if (position == -1) { + continue; + } + + if (position >= replacement.length()) { + position %= replacement.length(); + } + buffer.setCharAt(index, replacement.charAt(position)); + } + + return buffer.toString(); + } + + /** + * Ensures that the name provided is a valid identifier. This means that no spaces are allowed as well as special + * characters. This method translates all spaces and illegal characters to underscores (_). + * + * @param name + * The name to be checked and converted to an identifier if needed + * @return The valid identifier from the name + */ + public static String validIdentifier(String name) { + if (name == null || name.length() == 0) { + return name; + } + + StringBuffer buffer = new StringBuffer(name); + for (int index = 0; index < buffer.length(); index++) { + char ch = buffer.charAt(index); + + if ((index == 0 && !Character.isJavaIdentifierStart(ch)) || (!Character.isJavaIdentifierPart(ch))) { + buffer.setCharAt(index, '_'); + } + } + return buffer.toString(); + } + + /** + * This method verifies that the provided string only contains characters from the legal set, and replaces any + * character not in the legal set with the specified replacement character. + * + * @param sequence + * The sequence to be verified + * @param legal + * The set of all legal characters + * @param replacement + * The replacement character if a character is not in the legal set + * @return The verified *and possibly updated) string + */ + public static String verify(String sequence, String legal, char replacement) { + if (sequence == null) { + return sequence; + } + + StringBuffer buffer = new StringBuffer(sequence); + for (int index = 0; index < buffer.length(); index++) { + char ch = buffer.charAt(index); + if (legal.indexOf(ch) == -1) { + buffer.setCharAt(index, replacement); + } + } + return buffer.toString(); + } + + /** + * Private constructor to prevent instantiation of this class - All methods are static! + */ + private StringHelper() { + + } + + /** + * @param list + * The list of elements + * @return The list of elements formatted as a comma-delimited list + */ + public static String asList(List list) { + StringBuffer buffer = new StringBuffer(); + if (list != null) { + if (list.size() == 1) { + buffer.append(list.get(0)); + } else { + for (String element : list) { + buffer.append(element); + buffer.append(", "); + } + + if (buffer.length() > 2) { + buffer.delete(buffer.length() - 2, buffer.length()); + } + } + } + return buffer.toString(); + } + + /** + * @param map + * A map of strings + * @return A map expressed as a comma-delimited list of name=value tuples + */ + public static String asList(Map map) { + StringBuffer buffer = new StringBuffer(); + if (map != null) { + Set keys = map.keySet(); + for (String key : keys) { + buffer.append(String.format("%s=%s, ", key, map.get(key))); + } + + if (buffer.length() > 2) { + buffer.delete(buffer.length() - 2, buffer.length()); + } + } + return buffer.toString(); + } + + /** + * @param values + * An array or varargs of Strings to be concatenated into a comma-separated list + * @return The comma-seprated list of values + */ + public static String asList(String... values) { + StringBuilder builder = new StringBuilder(); + builder.append('['); + if (values != null && values.length > 0) { + int count = values.length; + for (int index = 0; index < count - 1; index++) { + builder.append(values[index]); + builder.append(','); + } + builder.append(values[count - 1]); + } + builder.append(']'); + return builder.toString(); + } + + public static Object resolveToType(String input) { + String intRegex = "^(\\-)?[0-9]+$"; + String doubleRegex = "^(\\-)?[0-9\\.]+$"; + String boolRegex = "(^(?i)((true)|(false))$)"; + + // Check for null + if (input == null) { + return null; + } + + // Check int first + if (input.matches(intRegex)) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException nfe) { + // Should not happen + nfe.printStackTrace(); + } + } + + // Check double (int + decimal point) + if (input.matches(doubleRegex)) { + try { + return Double.parseDouble(input); + } catch (NumberFormatException | NullPointerException e) { + // NPE won't happen bc of regex check + } + } + + // Check boolean + if (input.matches(boolRegex)) { + return Boolean.parseBoolean(input); + } + + // Try to parse a date + Date date = Time.utcParse(input); + if (date != null) { + return date; + } + + // No special type, return string + return input; + } + + /** + * Converts a properties object to a string in the format of
[ key=value, key=value, ... ]
+ * + * @param props + * The properties object to format + * @return A string in the format
[ key=value, ... ]
or null if the input was null + */ + public static String propertiesToString(Properties props) { + if (props == null) { + return null; + } + StringBuilder out = new StringBuilder(); + out.append("["); + for (Object key : props.keySet()) { + out.append(String.format(" %s = %s,", key.toString(), props.getProperty(key.toString()))); + } + if (props.size() > 0) { + out.deleteCharAt(out.lastIndexOf(",")); + } + out.append(" ]"); + return out.toString(); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/StructuredPropertyHelper.java b/appc-common/src/main/java/org/onap/appc/util/StructuredPropertyHelper.java new file mode 100644 index 000000000..b610b5a3e --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/StructuredPropertyHelper.java @@ -0,0 +1,260 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class is used to assemble properties that are defined using a structured name into groups, and allow them to be + * processed as sets of definitions. + *

+ * For example, a structured name uses a dotted-notation, like "provider.name". Further, the nodes of the structured + * name may be serialized using a suffix ordinal number (e.g., "provider1.name"). These structured properties form a + * hierarchical name space where the names are grouped together and can be retrieved as a set. + *

+ * + */ + +public class StructuredPropertyHelper { + + /** + * This method scans the properties object for all properties that match the root name and constructs a list of + * structured property node graphs that represents the namespaces of the properties. + *

+ * For example, assume that there are structured properties of the form "provider1.name", "provider2.name", + * "provider3.name", and so forth. There may also be other subordinate properties as well (e.g., "provider1.type"). + * This method would construct a list of graphs of nodes, where each node represents one value of the structured + * name. The roots would be the values "provider1", "provider2", "provider3", and so forth. The values of the + * subordinate nodes would be the second, third, and so forth name nodes of the compound name. The value of the + * property is associated with nodes that are representative of the leaf of the name space. + *

+ * + * @param properties + * The properties to be processed + * @param prefix + * The prefix of the root structured property name + * @return The node graph of the properties + */ + public static List getStructuredProperties(Properties properties, String prefix) { + List roots = new ArrayList<>(); + + for (String name : properties.stringPropertyNames()) { + if (name.startsWith(prefix)) { + String value = properties.getProperty(name); + processNamespace(roots, name, value); + } + } + + return roots; + } + + /** + * This method recursively walks the name space of the structured property and constructs the node graph to + * represent the property + * + * @param nodes + * The collection of nodes for the current level of the name space + * @param propertyName + * The name of the node + * @param value + * The value, if any + * @return The node for this level in the namespace + */ + @SuppressWarnings("nls") + private static Node processNamespace(List nodes, String propertyName, String value) { + String[] tokens = propertyName.split("\\.", 2); + String nodeName = normalizeNodeName(tokens[0]); + + Node namespaceNode = null; + for (Node node : nodes) { + if (node.getName().equals(nodeName)) { + namespaceNode = node; + break; + } + } + if (namespaceNode == null) { + namespaceNode = new Node(); + namespaceNode.setName(nodeName); + nodes.add(namespaceNode); + } + + if (tokens.length == 1 || tokens[1] == null || tokens[1].length() == 0) { + namespaceNode.setValue(value); + } else { + processNamespace(namespaceNode.getChildren(), tokens[1], value); + } + + return namespaceNode; + } + + /** + * This method normalizes a node name of the structured property name by removing leading and trailing whitespace, + * and by converting any ordinal position to a simple expression without leading zeroes. + * + * @param token + * The token to be normalized + * @return The normalized name, or null if the token was null; + */ + @SuppressWarnings("nls") + private static String normalizeNodeName(String token) { + if (token == null) { + return null; + } + + StringBuffer buffer = new StringBuffer(token.trim()); + Pattern pattern = Pattern.compile("([^0-9]+)([0-9]*)"); + Matcher matcher = pattern.matcher(buffer); + if (matcher.matches()) { + String nameRoot = matcher.group(1); + String ordinal = matcher.group(2); + if (ordinal != null && ordinal.length() > 0) { + int i = Integer.parseInt(ordinal); + buffer.setLength(0); + buffer.append(nameRoot); + buffer.append(Integer.toString(i)); + } + } + return buffer.toString(); + } + + /** + * This class represents a node in the structured property name space + * + */ + public static class Node implements Comparable { + + /** + * The name of the structured property node + */ + private String name; + + /** + * If the node is a leaf, then the value of the property + */ + private String value; + + /** + * If the node is not a leaf, then the sub-nodes of the property + */ + private List children; + + /** + * @return the value of name + */ + public String getName() { + return name; + } + + /** + * @param name + * the value for name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the value of value + */ + public String getValue() { + return value; + } + + /** + * @param value + * the value for value + */ + public void setValue(String value) { + this.value = value; + } + + /** + * @return the value of children + */ + public List getChildren() { + if (children == null) { + children = new ArrayList<>(); + } + return children; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return name.hashCode() + (value != null ? value.hashCode() : children.hashCode()); + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (this.getClass() != obj.getClass()) + return false; + + Node other = (Node) obj; + boolean result = name.equals(other.name); + + if (value == null) { + result &= other.value == null; + } else { + result &= value.equals(other.value); + } + if (children == null) { + result &= other.children == null; + } else { + result &= children.equals(other.children); + } + return result; + } + + /** + * @see java.lang.Object#toString() + */ + @SuppressWarnings("nls") + @Override + public String toString() { + if (value != null) { + return String.format("%s = %s", name, value); + } + return String.format("%s.%s", name, children.toString()); + } + + @Override + public int compareTo(StructuredPropertyHelper.Node o) { + return name.compareTo(o.name); + } + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/Time.java b/appc-common/src/main/java/org/onap/appc/util/Time.java new file mode 100644 index 000000000..ce2babdc3 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/Time.java @@ -0,0 +1,611 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.util; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Locale; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is a general purpose helper class to augment standard Java time support. + * + */ + +public final class Time { + + /** + * Logger to log operations + */ + private static final Logger LOG = LoggerFactory.getLogger(Time.class); + + /** + * A formatter to be used to format values + */ + private static SimpleDateFormat dateformatter = null; + + /** + * The UTC timezone (for UTC or GMT time) + */ + @SuppressWarnings("nls") + private static final TimeZone utcTZ = TimeZone.getTimeZone("UTC"); + + /** + * The cached reference to the datatype factory + */ + private static DatatypeFactory xmlDatatypeFactory = null; + + /** + * Private default constructor prevents instantiation + */ + private Time() { + // + } + + /** + * Increments a date by the indicated months, days, hours, minutes, and seconds, and returns the updated date. + * + * @param date + * The date to be manipulated + * @param months + * The number of months to be added to the date + * @param days + * The number of days to be added to the date + * @param hours + * The number of hours to be added to the date + * @param minutes + * The number of minutes to be added to the date + * @param seconds + * The number of seconds to be added to the date + * @return The updated date. + */ + public static Date addTime(final Date date, final int months, final int days, final int hours, final int minutes, + final int seconds) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.MONTH, months); + cal.add(Calendar.DATE, days); + cal.add(Calendar.HOUR_OF_DAY, hours); + cal.add(Calendar.MINUTE, minutes); + cal.add(Calendar.SECOND, seconds); + return cal.getTime(); + } + + /** + * Clears the time components of a calendar to zero, leaving the date components unchanged. + * + * @param cal + * the calendar to be updated + * @return The updated calendar object + */ + public static Calendar dateOnly(final Calendar cal) { + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + return cal; + } + + /** + * This method returns the local time that corresponds to the end of the current day + * + * @return The time that corresponds to the end of the current day, expressed as local time + */ + public static Date endOfDayLocal() { + return endOfDayLocal(new Date()); + } + + /** + * This method returns the last moment of the day for the supplied local time. This is defined as the millisecond + * before midnight of the current date represented by the local time. + * + * @param localTime + * The local time for which the last moment of the day is desired. + * @return The millisecond prior to midnight, local time. + */ + public static Date endOfDayLocal(final Date localTime) { + // @sonar:off + GregorianCalendar calendar = new GregorianCalendar(); + calendar.setTime(localTime); + calendar.set(Calendar.HOUR, 11); + calendar.set(Calendar.AM_PM, Calendar.PM); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + calendar.set(Calendar.MILLISECOND, 999); + // @sonar:on + + return calendar.getTime(); + } + + /** + * The end of the current day and in the current time zone expressed as a UTC time. + * + * @return The UTC time that corresponds to the end of the current day + */ + public static Date endOfDayUTC() { + return endOfDayUTC(new Date()); + } + + /** + * Returns the UTC time that corresponds to the end of the day for the local time specified, using the current + * (default) time zone. + * + * @param localTime + * The local time for which we are requesting the UTC time that corresponds to the end of the day + * @return The UTC time that corresponds to the end of the local day specified by the local time. + */ + public static Date endOfDayUTC(final Date localTime) { + return endOfDayUTC(localTime, TimeZone.getDefault()); + } + + /** + * Returns the time expressed in UTC time of the end of the day specified in local time and within the local time + * zone. + * + * @param localTime + * The local time for which we will compute the end of the local day, and then convert to UTC time. + * @param localTimeZone + * The time zone that the local time is within. + * @return The UTC date that corresponds to the end of the day local time and in the local time zone. + */ + public static Date endOfDayUTC(final Date localTime, final TimeZone localTimeZone) { + Date endOfDay = endOfDayLocal(localTime); + return utcDate(endOfDay, localTimeZone); + } + + /** + * returns current Date in 'UTC' Timezone + * + * @return The current date, expressed in the UTC timezone. + */ + @SuppressWarnings("nls") + public static Date getCurrentUTCDate() { + + // This code incorrectly changes the default timezone for the entire JVM in order to compute the UTC + // date for the current time. + + GregorianCalendar calendar = new GregorianCalendar(); + calendar.setTimeZone(TimeZone.getTimeZone("UTC")); + calendar.setTimeInMillis(utcTime()); + return calendar.getTime(); + } + + /** + * This method loads and caches the reference to the XML data type factory object. + * + * @return The XML Data Type Factory object + */ + public static DatatypeFactory getDatatypeFactory() { + if (xmlDatatypeFactory == null) { + try { + xmlDatatypeFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + e.printStackTrace(System.err); + } + } + return xmlDatatypeFactory; + } + + /** + * Gives the date-time String based on given Locale and Timezone + * + * @param date + * The date to be formatted + * @param locale + * The locale that we want to format the value for + * @param timezone + * The time zone that the date is within + * @return The formatted value + */ + public static String getDateByLocaleAndTimeZone(final Date date, final Locale locale, final TimeZone timezone) { + String strDate = null; + DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); + df.setTimeZone(timezone); + synchronized (df) { + strDate = df.format(date); + } + return strDate; + } + + /** + * Returns singleton UTC date formatter. + * + * @return + */ + @SuppressWarnings("nls") + private static SimpleDateFormat getDateFormatter() { + if (dateformatter == null) { + dateformatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + dateformatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); + } + return dateformatter; + } + + /** + * This method returns the local time that corresponds to a given UTC time in the current time zone. + * + * @param utcTime + * The UTC time for which we desire the equivalent local time in the current time zone. + * @return The local time that is equivalent to the given UTC time for the current time zone + */ + public static long localTime(final long utcTime) { + return localTime(utcTime, TimeZone.getDefault()); + } + + /** + * This method can be used to get the local time that corresponds to a specific UTC time. + *

+ * This method has a problem since the offset can only be determined by having a local time. So, we take the UTC + * time and add the raw offset to it to come up with an approximation of the local time. This gives us a local time + * that we can use to determine what the offset should be, which is what we actually add to the UTC time to get the + * local time. + *

+ * + * @param utcTime + * The UTC time for which we want to obtain the equivalent local time + * @param localTZ + * The time zone that we want the local time to be within + * @return The local time for the specified time zone and the given UTC time + */ + public static long localTime(final long utcTime, final TimeZone localTZ) { + int offset = localTZ.getOffset(utcTime + localTZ.getRawOffset()); + long result = utcTime + offset; + + return result; + } + + /** + * Sets the date components of a calendar to the specified values, leaving the time components unchanged. + * + * @param cal + * The calendar to be updated + * @param year + * The year to be set + * @param month + * The month to be set + * @param day + * The day to be set + * @return The updated calendar object + */ + public static Calendar setDate(final Calendar cal, final int year, final int month, final int day) { + cal.set(Calendar.YEAR, year); + cal.set(Calendar.MONTH, month); + cal.set(Calendar.DAY_OF_MONTH, day); + return cal; + } + + /** + * Returns the start of the day expressed in local time for the current local time. + * + * @return The start of the day + */ + public static Date startOfDayLocal() { + return startOfDayLocal(new Date()); + } + + /** + * This method returns the date that corresponds to the start of the day local time. The date returned represents + * midnight of the previous day represented in local time. If the UTC time is desired, use the methods + * {@link #startOfDayUTC(Date, TimeZone)}, {@link #startOfDayUTC(Date)}, or {@link #startOfDayUTC()} + * + * @param localTime + * The local date that we wish to compute the start of day for. + * @return The date that corresponds to the start of the local day + */ + public static Date startOfDayLocal(final Date localTime) { + GregorianCalendar calendar = new GregorianCalendar(); + calendar.setTime(localTime); + calendar.set(Calendar.HOUR, 0); + calendar.set(Calendar.AM_PM, Calendar.AM); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + + return calendar.getTime(); + } + + /** + * This method returns the UTC date that corresponds to the start of the local day based on the current time and the + * default time zone (the time zone we are running in). + * + * @return The start of the local day expressed as a UTC time. + */ + public static Date startOfDayUTC() { + return startOfDayUTC(new Date()); + } + + /** + * This method returns the UTC date that corresponds to the start of the local day specified in the current time + * zone. + * + * @param localTime + * The local time to be used to compute the start of the day + * @return The start of the local day expressed as a UTC time. + */ + public static Date startOfDayUTC(final Date localTime) { + return startOfDayUTC(localTime, TimeZone.getDefault()); + } + + /** + * This method returns the UTC date that corresponds to the start of the local day specified in the local timezone. + * + * @param localTime + * The local time to be used to compute start of day + * @param localTimeZone + * The time zone that the local time was recorded within + * @return The corresponding UTC date + */ + public static Date startOfDayUTC(final Date localTime, final TimeZone localTimeZone) { + Date startOfDay = startOfDayLocal(localTime); + return utcDate(startOfDay, localTimeZone); + } + + /** + * This method creates and returns an XML timestamp expressed as the current UTC value for the system. The caller + * does not specify the time value or time zone using this method. This ensures that the timestamp value is always + * expressed as UTC time. + * + * @return The XMLGregorianCalendar that can be used to record the timestamp + */ + + public static XMLGregorianCalendar timestamp() { + getDatatypeFactory(); + XMLGregorianCalendar ts = xmlDatatypeFactory.newXMLGregorianCalendar(); + GregorianCalendar utc = new GregorianCalendar(); + utc.setTime(utcDate()); + ts.setTimezone(0); + ts.setYear(utc.get(Calendar.YEAR)); + // Calendar Months are from 0-11 need to +1 + ts.setMonth(utc.get(Calendar.MONTH) + 1); + ts.setDay(utc.get(Calendar.DAY_OF_MONTH)); + ts.setHour(utc.get(Calendar.HOUR_OF_DAY)); + ts.setMinute(utc.get(Calendar.MINUTE)); + ts.setSecond(utc.get(Calendar.SECOND)); + ts.setMillisecond(utc.get(Calendar.MILLISECOND)); + return ts; + } + + /** + * Converts XMLGregorianCalendar to java.util.Date in Java + * + * @param calendar + * the calendar object to be converted + * @return The equivalent Date object + */ + public static Date toDate(final XMLGregorianCalendar calendar) { + if (calendar == null) { + return null; + } + return calendar.toGregorianCalendar().getTime(); + } + + /** + * Converts java Date to XMLGregorianCalendar. + * + * @param date + * The date to convert + * @return The XMLGregorianCalendar for the specified date + */ + @SuppressWarnings("nls") + public static XMLGregorianCalendar toXMLCalendar(final Date date) { + GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); + cal.setTime(date); + + XMLGregorianCalendar xmlCal = null; + try { + xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); + } catch (DatatypeConfigurationException e) { + LOG.error("toXMLCalendar", e); + } + return xmlCal; + } + + /** + * Truncates the provided date so that only the date, hours, and minutes portions are significant. This method + * returns the date with the seconds and milliseconds forced to zero. + * + * @param date + * The date to truncate + * @return The date with only the year, month, day, hours, and minutes significant. + */ + public static Date truncDate(final Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + return cal.getTime(); + } + + /** + * The UTC date that corresponds to the current date in the local time zone. + * + * @return The UTC date for now in the current time zone. + */ + public static Date utcDate() { + return new Date(); + } + + /** + * The UTC date for the specified date in the current (default) time zone. + * + * @param date + * The local date for which the UTC date is desired. + * @return The UTC date that corresponds to the date in the current time zone. + */ + public static Date utcDate(final Date date) { + TimeZone tz = TimeZone.getDefault(); + return utcDate(date, tz); + } + + /** + * Returns the UTC date for the specified date in the specified time zone. + * + * @param date + * The date for which the UTC date is desired in the specified zone + * @param tz + * The time zone that corresponds to the date to be converted to UTC + * @return The UTC date that corresponds to the local date in the local time zone. + */ + public static Date utcDate(final Date date, final TimeZone tz) { + return new Date(utcTime(date.getTime(), tz)); + } + + /** + * Format incoming date as string in GMT or UTC. + * + * @param dt + * The date to be formatted + * @return The date formatted for UTC timezone + */ + public static String utcFormat(final Date dt) { + String strDate = null; + DateFormat df = getDateFormatter(); + synchronized (df) { + strDate = df.format(dt); + } + return strDate; + } + + /** + * Parse previously formated Date object back to a Date object. + * + * @param dateStr + * The representation of a UTC date as a string + * @return The date object containing the parsed representation, or null if the representation cannot be parsed + */ + @SuppressWarnings("nls") + public static Date utcParse(final String dateStr) { + String[] adtl = { + "yyyy-MM-dd" + }; + return utcParse(dateStr, adtl); + } + + /** + * Parse previously formated Date object back to a Date object. + * + * @param dateStr + * The representation of a UTC date as a string + * @param adtlFormatStrings + * A list of strings that represent additional date format representations to try and parse. + * @return The date object containing the parsed representation, or null if the representation cannot be parsed + */ + @SuppressWarnings("nls") + public static Date utcParse(final String dateStr, String... adtlFormatStrings) { + if (dateStr != null) { + // Build the list of formatters starting with the default defined in the class + List formats = new ArrayList<>(); + formats.add(getDateFormatter()); + + if (adtlFormatStrings != null) { + for (String s : adtlFormatStrings) { + formats.add(new SimpleDateFormat(s)); + } + } + + // Return the first matching date formatter's result + for (DateFormat df : formats) { + df.setTimeZone(utcTZ); + try { + return df.parse(dateStr); + } catch (ParseException e) { + LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", dateStr, + df.toString())); + } + } + } + return null; + } + + /** + * This method returns the current time for the UTC timezone + * + * @return The time in the UTC time zone that corresponds to the current local time. + */ + public static long utcTime() { + return new Date().getTime(); + } + + /** + * Get the UTC time that corresponds to the given time in the default time zone (current time zone for the system). + * + * @param localTime + * The time in the current time zone for which the UTC time is desired. + * @return The UTC time + */ + public static long utcTime(final long localTime) { + TimeZone tz = TimeZone.getDefault(); + return utcTime(localTime, tz); + } + + /** + * Get the UTC time that corresponds to the given time in the specified timezone. + *

+ * Note that the java getOffset() method works a little counter-intuitive. It returns the offset that + * would be added to the current UTC time to get the LOCAL time represented by the local time zone. That means to + * get the UTC time, we need to SUBTRACT this offset from the local time. + *

+ * + * @param localTime + * The time in the specified time zone for which the UTC time is desired. + * @param localTZ + * The time zone which the local time is in. + * @return The UTC time for the specified local time in the specified local time zone. + */ + public static long utcTime(final long localTime, final TimeZone localTZ) { + int offset = localTZ.getOffset(localTime); + return localTime - offset; + + } + + /** + * Creates a timestamp value from a time + * + * @param utcTime + * The UTC time to convert to a timestamp + * @return The timestamp + */ + public static Timestamp utcTimestamp(final long utcTime) { + TimeZone tz = TimeZone.getDefault(); + return new Timestamp(utcTime(utcTime, tz)); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/UnmodifiableProperties.java b/appc-common/src/main/java/org/onap/appc/util/UnmodifiableProperties.java new file mode 100644 index 000000000..831f0f503 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/UnmodifiableProperties.java @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.Writer; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.InvalidPropertiesFormatException; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +/** + * This utility class is used to wrap a properties object and to delegate all read operations to the property object, + * while disallowing any write or modification to the property object. + * + */ +public class UnmodifiableProperties extends Properties implements Cloneable { + + /** + * Serial number + */ + private static final long serialVersionUID = 1L; + + private static final String PROPERTY_CANNOT_BE_MODIFIED_MSG = "Property cannot be modified!"; + + /** + * The properties object which we are wrapping + */ + private Properties properties; + + /** + * Create the unmodifiable wrapper around the provided properties object + * + * @param properties + * The properties to be wrapped and protected from modification + */ + public UnmodifiableProperties(Properties properties) { + this.properties = properties; + } + + /** + * @see java.util.Hashtable#clear() + */ + @Override + public synchronized void clear() { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Hashtable#clone() + */ + // @sonar:off + @Override + public synchronized Object clone() { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + // @sonar:on + + /** + * @see java.util.Hashtable#contains(java.lang.Object) + */ + @Override + public synchronized boolean contains(Object value) { + return properties.contains(value); + } + + /** + * @see java.util.Hashtable#containsKey(java.lang.Object) + */ + @Override + public synchronized boolean containsKey(Object key) { + return properties.containsKey(key); + } + + /** + * @see java.util.Hashtable#containsValue(java.lang.Object) + */ + @Override + public boolean containsValue(Object value) { + return properties.containsValue(value); + } + + /** + * @see java.util.Hashtable#elements() + */ + @Override + public synchronized Enumeration elements() { + return properties.elements(); + } + + /** + * @see java.util.Hashtable#entrySet() + */ + @Override + public Set> entrySet() { + return Collections.unmodifiableSet(properties.entrySet()); + } + + /** + * @see java.util.Hashtable#equals(java.lang.Object) + */ + @Override + public synchronized boolean equals(Object o) { + return properties.equals(o); + } + + /** + * @see java.util.Hashtable#get(java.lang.Object) + */ + @Override + public synchronized Object get(Object key) { + return properties.get(key); + } + + /** + * @see java.util.Properties#getProperty(java.lang.String) + */ + @Override + public String getProperty(String key) { + return properties.getProperty(key); + } + + /** + * @see java.util.Properties#getProperty(java.lang.String, java.lang.String) + */ + @Override + public String getProperty(String key, String defaultValue) { + return properties.getProperty(key, defaultValue); + } + + /** + * @see java.util.Hashtable#hashCode() + */ + @Override + public synchronized int hashCode() { + return properties.hashCode(); + } + + /** + * @see java.util.Hashtable#isEmpty() + */ + @Override + public synchronized boolean isEmpty() { + return properties.isEmpty(); + } + + /** + * @see java.util.Hashtable#keys() + */ + @Override + public synchronized Enumeration keys() { + return properties.keys(); + } + + /** + * @see java.util.Hashtable#keySet() + */ + @Override + public Set keySet() { + return Collections.unmodifiableSet(properties.keySet()); + } + + /** + * @see java.util.Properties#list(java.io.PrintStream) + */ + @Override + public void list(PrintStream out) { + properties.list(out); + } + + /** + * @see java.util.Properties#list(java.io.PrintWriter) + */ + @Override + public void list(PrintWriter out) { + properties.list(out); + } + + /** + * @see java.util.Properties#load(java.io.InputStream) + */ + @Override + public synchronized void load(InputStream inStream) throws IOException { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Properties#load(java.io.Reader) + */ + @Override + public synchronized void load(Reader reader) throws IOException { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Properties#loadFromXML(java.io.InputStream) + */ + @Override + public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Properties#propertyNames() + */ + @Override + public Enumeration propertyNames() { + return properties.propertyNames(); + } + + /** + * @see java.util.Hashtable#put(java.lang.Object, java.lang.Object) + */ + @Override + public synchronized Object put(Object key, Object value) { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Hashtable#putAll(java.util.Map) + */ + @Override + public synchronized void putAll(Map t) { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Hashtable#rehash() + */ + @Override + protected void rehash() { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Hashtable#remove(java.lang.Object) + */ + @Override + public synchronized Object remove(Object key) { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Properties#save(java.io.OutputStream, java.lang.String) + */ + @Override + @Deprecated + public synchronized void save(OutputStream out, String comments) { + properties.save(out, comments); + } + + /** + * @see java.util.Properties#setProperty(java.lang.String, java.lang.String) + */ + @Override + public synchronized Object setProperty(String key, String value) { + throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); + } + + /** + * @see java.util.Hashtable#size() + */ + @Override + public synchronized int size() { + return properties.size(); + } + + /** + * @see java.util.Properties#store(java.io.OutputStream, java.lang.String) + */ + @Override + public void store(OutputStream out, String comments) throws IOException { + properties.store(out, comments); + } + + /** + * @see java.util.Properties#store(java.io.Writer, java.lang.String) + */ + @Override + public void store(Writer writer, String comments) throws IOException { + properties.store(writer, comments); + } + + /** + * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String) + */ + @Override + public synchronized void storeToXML(OutputStream os, String comment) throws IOException { + properties.storeToXML(os, comment); + } + + /** + * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) + */ + @Override + public synchronized void storeToXML(OutputStream os, String comment, String encoding) throws IOException { + properties.storeToXML(os, comment, encoding); + } + + /** + * @see java.util.Properties#stringPropertyNames() + */ + @Override + public Set stringPropertyNames() { + return properties.stringPropertyNames(); + } + + /** + * @see java.util.Hashtable#toString() + */ + @Override + public synchronized String toString() { + return properties.toString(); + } + + /** + * @see java.util.Hashtable#values() + */ + @Override + public Collection values() { + return Collections.unmodifiableCollection(properties.values()); + } +} diff --git a/appc-common/src/main/java/org/onap/appc/util/httpClient.java b/appc-common/src/main/java/org/onap/appc/util/httpClient.java new file mode 100644 index 000000000..edb27c6f6 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/httpClient.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; + + +public class httpClient { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(httpClient.class); + + private static Configuration configuration = ConfigurationFactory.getConfiguration(); + + @SuppressWarnings("deprecation") + public static int postMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { + + logger.info("Sending POST request to " + path); + + HttpPost post; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + post = new HttpPost(serviceUrl.toExternalForm()); + post.setHeader("Content-Type", contentType); + + StringEntity entity = new StringEntity(payload); + entity.setContentType(contentType); + post.setEntity(new StringEntity(payload)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new APPCException(e); + } + + logger.debug("Sending request " + post); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(ip, port), + new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new APPCException(e); + } + return httpCode; + } + + @SuppressWarnings("deprecation") + public static int putMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { + + logger.info("Sending PUT request to " + path); + + HttpPut put; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + put = new HttpPut(serviceUrl.toExternalForm()); + put.setHeader("Content-Type", contentType); + + StringEntity entity = new StringEntity(payload); + entity.setContentType(contentType); + put.setEntity(new StringEntity(payload)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new APPCException(e); + } + + logger.debug("Sending request " + put); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(ip, port), + new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + try { + HttpResponse response = client.execute(put); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new APPCException(e); + } + return httpCode; + } + + @SuppressWarnings("deprecation") + public static String getMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { + + logger.info("Sending GET request to " + path); + + HttpGet get; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + get = new HttpGet(serviceUrl.toExternalForm()); + get.setHeader("Content-Type", contentType); + } catch (MalformedURLException e) { + throw new APPCException(e); + } + + logger.debug("Sending request " + get); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(ip, port), + new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + String result; + + try { + HttpResponse response = client.execute(get); + httpCode = response.getStatusLine().getStatusCode(); + result = (httpCode == HttpStatus.SC_OK) ? response.getEntity().toString() : null; + } catch (IOException e) { + throw new APPCException(e); + } + + return result; + } + + @SuppressWarnings("deprecation") + public static int deleteMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { + + logger.info("Sending DELETE request to " + path); + + HttpDelete delete; + try { + + URL serviceUrl = new URL(protocol, ip, port, path); + delete = new HttpDelete(serviceUrl.toExternalForm()); + delete.setHeader("Content-Type", contentType); + } catch (MalformedURLException e) { + throw new APPCException(e); + } + + logger.debug("Sending request " + delete); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(ip, port), + new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider).build(); + + int httpCode; + String result; + + try { + HttpResponse response = client.execute(delete); + httpCode = response.getStatusLine().getStatusCode(); + } catch (IOException e) { + throw new APPCException(e); + } + + return httpCode; + } +} diff --git a/appc-common/src/main/java/org/openecomp/appc/CmdLine.java b/appc-common/src/main/java/org/openecomp/appc/CmdLine.java deleted file mode 100644 index d63bd8758..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/CmdLine.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - package org.onap.appc; - -import org.onap.appc.encryption.EncryptionTool; - -public class CmdLine { - - public static void main(String[] args) { - if(args.length <= 1 || args.length >= 3){ - printUsage(); - }else{ - String command = args[0]; - - switch(command){ - case "encrypt": - if(args[1]!= null){ - String clearText = args[1]; - String encrypted = EncryptionTool.getInstance().encrypt(clearText); - System.out.println(encrypted); - }else{ - printUsage(); - } - break; - default: - printUsage(); - break; - - } - } - - } - - private static void printUsage(){ - System.out.println("Usage: java -jar ..."); - System.out.println("\tencrypt \t\t(Encrypts your text)"); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/Constants.java b/appc-common/src/main/java/org/openecomp/appc/Constants.java deleted file mode 100644 index e030b647d..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/Constants.java +++ /dev/null @@ -1,212 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc; - -/** - * This class contains the definitions of all constant values used in the APPC provider, adapters, and other components. - * These constants define properties, settings, and context variables. The context variables can be referenced from - * within the directed graph(s) to access information placed their by the provider and adapters. - *

- * Context properties are set in the graph context by the various adapters and the provider, or by the graph itself. - * These properties may also be accessed by the graph, adapters, or the provider. It is these properties that allow - * communication of state through the directed graph. All context properties have a symbolic name that starts with - * "CONTEXT_". - *

- * - */ - -public final class Constants { - - /** - * The name for the error code attribute to be set in the context - */ - @SuppressWarnings("nls") - public static final String ATTRIBUTE_ERROR_CODE = "error_code"; - - /** - * The name for the error message attribute to be set in the context - */ - @SuppressWarnings("nls") - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - - /** - * The name for the success message attribute to be set in the context - */ - @SuppressWarnings("nls") - public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; - - public static final String DG_ATTRIBUTE_STATUS = "SvcLogic.status"; - public static final String DG_OUTPUT_STATUS_CODE = "output.status.code"; - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - - /** - * The property that defines the name of the DG service logic to be loaded - */ - public static final String PROPERTY_MODULE_NAME = "appc.service.logic.module.name"; - - /** - * The property that defines the topology restart DG version to be used - */ - public static final String PROPERTY_TOPOLOGY_VERSION = "appc.topology.dg.version"; - - /** - * The method name of the DG that is used to perform topology restart operations - */ - public static final String PROPERTY_TOPOLOGY_METHOD = "appc.topology.dg.method"; - - /** - * The property that supplies the application name - */ - public static final String PROPERTY_APPLICATION_NAME = "appc.application.name"; - - /** - * The execution mode for the directed graph - */ - public static final String SYNC_MODE = "sync"; - - /** - * The name of the property that contains the service request enumerated value in the graph's context - */ - public static final String CONTEXT_SERVICE = "org.onap.appc.service"; - - /** - * The name of the property that contains the VM id value in the graph's context - */ - public static final String CONTEXT_VMID = "org.onap.appc.vmid"; - - /** - * The name of the property that contains the VM id value in the graph's context - */ - public static final String CONTEXT_IDENTITY_URL = "org.onap.appc.identity.url"; - - /** - * The name of the property that contains the service request id value in the graph's context - */ - public static final String CONTEXT_REQID = "org.onap.appc.reqid"; - - /** - * The name of the property that indicates which method of the IaaS adapter to call - */ - public static final String CONTEXT_ACTION = "org.onap.appc.action"; - - /** - * The enumerated value for restart of a VM. This is a constant for one possible value of CONTEXT_SERVICE. - */ - public static final String SERVICE_RESTART = "RESTART"; - - /** - * The enumerated value for rebuild of a VM. This is a constant for one possible value of CONTEXT_SERVICE. - */ - public static final String SERVICE_REBUILD = "REBUILD"; - - /** - * The name of the adapter. We get the name from a property file so that it can be changed easily if needed. - */ - public static final String PROPERTY_ADAPTER_NAME = "org.onap.appc.provider.adaptor.name"; - - /** - * The minimum number of contexts to cache in each provider/tenant pool - */ - public static final String PROPERTY_MIN_POOL_SIZE = "org.onap.appc.provider.min.pool"; - - /** - * The maximum number of contexts to cache in each provider/tenant pool - */ - public static final String PROPERTY_MAX_POOL_SIZE = "org.onap.appc.provider.max.pool"; - - /** - * The amount of time, in seconds, that the application waits for a change of state of a server to a known valid - * state before giving up and failing the request. - */ - public static final String PROPERTY_SERVER_STATE_CHANGE_TIMEOUT = "org.onap.appc.server.state.change.timeout"; - - /** - * The amount of time, in seconds, between subsequent polls to the openstack provider to update the state of a - * resource - */ - public static final String PROPERTY_OPENSTACK_POLL_INTERVAL = "org.onap.appc.openstack.poll.interval"; - - /** - * The amount of time, in seconds, to wait between retry attempts when a connection to a provider fails. - */ - public static final String PROPERTY_RETRY_DELAY = "org.onap.appc.provider.retry.delay"; - - /** - * The maximum number of times a connection retry will be attempted before the application fails the request - */ - public static final String PROPERTY_RETRY_LIMIT = "org.onap.appc.provider.retry.limit"; - /** - * The amount of time, in seconds, that the application waits for a change of state of a stacj to a known valid - * state before giving up and failing the request. - */ - public static final String PROPERTY_STACK_STATE_CHANGE_TIMEOUT ="org.onap.appc.stack.state.change.timeout" ; - - @SuppressWarnings("nls") - public static final String STATUS_GETTER = "status-getter"; - - @SuppressWarnings("nls") - public static final String VM_FUSION_STATUS_GETTER = "fusion-vm-status-getter"; - - /** - * The name for the status vm attribute to be set in the context when executing a vmstatuscheck. - */ - - @SuppressWarnings("nls") - public static final String STATUS_OF_VM = "status-vm"; - - /** - * Yang revision value to be used while generating YANG module - */ - public static final String YANG_REVISION = "2017-03-03"; - /** - * Yang revision format to be used while formatting YANG revision date - */ - public static final String YANG_REVISION_FORMAT = "YYYY-MM-DD"; - - /** - * Base container for yang that is generated to store in MD-SAL datastore - */ - public static final String YANG_BASE_CONTAINER = "vnf-config-repo"; - - /** - *VNF config list for yang that is generated to store in MD-SAL datastore - */ - public static final String YANG_VNF_CONFIG_LIST = "vnf-config-list"; - - /** - *Base container of VNF configuration data for yang that is generated to store in MD-SAL datastore - */ - public static final String YANG_VNF_CONFIG = "vnf-config"; - - /** - * Private default constructor prevents instantiation - */ - - private Constants() { - - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategies.java b/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategies.java deleted file mode 100644 index fadf9cb4f..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategies.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache; - -/** - * Enum of CacheStrategies - */ -public enum CacheStrategies { - LRU -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategy.java b/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategy.java deleted file mode 100644 index af91bb28c..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/CacheStrategy.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache; - -/** - * Interface of CacheStrategy - * @param key - * @param value - */ -public interface CacheStrategy { - /** - * Get object - * @param key of the object - * @return value of the object - */ - V getObject(K key); - - /** - * Put object - * @param key of the object - * @param value of the object - */ - void putObject(K key,V value); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/MetadataCache.java b/appc-common/src/main/java/org/openecomp/appc/cache/MetadataCache.java deleted file mode 100644 index ea0cad28f..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/MetadataCache.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache; - -/** - * Interface of MetadataCache - * @param key - * @param value - */ -public interface MetadataCache { - /** - * Get object - * @param key of the object - * @return value of the object - */ - V getObject(K key); - - /** - * Put object - * @param key of the object - * @param value of the object - */ - void putObject(K key,V value); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/impl/LRUCache.java b/appc-common/src/main/java/org/openecomp/appc/cache/impl/LRUCache.java deleted file mode 100644 index b82552f20..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/impl/LRUCache.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.onap.appc.cache.CacheStrategy; - -/** - * LRU cache implements CacheStategy - * @param Key - * @param Value - */ -public class LRUCache implements CacheStrategy { - - private Map map; - - LRUCache(final Integer capacity){ - map = new LinkedHashMap(capacity, 0.75F, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest){ - return size() > capacity; - } - }; - } - - @Override - public V getObject(K key) { - return map.get(key); - } - - @Override - public void putObject(K key, V value) { - map.put(key,value); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheFactory.java b/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheFactory.java deleted file mode 100644 index c140c6e8b..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheFactory.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import org.onap.appc.cache.CacheStrategies; -import org.onap.appc.cache.MetadataCache; - -/** - * Metadata Cache Factory - */ -public class MetadataCacheFactory { - - private static class ReferenceHolder { - private ReferenceHolder() { - throw new IllegalAccessError("ReferenceHolder"); - } - - private static final MetadataCacheFactory FACTORY = new MetadataCacheFactory(); - } - - private MetadataCacheFactory() { - // do nothing - } - - public static MetadataCacheFactory getInstance(){ - return ReferenceHolder.FACTORY; - } - - public MetadataCache getMetadataCache(){ - return new MetadataCacheImpl(); - } - - /** - * Get MetadataCache - * @param cacheStrategy the CacheStrategies to be used to build MetadataCacheImpl - * @return a new instance of MetadataCacheImpl - */ - public MetadataCache getMetadataCache(CacheStrategies cacheStrategy) { - return new MetadataCacheImpl(cacheStrategy); - } - - - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheImpl.java b/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheImpl.java deleted file mode 100644 index ca225adfe..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/cache/impl/MetadataCacheImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import org.onap.appc.cache.CacheStrategies; -import org.onap.appc.cache.CacheStrategy; -import org.onap.appc.cache.MetadataCache; - -/** - * Implementation of MetadataCache - * @param Key - * @param Value - */ -public class MetadataCacheImpl implements MetadataCache { - - private CacheStrategy strategy; - - MetadataCacheImpl(){ - this(CacheStrategies.LRU); - } - - MetadataCacheImpl(CacheStrategies strategy){ - this.strategy = initializeStrategy(strategy); - } - - private CacheStrategy initializeStrategy(CacheStrategies strategy) { - if (strategy != null) { - switch (strategy) { - case LRU: - return new LRUCache<>(50); - default: - // do nothing - } - } - return null; - } - - @Override - public V getObject(K key) { - return (V)strategy.getObject(key); - } - - @Override - public void putObject(K key, V value) { - strategy.putObject(key,value); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/concurrent/Signal.java b/appc-common/src/main/java/org/openecomp/appc/concurrent/Signal.java deleted file mode 100644 index 5d439d164..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/concurrent/Signal.java +++ /dev/null @@ -1,231 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.concurrent; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import org.onap.appc.util.StringHelper; - -/** - * This class is used to synchronize signaling of status between threads. - *

- * In complex multi-threaded applications it is often necessary to synchronize operations between threads. This is - * especially true in complex algorithms where processing dependencies exist between different threads and the - * synchronization of the operations of those threads is required. This class is a framework to enable multi-thread - * signaling and wait/post logic that makes the thread synchronization easier. - *

- *

- * Basically, in thread synchronization, one thread is the "waiter" and one or more other threads are the "notifiers". - * The notifiers send signals to the waiter to inform that thread that certain conditions are true, processing has been - * completed, or to inform the waiter of the state of the other thread(s). In the basic java framework, the waiter and - * notifier are simply using the wait/notify mechanism provided, which does not allow for different conditions, state, - * or "signals" to exist. The wait/notify mechanism, in combination with the object mutex, provides basic blocking and - * releasing of a thread's dispatching state. - *

- *

- * This class builds upon the java wait/notify mechanism and allows for "signals" to be defined. These signals are - * simply string constants that mean something to the waiter and notifier threads. Any number of signals may be defined, - * and it is possible to wait for more than one signal to be received, wait for any one of a set to be received, or to - * test if a signal has been received without blocking. - *

- *

- * Some operations are blocking operations. These stop the execution of the calling thread until the specified condition - * is true. These blocking methods are all named "wait...", such as {@link #waitFor(String...)} and - * {@link #waitForAny(String...)}. The thread making the call to these blocking methods MUST be the waiter thread (the - * thread registered with the signal object). - *

- *

- * Some operations are non-blocking. These operations allow for the testing or setting of signal conditions and do not - * block the caller. When calling these methods ({@link #isSignaled(String)}, {@link #signal(String)}, and - * {@link #setTimeout(long)} the waiter thread mutex will be held and may block the waiter thread for the duration of - * the method call. - *

- */ -public class Signal { - - /** - * The thread must be the thread of the waiter that is waiting for the signals to be received. It is the recipient - * of the signaled condition. This allows any number of other threads to send signals to the recipient and have the - * recipient synchronize its operation with the receipt of the appropriate signal(s). - */ - private Thread thread; - - /** - * The amount of time to wait for a signal to be receieved. Set to zero to wait forever. - */ - private long timeout = 0L; - - /** - * The collection of all received signals. Note, this need not be a synchronized collection because it will always - * be accessed while holding the mutex of the thread, therefore it is implicitly synchronized. - */ - private List receivedSignals; - - /** - * A signal object must access a thread that is waiting for the receipt of the signal(s). - */ - public Signal(Thread thread) { - this.thread = thread; - receivedSignals = new ArrayList(); - } - - /** - * Checks the waiter to see if it has been signaled - * - * @param signal - * The signal to check for - * @return True if the signal has been received, false otherwise - */ - public boolean isSignaled(String signal) { - synchronized (thread) { - return _signaled(signal); - } - } - - /** - * Sends the indicated signal to the waiter. - * - * @param signal - * The signal that is to be sent to the waiting thread and to notify it to process the signal. - */ - public void signal(String signal) { - synchronized (thread) { - if (!_signaled(signal)) { - receivedSignals.add(signal); - } - thread.notify(); - } - } - - /** - * Blocks the waiting thread until all of the indicated signals have been received, or the wait times out. - * - * @param signals - * The signals to be received. The waiter is blocked forever or until all of the signals are received. - * @throws TimeoutException - * If the wait has timed out waiting for a response - */ - public void waitFor(String... signals) throws TimeoutException { - long limit = System.currentTimeMillis() + timeout; - synchronized (thread) { - while (true) { - boolean complete = true; - for (String signal : signals) { - if (!_signaled(signal)) { - complete = false; - } - } - - if (complete) { - receivedSignals.removeAll(Arrays.asList(signals)); - return; - } - - if (timeout > 0) { - if (System.currentTimeMillis() > limit) { - throw new TimeoutException(String.format("Signals %s not received in the allotted timeout.", - StringHelper.asList(signals))); - } - } - - try { - thread.wait(timeout); - } catch (InterruptedException e) { - /* - * Interrupted exceptions are ignored - */ - } - } - } - } - - /** - * This method blocks the waiter until at least one of the indicated signals have been received. - * - * @param signals - * A list of signals, any one of which will satisfy the wait condition - * @return The signal that satisfied the wait - * @throws TimeoutException - * If none of the signals have been received within the allotted time - */ - public String waitForAny(String... signals) throws TimeoutException { - long limit = System.currentTimeMillis() + timeout; - synchronized (thread) { - while (true) { - for (String signal : signals) { - if (!_signaled(signal)) { - receivedSignals.remove(signal); - return signal; - } - } - - if (timeout > 0) { - if (System.currentTimeMillis() > limit) { - throw new TimeoutException( - String.format("One of signals \"%s\" not received in the allotted timeout.", - StringHelper.asList(signals))); - } - } - - try { - thread.wait(timeout); - } catch (InterruptedException e) { - /* - * Interrupted exceptions are ignored - */ - } - } - } - } - - /** - * This private method is used to handle the check for signaled status. Note that this method assumes the caller - * holds the thread mutex. - * - * @param signals - * The list of signals to check for - * @return True if any one of the signals has been received. - */ - private boolean _signaled(String... signals) { - for (String signal : signals) { - if (receivedSignals.contains(signal)) { - return true; - } - } - return false; - } - - /** - * Sets the timeout value for waiting for signals to be received - * - * @param timeout - */ - public void setTimeout(long timeout) { - this.timeout = timeout; - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/configuration/Configuration.java b/appc-common/src/main/java/org/openecomp/appc/configuration/Configuration.java deleted file mode 100644 index a0acf12cc..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/configuration/Configuration.java +++ /dev/null @@ -1,243 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.configuration; - -import java.util.Properties; - -import org.slf4j.Logger; - - - -/** - * This interface defines the common configuration support that is available to the application. - *

- * Where properties are common to all CDP components (server, coordinator, and EPM), the property symbolic values are - * defined as part of this interface. Where they are unique to each component, they must be defined within that - * component. - *

- */ -public interface Configuration { - - String PROPERTY_BOOTSTRAP_FILE_NAME = "org_onap_appc_bootstrap_file"; // - String DEFAULT_BOOTSTRAP_FILE_NAME = "appc.properties"; - String PROPERTY_BOOTSTRAP_FILE_PATH = "org_onap_appc_bootstrap_path"; // - String DEFAULT_BOOTSTRAP_FILE_PATH = "/opt/openecomp/appc/data/properties,${user.home},etc,../etc"; - String PROPERTY_RESOURCE_BUNDLES = "org.onap.appc.resources"; - String DEFAULT_RESOURCE_BUNDLES = "org/onap/appc/i18n/MessageResources"; - - /** - * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for - * {@link Boolean#valueOf(String)} are used. - * - * @param key - * The property key - * @return The value of the property expressed as a boolean, or false if it does not exist. - */ - boolean getBooleanProperty(String key); - - /** - * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for - * {@link Boolean#valueOf(String)} are used. - * - * @param key - * The property key - * @param defaultValue - * The default value to be returned if the property does not exist - * @return The value of the property expressed as a boolean, or false if it does not exist. - */ - boolean getBooleanProperty(String key, boolean defaultValue); - - /** - * Returns the indicated property value expressed as a floating point double-precision value (double). The standard - * rules for {@link Double#valueOf(String)} are used. - * - * @param key - * The property to retrieve - * @return The value of the property, or 0.0 if not found or invalid - */ - double getDoubleProperty(String key); - - /** - * Returns the indicated property value expressed as a floating point double-precision value (double). The standard - * rules for {@link Double#valueOf(String)} are used. - * - * @param key - * The property to retrieve - * @param defaultValue - * The default value to be returned if the property does not exist - * @return The value of the property, or 0.0 if not found or invalid - */ - double getDoubleProperty(String key, double defaultValue); - - /** - * Returns the property indicated expressed as an integer. The standard rules for - * {@link Integer#parseInt(String, int)} using a radix of 10 are used. - * - * @param key - * The property name to retrieve. - * @return The value of the property, or 0 if it does not exist or is invalid. - */ - int getIntegerProperty(String key); - - /** - * Returns the property indicated expressed as an integer. The standard rules for - * {@link Integer#parseInt(String, int)} using a radix of 10 are used. - * - * @param key - * The property name to retrieve. - * @param defaultValue - * The default value to be returned if the property does not exist - * @return The value of the property, or 0 if it does not exist or is invalid. - */ - int getIntegerProperty(String key, int defaultValue); - - /** - * Returns the specified property as a long integer value, if it exists, or zero if it does not. - * - * @param key - * The key of the property desired. - * @return The value of the property expressed as an integer long value, or zero if the property does not exist or - * is not a valid integer long. - */ - long getLongProperty(String key); - - /** - * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist - * or is invalid. - * - * @param key - * The key of the property desired. - * @param defaultValue - * the value to be returned if the property is not valid or does not exist. - * @return The value of the property expressed as an integer long value, or the default value if the property does - * not exist or is not a valid integer long. - */ - long getLongProperty(String key, long defaultValue); - - /** - * This method can be called to retrieve a properties object that is immutable. Any attempt to modify the properties - * object returned will result in an exception. This allows a caller to view the current configuration as a set of - * properties. - * - * @return An unmodifiable properties object. - */ - Properties getProperties(); - - /** - * This method is called to obtain a property as a string value - * - * @param key - * The key of the property - * @return The string value, or null if it does not exist. - */ - String getProperty(String key); - - /** - * This method is called to obtain a property as a string value - * - * @param key - * The key of the property - * @param defaultValue - * The default value to be returned if the property does not exist - * @return The string value, or null if it does not exist. - */ - String getProperty(String key, String defaultValue); - - /** - * Returns true if the named property is defined, false otherwise. - * - * @param key - * The key of the property we are interested in - * @return True if the property exists. - */ - boolean isPropertyDefined(String key); - - /** - * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only - * if it has the value "true" or "false" (ignoring case). - * - * @param key - * The property to be checked - * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string - */ - boolean isValidBoolean(String key); - - /** - * Returns an indication if the indicated property represents a valid double-precision floating point number. - * - * @param key - * The property to be examined - * @return True if the property is a valid representation of a double, or false if it does not exist or contains - * illegal characters. - */ - boolean isValidDouble(String key); - - /** - * Returns an indication if the property is a valid integer value or not. - * - * @param key - * The key of the property to check - * @return True if the value is a valid integer string, or false if it does not exist or contains illegal - * characters. - */ - boolean isValidInteger(String key); - - /** - * Determines is the specified property exists and is a valid representation of an integer long value. - * - * @param key - * The property to be checked - * @return True if the property is a valid representation of an integer long value, and false if it either does not - * exist or is not valid. - */ - boolean isValidLong(String key); - - /** - * This method allows the caller to set all properties from a provided properties object into the configuration - * property set. - *

- * The primary difference between this method and the factory method - * {@link ConfigurationFactory#getConfiguration(Properties)} is that this method does not clear and reload the - * configuration. Rather, this method merges the provided properties object contents into the existing properties, - * replacing any same-named keys with the values from this object. - *

- * - * @param properties - * The properties object to copy all properties from - */ - void setProperties(Properties properties); - - /** - * This method allows a caller to insert a new property definition into the configuration object. This allows the - * application to adjust or add to the current configuration. If the property already exists, it is replaced with - * the new value. - * - * @param key - * The key of the property to be defined - * @param value - * The value of the property to be defined - */ - void setProperty(String key, String value); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/configuration/ConfigurationFactory.java b/appc-common/src/main/java/org/openecomp/appc/configuration/ConfigurationFactory.java deleted file mode 100644 index ee2648847..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/configuration/ConfigurationFactory.java +++ /dev/null @@ -1,421 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.configuration; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.DateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Properties; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; - -import org.onap.appc.i18n.Msg; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; - -/** - * The configuration factory is used to obtain access to an already created and initialized singleton configuration - * object as well as to create and initialize the singleton if not already set up. - *

- * This class is responsible for the creation of the configuration object used to manage the configuration of the - * application. The configuration object implementation must implement the Configuration interface. This - * allows for the factory to create different specializations in the future if needed and not break any application - * code. - *

- *

- * The configuration object is basically a wrapper around a properties object. The configuration is therefore specified - * as a set of properties that are loaded and processed from different sources with different precedences. It is - * important that the configuration object always be able to supply default values for any configuration properties that - * must be supplied, and not rely on the user always supplying these values. This also relieves the application itself - * from having to interpret missing or invalid properties and applying defaults. By having all of the defaults in one - * place, the application code can be simpler (not having to worry about defaults or invalid properties), and the - * defaults can be changed much easier (they are all in one place and not distributed throughout the codebase). - *

- *

- * Since the configuration is managed as a property object, we can use a characteristic of the Properties - * class to our advantage. Namely, if we put a property into a Properties object that already exists, the - * Properties object replaces it with the new value. This does not affect any other properties that may - * already be defined in the properties object. This gives us the ability to initialize the properties with default - * values for all of the application settings, then override just those that we need to override, possibly from multiple - * sources and in increasing order of precedence. - *

- *

- * This means that properties are in effect "merged" together from multiple sources in a prescribed precedence order. In - * fact, the precedence order that this factory implements is defined as: - *

- *
    - *
  1. Default values from a system resource file.
  2. - *
  3. User-supplied properties file, if any.
  4. - *
  5. Application-supplied properties, if any.
  6. - *
  7. Command-line properties (if any)
  8. - *
- *

- * The name and location of the properties file that is loaded can also be set, either in the defaults, overridden by - * the system command line via -D, or as a system environment variable. There are two properties that can be specified - * to define the name and path. These are: - *

- *
- *
org.onap.appc.bootstrap.file
- *
This property defines the name of the file that will be loaded. If not specified, the default value is - * "appc.properties". This can be specified in either (or both) the default properties or the command line. The command - * line specification will always override.
- *
org.onap.appc.bootstrap.path
- *
This is a comma-delimited (,) path of directories to be searched to locate the specified file. The first - * occurrence of the file is the one loaded, and no additional searching is performed. The path can be specified in - * either, or both, the default values and the command line specification. If specified on the command line, the value - * overrides the default values. If omitted, the default path is $/opt/openecomp/appc/data/properties,${user.home},.
- *
- * - * @since Mar 18, 2014 - * @version $Id$ - */ -public final class ConfigurationFactory { - - private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - /** - * This is a string constant for the comma character. It's intended to be used a common string delimiter. - */ - private static final String COMMA = ","; - - /** - * The default Configuration object that implements the Configuration interface and represents our - * system configuration settings. - */ - private static DefaultConfiguration config = null; - - /** - * The default properties resource to be loaded - */ - private static final String DEFAULT_PROPERTIES = "org/onap/appc/default.properties"; - - /** - * This collection allows for special configurations to be created and maintained, organized by some identification - * (such as an object reference to the StackBuilder to which they apply), and then obtained from the configuration - * factory when needed. - */ - private static HashMap localConfigs = new HashMap<>(); - - /** - * The reentrant shared lock used to serialize access to the properties. - */ - private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - /** - * This is a constant array of special property names that will be copied from the configuration back to the System - * properties object if they are defined in the configuration AND they do not already exist in the System properties - * object. These are intended as a convenience for setting the AFT properties for the Discovery client where it may - * be difficult or impossible to set VM arguments for the container. - */ - private static final String[] specialProperties = { - "AFT_LATITUDE", "AFT_LONGITUDE", "AFT_ENVIRONMENT", "SCLD_PLATFORM" - }; - - private ConfigurationFactory() { - } - - /** - * This method is used to obtain the common configuration object (as well as set it up if not already). - * - * @return The configuration object implementation - */ - public static Configuration getConfiguration() { - - /* - * First, attempt to access the properties as a read lock holder - */ - ReadLock readLock = lock.readLock(); - readLock.lock(); - try { - - /* - * If the properties don't exist, release the read lock and acquire the write lock. Once we get the write - * lock, we need to re-check to see that the configuration needs to be set up (because another thread may - * have beat us to it). After we get a configuration set up, release the write lock and re-obtain the read - * lock to access the properties. - */ - if (config == null) { - readLock.unlock(); - WriteLock writeLock = lock.writeLock(); - writeLock.lock(); - try { - if (config == null) { - config = new DefaultConfiguration(); - initialize(null); - } - } catch (Exception t) { - logger.error("getConfiguration", t); - } finally { - writeLock.unlock(); - } - readLock.lock(); - } - return config; - } finally { - readLock.unlock(); - } - } - - /** - * This method will obtain the local configuration for the specified object if it exists, or will create it from the - * current global configuration. This allows the configuration to be tailored for a specific process or operation, - * and uniquely identified by some value (such as the object that represents the special use of the configuration). - * - * @param owner - * The owner or identification of the owner of the special configuration - * @return The special configuration object, or a clone of the global configuration so that it can be altered if - * needed. - */ - public static Configuration getConfiguration(final Object owner) { - ReadLock readLock = lock.readLock(); - readLock.lock(); - try { - DefaultConfiguration local = (DefaultConfiguration) localConfigs.get(owner); - if (local == null) { - readLock.unlock(); - WriteLock writeLock = lock.writeLock(); - writeLock.lock(); - try { - local = (DefaultConfiguration) localConfigs.get(owner); - if (local == null) { - DefaultConfiguration global = (DefaultConfiguration) getConfiguration(); - try { - local = (DefaultConfiguration) global.clone(); - } catch (CloneNotSupportedException e) { - logger.error("getConfiguration", e); - } - localConfigs.put(owner, local); - } - } finally { - writeLock.unlock(); - } - readLock.lock(); - } - return local; - } finally { - readLock.unlock(); - } - } - - /** - * This method allows the caller to alter the configuration, supplying the specified configuration properties which - * override the application default values. - *

- * The configuration is re-constructed (if already constructed) or created new (if not already created) and the - * default properties are loaded into the configuration. - *

- *

- * The primary purpose of this method is to allow the application configuration properties to be reset or refreshed - * after the application has already been initialized. This method will lock the configuration for the duration - * while it is being re-built, and should not be called on a regular basis. - *

- * - * @param props - * The properties used to configure the application. - * @return Access to the configuration implementation - */ - public static Configuration getConfiguration(final Properties props) { - WriteLock writeLock = lock.writeLock(); - writeLock.lock(); - try { - config = new DefaultConfiguration(); - initialize(props); - return config; - } finally { - writeLock.unlock(); - } - } - - /** - * This method will clear the current configuration and then re-initialize it with the default values, - * application-specific configuration file, user-supplied properties (if any), and then command-line settings. - *

- * This method MUST be called holding the configuration lock! - *

- *

- * This method is a little special in that logging messages generated during the method must be cached and delayed - * until after the logging framework has been initialized. After that, the delayed logging buffer can be dumped to - * the log file and cleared. - *

- * - * @param props - * Application-supplied configuration values, if any - */ - private static void initialize(final Properties props) { - DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); - Date now = new Date(); - logger.info("------------------------------------------------------------------------------"); - - logger.info(Msg.CONFIGURATION_STARTED, format.format(now)); - - /* - * Clear any existing properties - */ - config.clear(); - logger.info(Msg.CONFIGURATION_CLEARED); - - /* - * Load the defaults (if any are present) - */ - InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_PROPERTIES); - if (in != null) { - logger.info(Msg.LOADING_DEFAULTS, DEFAULT_PROPERTIES); - try { - config.setProperties(in); - } finally { - try { - in.close(); - } catch (IOException e) { - // not much we can do since logger may not be configured yet - e.printStackTrace(System.out); - } - } - for (String key : config.getProperties().stringPropertyNames()) { - logger.info(Msg.PROPERTY_VALUE, key, config.getProperty(key)); - } - } else { - logger.info(Msg.NO_DEFAULTS_FOUND, DEFAULT_PROPERTIES); - } - - /* - * Look for application configuration property file. By default, we will look for the file "cdp.properties" on - * the user home path, then on "./etc" (relative to current path), then on "../etc" (relative to current path). - * If we do not find any property file, then we continue. Otherwise, we load the first property file we find and - * then continue. In order to allow default values for the filename and paths to be searched, we first attempt - * to obtain these from our configuration object (which should be primed with default values and/or overridden - * with application-specified values). We then use the values obtained from that to get any user supplied values - * on the command line. - */ - String filename = - config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, Configuration.DEFAULT_BOOTSTRAP_FILE_NAME); - filename = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, filename); - String env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME); - if (env != null && env.trim().length() > 0) { - filename = env; - } - - String path = - config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, Configuration.DEFAULT_BOOTSTRAP_FILE_PATH); - path = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, path); - env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH); - if (env != null && env.trim().length() > 0) { - path = env; - } - - logger.info(Msg.SEARCHING_CONFIGURATION_OVERRIDES, path, filename); - - String[] pathElements = path.split(COMMA); - boolean found = false; - for (String pathElement : pathElements) { - File file = new File(pathElement, filename); - if (file.exists() && file.canRead() && !file.isDirectory()) { - - logger.info(Msg.LOADING_CONFIGURATION_OVERRIDES, file.getAbsolutePath()); - Properties fileProperties = new Properties(); - BufferedInputStream stream = null; - try { - stream = new BufferedInputStream(new FileInputStream(file)); - fileProperties.load(stream); - for (String key : fileProperties.stringPropertyNames()) { - logger.debug(Msg.PROPERTY_VALUE, key, fileProperties.getProperty(key)); - config.setProperty(key, fileProperties.getProperty(key)); - } - found = true; - break; - } catch (IOException e) { - logger.error(EELFResourceManager.format(e)); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - // not much we can do since logger may not be configured - // yet - e.printStackTrace(System.out); - } - } - } - } - - if (!found) { - logger.warn(Msg.NO_OVERRIDE_PROPERTY_FILE_LOADED, filename, path); - } - - /* - * Apply any application-specified properties - */ - if (props != null) { - logger.info(Msg.LOADING_APPLICATION_OVERRIDES); - for (String key : props.stringPropertyNames()) { - logger.debug(Msg.PROPERTY_VALUE, key, props.getProperty(key)); - config.setProperty(key, props.getProperty(key)); - } - } else { - logger.info(Msg.NO_APPLICATION_OVERRIDES); - } - - /* - * Merge in the System.properties to pick-up any command line arguments (-Dkeyword=value) - */ - logger.info(Msg.MERGING_SYSTEM_PROPERTIES); - config.setProperties(System.getProperties()); - - /* - * As a convenience, copy the "specialProperties" that are not defined in System.properties from the - * configuration back to the system properties object. - */ - for (String key : config.getProperties().stringPropertyNames()) { - for (String specialProperty : specialProperties) { - if (key.equals(specialProperty) && !System.getProperties().containsKey(key)) { - System.setProperty(key, config.getProperty(key)); - logger.info(Msg.SETTING_SPECIAL_PROPERTY, key, config.getProperty(key)); - } - } - } - - /* - * Initialize the resource manager by loading the requested bundles, if any are defined. Resource bundles may be - * specified as a comma-delimited list of names. These resource names are base names of resource bundles, do not - * include the language or country code, or the ".properties" extension. The actual loading of the resource - * bundles is done lazily when requested the first time. If the bundle does not exist, or cannot be loaded, it - * is ignored. - */ - String resourcesList = - config.getProperty(Configuration.PROPERTY_RESOURCE_BUNDLES, Configuration.DEFAULT_RESOURCE_BUNDLES); - String[] resources = resourcesList.split(","); - for (String resource : resources) { - logger.info(Msg.LOADING_RESOURCE_BUNDLE, resource.trim()); - EELFResourceManager.loadMessageBundle(resource.trim()); - } - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java b/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java deleted file mode 100644 index 3e86c0788..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java +++ /dev/null @@ -1,557 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.configuration; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.security.CodeSource; -import java.security.ProtectionDomain; -import java.security.Provider; -import java.security.Provider.Service; -import java.security.Security; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.jar.JarFile; -import java.util.jar.Manifest; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.onap.appc.encryption.EncryptionTool; -import org.onap.appc.util.UnmodifiableProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class provides the implementation of the Configuration interface. It is created by the - * ConfigurationFactory and initialized with the configuration values for the process. - * - * @version $Id$ - * @since Mar 18, 2014 - */ -public final class DefaultConfiguration implements Configuration, Cloneable { - - private static final Logger logger = LoggerFactory.getLogger(DefaultConfiguration.class); - - /** - * The framework configuration properties. - */ - private Properties properties = new Properties(); - - /** - * Construct the configuration object. - */ - DefaultConfiguration() { - // do nothing - } - - /** - * Clears all properties - */ - public void clear() { - properties.clear(); - } - - /** - * @see java.lang.Object#clone() - */ - @Override - protected Object clone() throws CloneNotSupportedException { - DefaultConfiguration clone = (DefaultConfiguration) super.clone(); - - clone.properties = new Properties(this.properties); - clone.properties.putAll(this.properties); - - return clone; - } - - /** - * Decrypts an encrypted value, if it is encrypted, and returns the clear text. Performs no operation on the string - * if it is not encrypted. - * - * @param value The value to (optionally) be decrypted - * @return The clear text - */ - @SuppressWarnings("nls") - private static String decrypt(String value) { - if (value != null && value.startsWith(EncryptionTool.ENCRYPTED_VALUE_PREFIX)) { - try { - return EncryptionTool.getInstance().decrypt(value); - } catch (Exception e) { - StringBuilder out = new StringBuilder(); - for (Provider p : Security.getProviders()) { - for (Service s : p.getServices()) { - String algo = s.getAlgorithm(); - out.append(String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", - algo, p.getName(), s.getClassName())); - } - } - logger.debug(out.toString()); - logger.warn(String.format("Could not decrypt the configuration value [%s]", value), e); - } - } - return value; - } - - /** - * Decrypts all elements in the properties object - */ - private void decryptAllProperties() { - if (properties != null) { - for (Entry e : properties.entrySet()) { - if (e.getValue() != null) { - e.setValue(decrypt(e.getValue().toString())); - } - } - } - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - - if (this.getClass() != obj.getClass()) { - return false; - } - - DefaultConfiguration other = (DefaultConfiguration) obj; - - return (this.properties.size() == other.properties.size()) - && (this.properties.entrySet().containsAll(other.properties.entrySet())) - && (other.properties.entrySet().containsAll(this.properties.entrySet())); - - } - - /** - * This method will use the properties object to expand any variables that may be present in the template provided. - * Variables are represented by the string "${name}", where "name" is the name of a property defined in either the - * current configuration object, or system properties if undefined. If the value cannot be found, the variable is - * removed and an empty string is used to replace the variable. - * - * @param template The template to be expanded - * @return The expanded template where each variable is replaced with its value - */ - @SuppressWarnings("nls") - private String expandVariables(String template) { - if (template == null) { - return null; - } - - // Decrypt the template if needed - // template = decrypt(template); DH: Do not assign values to parameters, bad form! Also, Sonar complains - // bitterly - - StringBuilder builder = new StringBuilder(decrypt(template)); - Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}"); - Matcher matcher = pattern.matcher(builder); - while (matcher.find()) { - String variable = matcher.group(1); - String value = properties.getProperty(variable); - if (value == null) { - value = System.getProperty(variable); - } - if (value == null) { - value = ""; - } - builder.replace(matcher.start(), matcher.end(), value); - - matcher.reset(); - } - return builder.toString().trim(); - } - - /** - * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for - * Boolean.parseBoolean() are used. - * - * @param key The property key - * @return The value of the property expressed as a boolean, or false if it does not exist. - */ - @SuppressWarnings("nls") - @Override - public boolean getBooleanProperty(String key) { - return Boolean.valueOf(getProperty(key, "false")); - } - - /** - * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for - * Boolean.valueOf(String) are used. - * - * @param key The property key - * @param defaultValue The default value to be returned if the property does not exist - * @return The value of the property expressed as a boolean, or false if it does not exist. - * @see org.onap.appc.configuration.Configuration#getBooleanProperty(java.lang.String, boolean) - */ - @Override - public boolean getBooleanProperty(String key, boolean defaultValue) { - if (isPropertyDefined(key)) { - return getBooleanProperty(key); - } - return defaultValue; - } - - /** - * Returns the indicated property value expressed as a floating point double-precision value (double). - * - * @param key The property to retrieve - * @return The value of the property, or 0.0 if not found - * @see org.onap.appc.configuration.Configuration#getDoubleProperty(java.lang.String) - */ - @SuppressWarnings("nls") - @Override - public double getDoubleProperty(String key) { - try { - return Double.valueOf(getProperty(key, "0.0")); - } catch (NumberFormatException e) { - return 0.0; - } - } - - /** - * This method is called to obtain a property as a string value - * - * @param key The key of the property - * @param defaultValue The default value to be returned if the property does not exist - * @return The string value, or null if it does not exist. - * @see org.onap.appc.configuration.Configuration#getDoubleProperty(java.lang.String, double) - */ - @Override - public double getDoubleProperty(String key, double defaultValue) { - if (isPropertyDefined(key)) { - return getDoubleProperty(key); - } - return defaultValue; - } - - /** - * Returns the property indicated expressed as an integer. The standard rules for - * {@link Integer#parseInt(String, int)} using a radix of 10 are used. - * - * @param key The property name to retrieve. - * @return The value of the property, or 0 if it does not exist or is invalid. - * @see org.onap.appc.configuration.Configuration#getIntegerProperty(java.lang.String) - */ - @SuppressWarnings("nls") - @Override - public int getIntegerProperty(String key) { - try { - return Integer.parseInt(getProperty(key, "0"), 10); - } catch (NumberFormatException e) { - return 0; - } - } - - /** - * Returns the property indicated expressed as an integer. The standard rules for Integer.parseInt(String, int) - * using a radix of 10 are used. - * - * @param key The property name to retrieve. - * @param defaultValue The default value to be returned if the property does not exist - * @return The value of the property, or 0 if it does not exist or is invalid. - * @see org.onap.appc.configuration.Configuration#getIntegerProperty(java.lang.String, int) - */ - @Override - public int getIntegerProperty(String key, int defaultValue) { - if (isPropertyDefined(key)) { - return getIntegerProperty(key); - } - return defaultValue; - } - - /** - * Returns the specified property as a long integer value, if it exists, or zero if it does not. - * - * @param key The key of the property desired. - * @return The value of the property expressed as an integer long value, or zero if the property does not exist or - * is not a valid integer long. - * @see org.onap.appc.configuration.Configuration#getLongProperty(java.lang.String) - */ - @SuppressWarnings("nls") - @Override - public long getLongProperty(String key) { - try { - return Long.parseLong(getProperty(key, "0"), 10); - } catch (NumberFormatException e) { - return 0; - } - } - - /** - * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist - * or is invalid. - * - * @param key The key of the property desired. - * @param defaultValue the value to be returned if the property is not valid or does not exist. - * @return The value of the property expressed as an integer long value, or the default value if the property does - * not exist or is not a valid integer long. - * @see org.onap.appc.configuration.Configuration#getLongProperty(java.lang.String, long) - */ - @Override - public long getLongProperty(String key, long defaultValue) { - if (isPropertyDefined(key)) { - return getLongProperty(key); - } - return defaultValue; - } - - /** - * This method can be called to retrieve a properties object that is immutable. Any attempt to modify the properties - * object returned will result in an exception. This allows a caller to view the current configuration as a set of - * properties. - * - * @return An unmodifiable properties object. - * @see org.onap.appc.configuration.Configuration#getProperties() - */ - @Override - public Properties getProperties() { - return new UnmodifiableProperties(properties); - } - - /** - * This method is called to obtain a property as a string value - * - * @param key The key of the property - * @return The string value, or null if it does not exist. - */ - @Override - public String getProperty(String key) { - String value = properties.getProperty(key); - if (value == null) { - return null; - } - return expandVariables(value.trim()); - } - - /** - * This method is called to obtain a property as a string value - * - * @param key The key of the property - * @param defaultValue The default value to be returned if the property does not exist - * @return The string value, or null if it does not exist. - * @see org.onap.appc.configuration.Configuration#getProperty(java.lang.String, java.lang.String) - */ - @Override - public String getProperty(String key, String defaultValue) { - if (isPropertyDefined(key)) { - return getProperty(key); - } - - if (defaultValue == null) { - return null; - } - - return expandVariables(defaultValue.trim()); - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return properties == null ? 0 : properties.hashCode(); - } - - /** - * Returns true if the named property is defined, false otherwise. - * - * @param key The key of the property we are interested in - * @return True if the property exists. - */ - @Override - public boolean isPropertyDefined(String key) { - return properties.containsKey(key); - } - - /** - * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only - * if it has the value "true" or "false" (ignoring case). - * - * @param key The property to be checked - * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string - * @see org.onap.appc.configuration.Configuration#isValidBoolean(java.lang.String) - */ - @SuppressWarnings("nls") - @Override - public boolean isValidBoolean(String key) { - String value = getProperty(key); - if (value != null) { - value = value.toLowerCase(); - return value.matches("true|false"); - } - return false; - } - - /** - * Returns an indication if the indicated property represents a valid double-precision floating point number. - * - * @param key The property to be examined - * @return True if the property is a valid representation of a double, or false if it does not exist or contains - * illegal characters. - * @see org.onap.appc.configuration.Configuration#isValidDouble(java.lang.String) - */ - @Override - public boolean isValidDouble(String key) { - String value = getProperty(key); - if (value != null) { - try { - Double.valueOf(value); - return true; - } catch (NumberFormatException e) { - return false; - } - } - return false; - } - - /** - * Returns an indication if the property is a valid integer value or not. - * - * @param key The key of the property to check - * @return True if the value is a valid integer string, or false if it does not exist or contains illegal - * characters. - * @see org.onap.appc.configuration.Configuration#isValidInteger(java.lang.String) - */ - @Override - public boolean isValidInteger(String key) { - String value = getProperty(key); - if (value != null) { - try { - Integer.parseInt(value.trim(), 10); - return true; - } catch (NumberFormatException e) { - return false; - } - } - return false; - } - - /** - * Determines is the specified property exists and is a valid representation of an integer long value. - * - * @param key The property to be checked - * @return True if the property is a valid representation of an integer long value, and false if it either does not - * exist or is not valid. - * @see org.onap.appc.configuration.Configuration#isValidLong(java.lang.String) - */ - @Override - public boolean isValidLong(String key) { - String value = getProperty(key); - if (value != null) { - try { - Long.parseLong(value.trim(), 10); - return true; - } catch (NumberFormatException e) { - return false; - } - } - return false; - } - - /** - * This method allows an implementation to load configuration properties that may override default values. - * - * @param is An input stream that contains the properties to be loaded - */ - public void setProperties(InputStream is) { - try { - properties.load(is); - } catch (IOException e) { - logger.warn("setProperties with inputStream got exception", e); - } - } - - /** - * This method allows an implementation to load configuration properties that may override default values. - * - * @param props An optional Properties object to be merged into the configuration, replacing any same-named - * properties. - * @see org.onap.appc.configuration.Configuration#setProperties(java.util.Properties) - */ - @Override - public void setProperties(Properties props) { - properties.putAll(props); - decryptAllProperties(); - } - - /** - * This method allows a caller to insert a new property definition into the configuration object. This allows the - * application to adjust or add to the current configuration. If the property already exists, it is replaced with - * the new value. - * - * @param key The key of the property to be defined - * @param value The value of the property to be defined - * @see org.onap.appc.configuration.Configuration#setProperty(java.lang.String, java.lang.String) - */ - @Override - public void setProperty(String key, String value) { - properties.setProperty(key, decrypt(value)); - } - - /** - * @see java.lang.Object#toString() - */ - @SuppressWarnings("nls") - @Override - public String toString() { - return String.format("Configuration: %d properties, keys:[%s]", - properties.size(), properties.keySet().toString()); - } - - /** - * This is a helper method to read the manifest of the jar file that this class was loaded from. Note that this will - * only work if the code is packaged in a jar file. If it is an open deployment, such as under eclipse, this will - * not work and there is code added to detect that case. - * - * @return The manifest object from the jar file, or null if the code is not packaged in a jar file. - */ - @SuppressWarnings({ - "unused", "nls" - }) - private Manifest getManifest() { - ProtectionDomain domain = getClass().getProtectionDomain(); - CodeSource source = domain.getCodeSource(); - URL location = source.getLocation(); - String path = location.getPath(); - int index = path.indexOf('!'); - if (index != -1) { - path = path.substring(0, index); - } - if (path.endsWith(".jar")) { - try (JarFile jar = new JarFile(location.getFile())) { - return jar.getManifest(); - } catch (IOException e) { - logger.error("getManifest", e); - } - } - - return null; - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/configuration/package.html b/appc-common/src/main/java/org/openecomp/appc/configuration/package.html deleted file mode 100644 index c6889da9a..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/configuration/package.html +++ /dev/null @@ -1,174 +0,0 @@ - - - - -Configuration - - - -

- CDP Configuration support is provided by a common framework to load - and manage configuration properties from multiple sources. The basic - concept is to load a set of default properties from a known resource - file located on the class path, and then override these defaults - with optional settings that can be provided by a user through either - additional property files or via the command line (as VM arguments). - The loading of defaults from a resource property file (named com/att/cdp/default.properties) - ensures that values are defined for properties the application needs - in order to operate. -

-

- One of these default values that can be set is the name of the - property file that allows the user to supply settings, as well as - the path where the file can be found. In general, the default name - of the property file will be "cdp.properties", - and the path that will be searched is "${user.home};etc;../etc". - However, these values can be changed through the use of the - default.properties resource file. The property that specifies the - property file name is named com.att.cdp.bootstrap.file, - while the property named com.att.cdp.bootstrap.path - specifies the search path. -

-

- After the default.properties are loaded, but prior to searching for - the application configuration file, the configuration factory checks - for properties com.att.cdp.bootstrap.path and com.att.cdp.bootstrap.file - in the System properties object (meaning they were set by the - command line). If these values are defined in the system properties - object, they are used. If not, these values are obtained from the - default properties just loaded. This allows the specification of - either the file name or path, or both, to be overridden during start - up by using command-line arguments. -

-

The search path is scanned for the - first occurrence of the specified property file. The first - occurrence is loaded and scanning is stopped at that point. The - configuration factory does not load all occurrences it finds, only - the first occurrence it finds.

-

The configuration properties are - loaded and processed according to a defined precedence order, such - that properties defined with a higher precedence override the same - property at a lower precedence. The precedence order is defined as - follows:

-

Precedence Order

-
    -
  1. Default properties are initially loaded into the - configuration. These default properties are the lowest level - precedence, and will be overridden by any properties specified at - higher levels. These are loaded from resources that are packaged - as part of the various application components. Each component - (Server, Coordinator, EPM, or CLI) may have different default - properties. The default properties are loaded from a resource - named com/att/cdp/default.properties. The default - properties can specify the name of the application property file - to be used to configure the application, as well as the path to - search. Additionally, these properties can be supplied via the - command line to override the default settings if needed.

    -
  2. -
  3. The configuration factory allows for the application to - supply an initial properties object to initialize the - configuration. This properties object could be loaded or created - in any way necessary for the application. This is totally up to - the application to define, if it is needed. If no - application-specific property object is supplied, this step is - skipped. If a property object is supplied, it is used to replace - or set any properties that may have been defined by the defaults.
    -
    -
  4. -
  5. The configuration factory will then search for a bootstrap - file on a bootstrap path. The actual bootstrap file name and path - can be specified as properties on the command line, or will - default to a file name of cdp.properties and a - path of ${user.home};etc;../etc. If desired, the - user can specify the exact name of the property file to be loaded - as well as the path using -Dcom.att.cdp.bootstrap.file=<filename> - and -Dcom.att.cdp.bootstrap.path=<path>. - These properties are set to default values by the default - properties loaded in step #1 above. The first occurrence of a - property file is the file loaded and used. Any other occurrences - are not processed.

    -
  6. -
  7. The System properties are then merged into the - configuration. This allows the highest level of precedence, - command-line VM arguments (-Dname=value) to be - merged into the configuration property object. These settings - override all lower level settings of the same name, as well as - merge all system properties into the configuration object. -
  8. -
-

Variables

-

- The configuration support allows for variables to be inserted into - any property that is defined. Variables are named using the format ${name}, - where the "name" is the name of a property that is defined - in the configuration, or a system property (such as user.home). - Variables can nest, such that a variable can be replaced with - another variable, which is then reevaluated to obtain the value. - This allows for indirection as well as variable substitution, if - needed. -

-

Using the Configuration Support

-

- The configuration support was designed to be easy to use. The - configuration implementation is abstracted away from the application - so that it could be changed easily in the future if needed, or if we - needed to load different implementations for different reasons. This - means that the application always accesses the configuration through - an interface, named Configuration. The - implementation of that configuration interface is obtained by a - static method on the ConfigurationFactory class. - The configuration factory will both create the configuration if not - already created on the first access, as well as return the current - configuration if already created. Additionally, the - ConfigurationFactory provides mechanisms to recreate the - configuration after the application is initialized should the need - arise to update its configuration. -

-

An example of the code needed to - obtain access to the configuration is:

-
Configuration config = ConfigurationFactory.getConfiguration();
-

Please refer to the javadoc or the - source code in cdp-common for other ways that the configuration and - configuration factory can be used.

-

Reloading Properties

-

The configuration support allows - for properties to be re-loaded and re-evaluated after the - application is running. This is designed to allow a configuration to - be refreshed should the need arise. This could allow on-demand - refresh (via a command, for example), or automatically based on - sensing a change in the configuration file.

-

- When the ConfigurationFactory method getConfiguration(Properties) - is called, the current configuration is cleared and rebuilt using - the process defined above. The supplied property object is used in - step #2 of the process. While the properties are being re-built, no - access to the properties are allowed. Any attempt to access - properties while the re-build operation is in effect will block the - caller until completed. This is accomplished using read and write - shared locks. -

- - ->>>>>>> app-controller/master:appc-common/src/main/java/org/onap/appc/configuration/package.html diff --git a/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionException.java b/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionException.java deleted file mode 100644 index 519933598..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryption; - -public class EncryptionException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 8259594446628138378L; - - public EncryptionException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionTool.java b/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionTool.java deleted file mode 100644 index 5d6d7ab33..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/encryption/EncryptionTool.java +++ /dev/null @@ -1,215 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryption; - -import java.security.Provider; -import java.security.Provider.Service; -import java.security.Security; - -import javax.crypto.Cipher; - -import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; -import org.jasypt.util.text.BasicTextEncryptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is used to encapsulate the encryption and decryption support in one place and to provide a utility to - * encrypt and decrypt data. - */ -public class EncryptionTool { - - /** - * This lock object is used ONLY if the singleton has not been set up. - */ - private static final Object lock = new Object(); - - /** - * The salt is used to initialize the PBE (password Based Encrpytion) algorithm. - */ - private static final byte[] DEFAULT_SALT = { - (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 - }; - - /** - * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt - * it - */ - @SuppressWarnings("nls") - public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; - - /** - * The instance of the encryption utility object - */ - private static EncryptionTool instance = null; - - /** - * The iteration count used to initialize the PBE algorithm and to generate the key spec - */ - private static final int ITERATION_COUNT = 20; - - /** - * The logger for this class. - */ - private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); - - /** - * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a - * symmetrical cipher. - */ - private static char[] secret = { - 'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', '/', '%', 'Y', '\\', 'f', - 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w', - 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V' - }; - - /** - * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 - * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. - */ - @SuppressWarnings("nls") - private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; - - /** - * The decryption cipher object - */ - private Cipher decryptCipher = null; - - /** - * The encryption cipher object - */ - private Cipher encryptCipher = null; - - private BasicTextEncryptor encryptor; - - /** - * Get an instance of the EncryptionTool - * - * @return The encryption tool to be used - */ - public static final EncryptionTool getInstance() { - if (instance == null) { - synchronized (lock) { - if (instance == null) { - instance = new EncryptionTool(); - } - } - } - return instance; - } - - /** - * Create the EncryptionTool instance - */ - @SuppressWarnings("nls") - private EncryptionTool() { - String out = "Found the following security algorithms:"; - for (Provider p : Security.getProviders()) { - for (Service s : p.getServices()) { - String algo = s.getAlgorithm(); - out += - String.format("\n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), - s.getClassName()); - } - } - LOG.debug(out); - } - - /** - * Decrypt the provided encrypted text - * - * @param cipherText - * THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is. - * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted. - */ - @SuppressWarnings("nls") - public synchronized String decrypt(String cipherText) { - if (isEncrypted(cipherText)) { - String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length()); - byte[] plainByte = Base64.decodeBase64(encValue.getBytes()); - byte[] decryptByte = xorWithSecret(plainByte); - return new String(decryptByte); - } else { - return cipherText; - } - - } - - /** - * Encrypt the provided clear text - * - * @param clearText - * The clear text to be encrypted - * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned. - * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the - * clear text is encrypted and returned. - */ - @SuppressWarnings("nls") - public synchronized String encrypt(String clearText) { - if (clearText != null) { - byte[] encByte = xorWithSecret(clearText.getBytes()); - String encryptedValue = new String(Base64.encodeBase64(encByte)); - return ENCRYPTED_VALUE_PREFIX + encryptedValue; - } else { - return null; - } - } - - /** - * Is a value encrypted? A value is considered to be encrypted if it begins with the - * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. - * - * @param value - * the value to check. - * @return true/false; - */ - private static boolean isEncrypted(final String value) { - return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX); - } - - /** - * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer - * and returns a byte array the same size as input - * - * @param inp - * The byte array to be XORed with secret - * @return A byte array the same size as inp or null if input is null. - */ - private byte[] xorWithSecret(byte[] inp) { - if (inp == null) { - return null; - } - - byte[] secretBytes = new String(secret).getBytes(); - int size = inp.length; - - byte[] out = new byte[size]; - for (int i = 0; i < size; i++) { - out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length])); - } - return out; - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/encryption/HexHelper.java b/appc-common/src/main/java/org/openecomp/appc/encryption/HexHelper.java deleted file mode 100644 index 250a17efb..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/encryption/HexHelper.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryption; - -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * HexHelper utility used for encryption/decryption - */ -public final class HexHelper { - - @SuppressWarnings({ - "javadoc", "nls" - }) - public static final String CM_PATH = "@(#) [viewpath]/[item]"; - - @SuppressWarnings({ - "nls", "javadoc" - }) - public static final String CM_PROJECT = "@(#) [environment] [baseline]"; - - @SuppressWarnings({ - "javadoc", "nls" - }) - public static final String CM_VERSION = "@(#) [version] [crtime]"; - - private static final char[] HEX_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', - 'E', 'F' }; - - /** - * The logger for this class. - */ - private static final Logger LOG = LoggerFactory.getLogger(HexHelper.class); - - private static Map TextToHex; - - static { - TextToHex = new HashMap<>(); - TextToHex.put(Character.valueOf('0'), Integer.valueOf(0)); - TextToHex.put(Character.valueOf('1'), Integer.valueOf(1)); - TextToHex.put(Character.valueOf('2'), Integer.valueOf(2)); - TextToHex.put(Character.valueOf('3'), Integer.valueOf(3)); - TextToHex.put(Character.valueOf('4'), Integer.valueOf(4)); - TextToHex.put(Character.valueOf('5'), Integer.valueOf(5)); - TextToHex.put(Character.valueOf('6'), Integer.valueOf(6)); - TextToHex.put(Character.valueOf('7'), Integer.valueOf(7)); - TextToHex.put(Character.valueOf('8'), Integer.valueOf(8)); - TextToHex.put(Character.valueOf('9'), Integer.valueOf(9)); - TextToHex.put(Character.valueOf('A'), Integer.valueOf(10)); - TextToHex.put(Character.valueOf('B'), Integer.valueOf(11)); - TextToHex.put(Character.valueOf('C'), Integer.valueOf(12)); - TextToHex.put(Character.valueOf('D'), Integer.valueOf(13)); - TextToHex.put(Character.valueOf('E'), Integer.valueOf(14)); - TextToHex.put(Character.valueOf('F'), Integer.valueOf(15)); - } - - /** - * Default private constructor prevents instantiation - */ - private HexHelper() { - // no-op - } - - /** - * Converts an array of bytes to the equivalent string representation using hexadecimal notation and returning that - * representation in a StringBuffer. - * - * @param bytes - * The bytes to be converted to a hexadecimal string - * @return The string representation - */ - public static StringBuffer convertBytesToHexSB(byte[] bytes) { - StringBuffer sb = new StringBuffer(bytes.length * 2); - int byteLen = bytes.length; - for (int index = 0; index < byteLen; index++) { - char tempChar; - // Get the first 4 bits (high) Do bitwise logical AND to get rid of - // low nibble. Shift results to right by 4 and get char - // representation - tempChar = HEX_TABLE[((bytes[index] & 0xf0) >>> 4)]; - sb.append(tempChar); - - // Get the last 4 bits (low) Do bitwise logical AND to get rid of - // high nibble. Get char representation - tempChar = HEX_TABLE[(bytes[index] & 0x0f)]; - sb.append(tempChar); - } - return sb; - } - - /** - * Converts a hexadecimal string representation of a binary value to an array of bytes - * - * @param hexValue - * The hex representation string to be converted - * @return The array of bytes that contains the binary value - */ - @SuppressWarnings("nls") - public static byte[] convertHexToBytes(String hexValue) { - byte[] bytes = null; - byte high; - byte low; - char hexChar; - - StringBuffer buffer = new StringBuffer(hexValue.toUpperCase()); - if (buffer.length() % 2 != 0) { - LOG.warn("Invalid HEX value length. " - + "The length of the value has to be a multiple of 2. Prepending '0' value."); - buffer.insert(0, '0'); - } - int hexLength = buffer.length(); - int byteLength = hexLength / 2; - - bytes = new byte[byteLength]; - for (int index = 0; index < hexLength; index += 2) { - hexChar = buffer.charAt(index); - high = (TextToHex.get(Character.valueOf(hexChar))).byteValue(); - high = (byte) (high << 4); - hexChar = buffer.charAt(index + 1); - low = (TextToHex.get(Character.valueOf(hexChar))).byteValue(); - high = (byte) (high | low); - bytes[index / 2] = high; - } - return bytes; - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/exceptions/APPCException.java b/appc-common/src/main/java/org/openecomp/appc/exceptions/APPCException.java deleted file mode 100644 index 0efed763c..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/exceptions/APPCException.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -/** - * This is a base class for all APPC defined exceptions. - */ - -public class APPCException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be - * initialized by a call to initCause. - */ - public APPCException() { - } - - /** - * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently - * be initialized by a call to initCause. - * - * @param message - * the detail message. The detail message is saved for later retrieval by the getMessage() method. - */ - public APPCException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified cause and a detail message of (cause==null ? null : - * cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for example, - * java.security.PrivilegedActionException). - * - * @param cause - * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - */ - public APPCException(Throwable cause) { - super(cause); - } - - /** - * - Constructs a new exception with the specified detail message and cause. - *

- * Note that the detail message associated with cause is not automatically incorporated in this exception's detail - * message. - *

- * - * @param message - * the detail message (which is saved for later retrieval by the getMessage() method). - * @param cause - * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - */ - public APPCException(String message, Throwable cause) { - super(message, cause); - } - - /** - * - Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and - * writable stack trace enabled or disabled. - * - * @param message - * the detail message. - * @param cause - * the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression - * whether or not suppression is enabled or disabled - * @param writableStackTrace - * whether or not the stack trace should be writable - */ - public APPCException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidInputException.java b/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidInputException.java deleted file mode 100644 index 4a82ba83b..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidInputException.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -public class InvalidInputException extends Exception { - public InvalidInputException(String message){ - super(message); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidStateException.java b/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidStateException.java deleted file mode 100644 index d29b93117..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/exceptions/InvalidStateException.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -public class InvalidStateException extends Exception { - public InvalidStateException(String message) { - super(message); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/exceptions/UnknownProviderException.java b/appc-common/src/main/java/org/openecomp/appc/exceptions/UnknownProviderException.java deleted file mode 100644 index 89b29e652..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/exceptions/UnknownProviderException.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -/** - * This exception indicates that the named provider could not be found or was unidentifiable. - */ -public class UnknownProviderException extends APPCException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be - * initialized by a call to initCause. - */ - public UnknownProviderException() { - } - - /** - * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently - * be initialized by a call to initCause. - * - * @param message - * the detail message. The detail message is saved for later retrieval by the getMessage() method. - */ - public UnknownProviderException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified cause and a detail message of (cause==null ? null : - * cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for example, - * java.security.PrivilegedActionException). - * - * @param cause - * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - */ - public UnknownProviderException(Throwable cause) { - super(cause); - } - - /** - * - Constructs a new exception with the specified detail message and cause. - *

- * Note that the detail message associated with cause is not automatically incorporated in this exception's detail - * message. - *

- * - * @param message - * the detail message (which is saved for later retrieval by the getMessage() method). - * @param cause - * the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - */ - public UnknownProviderException(String message, Throwable cause) { - super(message, cause); - } - - /** - * - Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and - * writable stack trace enabled or disabled. - * - * @param message - * the detail message. - * @param cause - * the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression - * whether or not suppression is enabled or disabled - * @param writableStackTrace - * whether or not the stack trace should be writable - */ - public UnknownProviderException(String message, - Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/i18n/Msg.java b/appc-common/src/main/java/org/openecomp/appc/i18n/Msg.java deleted file mode 100644 index b6a0657a0..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/i18n/Msg.java +++ /dev/null @@ -1,824 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.i18n; - -import com.att.eelf.i18n.EELFResolvableErrorEnum; -import com.att.eelf.i18n.EELFResourceManager; - -/** - * The messages issued by APPC components. - *

- * This message definition is shared by all APPC components. - *

- * - */ -@SuppressWarnings("nls") -public enum Msg implements EELFResolvableErrorEnum { - - /** - * ECOMP Application Controller (APP-C) initialization started at {0} - */ - CONFIGURATION_STARTED, - - /** - * Prior configuration has been cleared - */ - CONFIGURATION_CLEARED, - - /** - * Loading configuration properties from file "{0}" - */ - LOADING_CONFIGURATION_OVERRIDES, - - /** - * Configuration defaults loaded from resource file "{0}" - */ - LOADING_DEFAULTS, - - /** - * No default property resource "{0}" was found! - */ - NO_DEFAULTS_FOUND, - - /** - * Property "{0}" ="{1}" - */ - PROPERTY_VALUE, - - /** - * No configuration file named [{0}] was found on the configuration search path [{1}]. \ If a configuration file - * should have been loaded, check the file name and search path specified. CDP will proceed using the \ default - * values and command-line overrides (if any). - */ - NO_OVERRIDE_PROPERTY_FILE_LOADED, - - /** - * Searching path "{0}" for configuration settings "{1}" - */ - SEARCHING_CONFIGURATION_OVERRIDES, - - /** - * Loading application-specific override properties - */ - LOADING_APPLICATION_OVERRIDES, - - /** - * No application-specific override properties were provided! - */ - NO_APPLICATION_OVERRIDES, - - /** - * Merging system properties into configuration - */ - MERGING_SYSTEM_PROPERTIES, - - /** - * Setting property "{0}={1}" in system properties - */ - SETTING_SPECIAL_PROPERTY, - - /** - * Loading resource bundle "{0}" - */ - LOADING_RESOURCE_BUNDLE, - - /** - * Logging has already been initialized, check the container logging definitions to ensure they represent your - * desired logging configuration. - */ - LOGGING_ALREADY_INITIALIZED, - - /** - * Searching path "{0}" for log configuration file "{1}" - */ - SEARCHING_LOG_CONFIGURATION, - - /** - * Loading default logging configuration from system resource file "{0}" - */ - LOADING_DEFAULT_LOG_CONFIGURATION, - - /** - * No log configuration could be found or defaulted! - */ - NO_LOG_CONFIGURATION, - - /** - * An unsupported logging framework is bound to SLF4J. Only Logback or Log4J are supported. - */ - UNSUPPORTED_LOGGING_FRAMEWORK, - - /** - * Loading logging configuration from file "{0}" - */ - LOADING_LOG_CONFIGURATION, - - /** - * Provider {0} cannot be found or cannot be resolved to a valid provider. - */ - UNKNOWN_PROVIDER, - - /** - * Server name "{0}" with id "{1}" in tenant "{2}" and region "{3}" did not change state within the alloted time. - * Current state is "{4}" and the desired state(s) are "{5}" - */ - SERVER_STATE_CHANGE_TIMEOUT, - - /** - * Server name "{0}" with id "{1}" in tenant "{2}" has a state of deleted and cannot be {3}. - */ - SERVER_DELETED, - - /** - * Server name "{0}" with id "{1}" in tenant "{2}" has an unknown state of "{3}". - */ - UNKNOWN_SERVER_STATE, - - /** - * {0} component {1} is being initialized... - */ - COMPONENT_INITIALIZING, - - /** - * {0} component {1} has completed initialization - */ - COMPONENT_INITIALIZED, - - /** - * {0} component {1} is terminating... - */ - COMPONENT_TERMINATING, - - /** - * {0} component {1} has terminated - */ - COMPONENT_TERMINATED, - - /** - * Operation {0} is not supported or implemented at this time. - */ - IAAS_ADAPTER_UNSUPPORTED_OPERATION, - - /** - * Operation {0} called. Input document:\n{1} - */ - IAAS_ADAPTER_RPC_CALLED, - - /** - * Unable to locate the {0} service in the OSGi container - */ - NO_SERVICE_FOUND, - - /** - * Dump of context parameters for module {0}, RPC {1}, and version {2} - */ - CONTEXT_PARAMETERS_DISPLAY, - - /** - * Response properties from execution of module '{0}', RPC '{1}', and version '{2}' are: - */ - RESPONSE_PARAMETERS_DISPLAY, - - /** - * Service {0}:{1} was provided a null (empty) or invalid argument, '{2}' = '{3}' - */ - NULL_OR_INVALID_ARGUMENT, - - /** - * Service {0}:{1} is processing service '{2}' with request id '{3}' - */ - PROCESSING_REQUEST, - - /** - * Service {0}:{1} received request for service '{2}' but that service is invalid or unknown. - */ - INVALID_SERVICE_REQUEST, - - /** - * {0} registering service {1} using class {2} - */ - REGISTERING_SERVICE, - - /** - * {0} unregistering service {1} - */ - UNREGISTERING_SERVICE, - - /** - * {0} IAAS Adapter initializing provider {1} as {2} - */ - LOADING_PROVIDER_DEFINITIONS, - - /** - * {0} IAAS Adapter restart of server requested - */ - RESTARTING_SERVER, - - /** - * {0} IAAS Adapter rebuild of server requested - */ - REBUILDING_SERVER, - - /** - * {0} IAAS Adapter migrate of server requested - */ - MIGRATING_SERVER, - - /** - * {0} IAAS Adapter evacuate of server requested - */ - EVACUATING_SERVER, - - /** - * {0} IAAS Adapter create snapshot of server requested - */ - SNAPSHOTING_SERVER, - - /** - * {0} IAAS Adapter look for server requested - */ - LOOKING_SERVER_UP, - - /** - * {0} IAAS Adapter cannot perform requested service, VM url '{1}' is invalid - */ - INVALID_SELF_LINK_URL, - - /** - * Located server '{0}' on tenant '{1}' and in state '{2}' - */ - SERVER_FOUND, - - /** - * No server found in provider with self-link URL [{0}] - */ - SERVER_NOT_FOUND, - - /** - * Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}] - */ - SERVER_OPERATION_EXCEPTION, - - /** - * One or more properties for [{0}] are missing, null, or empty. They are: - */ - MISSING_REQUIRED_PROPERTIES, - - /** - * The server [{0}] (id={1}) in tenant {2} is in error state, {3} is not allowed - */ - SERVER_ERROR_STATE, - - /** - * The image {0} could not be located for {1} - */ - IMAGE_NOT_FOUND, - - /** - * Time out waiting for {0} with name {1} (and id {2}) to reach one of {3} states, current state is {4} - */ - STATE_CHANGE_TIMEOUT, - - /** - * Exception {0} waiting for {1} with name {2} (and id {3}) to reach one of {4} states, current state is {5} - * cause={6} - */ - STATE_CHANGE_EXCEPTION, - - /** - * Server {0} is being stopped... - */ - STOP_SERVER, - - /** - * Server {0} is being started... - */ - START_SERVER, - - /** - * Server {0} is being resumed... - */ - RESUME_SERVER, - - /** - * Server {0} is being unpaused... - */ - UNPAUSE_SERVER, - - /** - * Server {0} is being rebuilt... - */ - REBUILD_SERVER, - - /** - * Connection to provider {0} at identity {1} using tenant name {2} (id {3}) failed, reason={4}, retrying in {5} - * seconds, attempt {6} of {7}. - */ - CONNECTION_FAILED_RETRY, - - /** - * Connection to provider {0} at service {1} failed after all retry attempts. - */ - CONNECTION_FAILED, - - /** - * {0} IAAS Adapter stop server requested - */ - STOPPING_SERVER, - - /** - * {0} IAAS Adapter start server requested - */ - STARTING_SERVER, - - /** - * Server {0} (id {1}) failed to rebuild, reason {2} - */ - REBUILD_SERVER_FAILED, - - /** - * Application {0} graph {1} response did not set the {2} parameter. This parameter is required for synchronization - * with the controller. Absence of this parameter is assumed to be a failure. Please correct the DG. - */ - PARAMETER_IS_MISSING, - - /** - * Application {0} graph {1} did not set parameter {2} to a valid numeric value ({3}). Please correct the DG. - */ - PARAMETER_NOT_NUMERIC, - - /** - * Application {0} graph {1} completed with failure: error code = {2}, message = {3} - */ - DG_FAILED_RESPONSE, - - /** - * Application {0} received exception {1} attempting to call graph {2}, exception message = {3} - */ - EXCEPTION_CALLING_DG, - - /** - * Application {0} was unable to locate graph {1} - */ - GRAPH_NOT_FOUND, - - /** - * Application {0} graph {1} responded with {3} properties - */ - DEBUG_GRAPH_RESPONSE_HEADER, - - /** - * {0}:{1} - {2} = {3} - */ - DEBUG_GRAPH_RESPONSE_DETAIL, - - /** - * Application {0} request {1} was supplied a property '{2}' with the value '{3}' that does not meet the required - * form(s): - */ - INVALID_REQUIRED_PROPERTY, - - /** - * Server {0} (id {1}) failed to migrate during {2} phase, reason {3} - */ - MIGRATE_SERVER_FAILED, - - /** - * Server {0} (id {1}) failed to evacuate, reason {2} - */ - EVACUATE_SERVER_FAILED, - - /** - * Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3} - */ - EVACUATE_SERVER_REBUILD_FAILED, - - /** - * APP-C instance is too busy - */ - APPC_TOO_BUSY, - - /** - * Concurrent access to server "{0}" - */ - VF_SERVER_BUSY, - - /** - * Server "{0}" does not support command "{1}" in the current state "{2}" - */ - VF_ILLEGAL_COMMAND, - - /** - * Server "{0}" cannot handle command "{1}" because of its doubtful state - */ - VF_UNDEFINED_STATE, - - /** - * No resource found with ID "{0}" in A&AI system - */ - APPC_NO_RESOURCE_FOUND, - - /** - * The request "{0}" for server "{1}" has exceeded its TTL limit of "{3}" seconds - */ - APPC_EXPIRED_REQUEST, - - /** - * Workflow for vnfType = "{0}" and command = "{1}" not found. - */ - APPC_WORKFLOW_NOT_FOUND, - - /** - * Null vnfId and command provided - */ - APPC_INVALID_INPUT, - - /** - * Operation '{0}' for VNF type '{1}' from Source '{2}' with RequestID '{3}' was started at '{4}' and ended at '{5}' - * with status code '{6}' - */ - APPC_AUDIT_MSG, - - /** - * APP-C is unable to communicate with A&AI - */ - AAI_CONNECTION_FAILED, - - /** - * APP-C is unable to update COMPONENT_ID {0} to {1} for reason {2} - */ - AAI_UPDATE_FAILED, - - /** - * APP-C is unable to retrieve VF/VFC {0} data for Transaction ID{1}as a result of A&AI communication failure or its - * internal error. - */ - AAI_GET_DATA_FAILED, - - /** - * A&AI at identity {0} using VNF_ID {1} failed, reason={2}, retrying in {3} seconds, attempt {4} of {5} - */ - AAI_CONNECTION_FAILED_RETRY, - - /** - * APP-C is unable to delete COMPONENT_ID {0} for reason {1} - */ - AAI_DELETE_FAILED, - - /** - * APP-C is unable to query AAI for VNF_ID {0} - */ - AAI_QUERY_FAILED, - - /** - * VNF {0} is configured - */ - VNF_CONFIGURED, - - /** - * VNF {0} is being configured - */ - VNF_CONFIGURATION_STARTED, - - /** - * VNF {0} configuration failed for reason {1} - */ - VNF_CONFIGURATION_FAILED, - - /** - * VNF {0} is being tested - */ - VNF_TEST_STARTED, - - /** - * VNF {0} was tested - */ - VNF_TESTED, - - /** - * VNF {0} test failed for reason {1} - */ - VNF_TEST_FAILED, - - /** - * VNF {0} test failed for reason {1} - */ - VNF_NOT_FOUND, - - /** - * VNF {0} Healthcheck operation failed for reason {1} - */ - VNF_HEALTHCECK_FAILED, - - /** - * VM {0} Healthcheck operation failed for reason {1} - */ - VM_HEALTHCECK_FAILED, - - /** - * Server {0} (id {1}) failed to stop during {2} phase, reason {3} - */ - STOP_SERVER_FAILED, - - /** - * Server {0} (id {1}) failed to terminate during {2} phase, reason {3} - */ - TERMINATE_SERVER_FAILED, - - /** - * {0} IAAS Adapter terminate server requested - */ - TERMINATING_SERVER, - - /** - * Server {0} is being terminated... - */ - TERMINATE_SERVER, - - /** - * Migrate {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... - */ - MIGRATE_COMPLETE, - - /** - * Restart {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... - */ - RESTART_COMPLETE, - - /** - * Rebuild {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}... - */ - REBUILD_COMPLETE, - - /** - * Located stack '{0}' on tenant '{1}' and in state '{2}' - */ - STACK_FOUND, - - /** - * {0} IAAS Adapter terminate stack requested - */ - - TERMINATING_STACK, - - /** - * stack {0} is being terminated... - */ - TERMINATE_STACK, - /** - * No stack found in provider with self-link URL [{0}] - */ - - STACK_NOT_FOUND, - - /** - * Exception {0} was caught attempting {1} of stack [{2}] on tenant [{3}] - */ - STACK_OPERATION_EXCEPTION, - - /** - * Stack {0} (id {1}) failed to terminate during {2} phase, reason {3} - */ - - TERMINATE_STACK_FAILED, - - /** - * Exception {0} was caught attempting to close provider context for {1}. - */ - - CLOSE_CONTEXT_FAILED, - - /** - * {0} IAAS Adapter snapshoting stack - */ - SNAPSHOTING_STACK, - - /** - * Stack {0} snapshoted, snapshot ID = [{1}]. - */ - STACK_SNAPSHOTED, - - /** - * {0} IAAS Adapter restoring stack - */ - RESTORING_STACK, - - /** - * Stack {0} is restored to snapshot {1}. - */ - STACK_RESTORED, - - /** - * {0} IAAS Adapter checking server - */ - CHECKING_SERVER, - - /** - * Parameter {0} is missing in svc request of {1}. - */ - MISSING_PARAMETER_IN_REQUEST, - - /** - * Cannot establish connection to server {0} port {1} with user {2}. - */ - CANNOT_ESTABLISH_CONNECTION, - - /** - * Operation '{0}' for VNF type '{1}' from Source '{2}' with RequestID '{3}' on '{4}' with action '{5}' - * ended in {6}ms with result '{7}' - */ - APPC_METRIC_MSG, - - /** - * Parsing failied for{0} - */ - INPUT_PAYLOAD_PARSING_FAILED, - - /** - * Error occurred for due to {0} - */ - APPC_EXCEPTION, - - /** - * SSH Data Exception occurred due to {0} - */ - SSH_DATA_EXCEPTION, - - /** - * Json processing exception occurred due to {0} - */ - JSON_PROCESSING_EXCEPTION, - - /** - * Operation {0} succeed for {1} - */ - SUCCESS_EVENT_MESSAGE, - - /** - * Dependency model not found for VNF type {0} due to {1} - */ - DEPENDENCY_MODEL_NOT_FOUND, - - /** - * Invalid Dependency model for VNF Type {0} due to {1} - */ - INVALID_DEPENDENCY_MODEL, - - /** - * Failed to retrieve VNFC DG - */ - FAILURE_RETRIEVE_VNFC_DG, - - /** - * Network check for Server {0} failed for Port {1} - * - */ - SERVER_NETWORK_ERROR, - - /** - * Hypervisor check for Server {0} failed. Status is DOWN or UNKNOWN - * - */ - HYPERVISOR_DOWN_ERROR, - - /** - * Unable to determine Hypervisor status for Server {0}. failed. - * - */ - HYPERVISOR_STATUS_UKNOWN, - - /** - * Hypervisor Network check for Server {0} failed. Not reachable by APPC - * - */ - HYPERVISOR_NETWORK_ERROR, - - /** - * Restart application operation failed on server : {0}, reason {1} - */ - APPLICATION_RESTART_FAILED, - - /** - * Start application operation failed on server : {0}, reason {1} - */ - APPLICATION_START_FAILED, - - /** - * Start application operation failed on server : {0}, reason {1} - */ - APPLICATION_STOP_FAILED, - - /** - * Application on server {0} is being restarted... - */ - RESTART_APPLICATION, - - /** - * Application on server {0} is being started... - */ - START_APPLICATION, - - /** - * Application on server {0} is being started... - */ - STOP_APPLICATION, - - /** - * APPC LCM operations are disabled - */ - LCM_OPERATIONS_DISABLED, - - /** - * Application {0} received exception {1} while attempting to execute oam operation {2}, exception message = {3}|\ - */ - OAM_OPERATION_EXCEPTION, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_ENTERING_MAINTENANCE_MODE, - - /** - * Application {0} is in {1} - */ - OAM_OPERATION_MAINTENANCE_MODE, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_STARTING, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_STARTED, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_STOPPING, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_STOPPED, - /** - * A {1} API is not allowed when {0} is in the {2} state - */ - INVALID_STATE_TRANSITION, - - /** - * Application {0} was unable to find the Request Handler service - */ - REQUEST_HANDLER_UNAVAILABLE, - - /** - * Application {0} is {1} - */ - OAM_OPERATION_RESTARTING, - - /** - * Application {0} is {1} for restart - */ - OAM_OPERATION_RESTARTED, - - /** - * {0} - */ - OAM_OPERATION_INVALID_INPUT, - - /** - * Unsupported identity service version, unable to retrieve ServiceCatalog - * for identity service {0} - */ - IAAS_UNSUPPORTED_IDENTITY_SERVICE - ; - /* - * Static initializer to ensure the resource bundles for this class are loaded... - */ - static { - EELFResourceManager.loadMessageBundle("org/onap/appc/i18n/MessageResources"); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/logging/LoggingConstants.java b/appc-common/src/main/java/org/openecomp/appc/logging/LoggingConstants.java deleted file mode 100644 index 30ff91d68..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/logging/LoggingConstants.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.logging; - -/** - * Constant definition of logging - */ -public class LoggingConstants { - private LoggingConstants() { - throw new IllegalAccessError("LoggingConstants"); - } - - /** - * Constants of MDC property keys - */ - public static class MDCKeys { - private MDCKeys() { - throw new IllegalAccessError("MDCKeys"); - } - - public static final String ERROR_CODE = "ErrorCode"; - public static final String ERROR_DESCRIPTION = "ErrorDescription"; - public static final String STATUS_CODE = "StatusCode"; - public static final String RESPONSE_CODE = "ResponseCode"; - public static final String RESPONSE_DESCRIPTION = "ResponseDescription"; - public static final String TARGET_ENTITY = "TargetEntity"; - public static final String TARGET_SERVICE_NAME = "TargetServiceName"; - public static final String PARTNER_NAME = "PartnerName"; - public static final String SERVER_NAME = "ServerName"; - public static final String BEGIN_TIMESTAMP = "BeginTimestamp"; - public static final String END_TIMESTAMP = "EndTimestamp"; - public static final String ELAPSED_TIME = "ElapsedTime"; - public static final String CLASS_NAME = "ClassName"; - public static final String TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; - } - - /** - * Constants of status code values - */ - public static class StatusCodes { - private StatusCodes() { - throw new IllegalAccessError("StatusCodes"); - } - public static final String COMPLETE = "COMPLETE"; - public static final String ERROR = "ERROR"; - } - - /** - * Constants of APPC target names - */ - public static class TargetNames { - private TargetNames() { - throw new IllegalAccessError("TargetNames"); - } - public static final String APPC = "APPC"; - public static final String AAI = "A&AI"; - public static final String DB = "DataBase"; - public static final String APPC_PROVIDER = "APPC Provider"; - public static final String APPC_OAM_PROVIDER = "APPC OAM Provider"; - public static final String STATE_MACHINE = "StateMachine"; - public static final String WORKFLOW_MANAGER = "WorkflowManager"; - public static final String REQUEST_VALIDATOR = "RequestValidator"; - public static final String LOCK_MANAGER = "LockManager"; - public static final String REQUEST_HANDLER = "RequestHandler"; - } - - /** - * Constants of targeted service names - */ - public static class TargetServiceNames { - private TargetServiceNames() { - throw new IllegalAccessError("TargetServiceNames"); - } - - /** - * Constants of AAI service names - */ - public static class AAIServiceNames { - private AAIServiceNames() { - throw new IllegalAccessError("AAIServiceNames"); - } - public static final String QUERY = "query"; - public static final String GET_VNF_DATA = "getVnfData"; - } - - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/logging/LoggingUtils.java b/appc-common/src/main/java/org/openecomp/appc/logging/LoggingUtils.java deleted file mode 100644 index 1e4156e02..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/logging/LoggingUtils.java +++ /dev/null @@ -1,235 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.logging; - -import org.onap.appc.i18n.Msg; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResolvableErrorEnum; -import com.att.eelf.i18n.EELFResourceManager; -import org.slf4j.MDC; - -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.TimeZone; - -/** - * Logging utilities - */ -public class LoggingUtils { - - private final static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - private final static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - private final static EELFLogger metricLogger = EELFManager.getInstance().getMetricsLogger(); - - private LoggingUtils() { - throw new IllegalAccessError("LoggingUtils"); - } - - public static void logErrorMessage(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String additionalMessage, String className) { - logError(errorCode, errorDescription, targetEntity, targetServiceName, additionalMessage, className); - } - - public static void logErrorMessage(String targetEntity, String targetServiceName, String additionalMessage, - String className) { - logError("", "", targetEntity, targetServiceName, additionalMessage, className); - } - - public static void logErrorMessage(String targetServiceName, String additionalMessage, String className) { - logError("", "", LoggingConstants.TargetNames.APPC, targetServiceName, - additionalMessage, className); - } - - private static void logError(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String additionalMessage, String className) { - populateErrorLogContext(errorCode, errorDescription, targetEntity, targetServiceName, className); - errorLogger.error(additionalMessage == null ? "" : additionalMessage); - cleanErrorLogContext(); - } - - public static void logAuditMessage(Instant beginTimeStamp, Instant endTimeStamp, String code, - String responseDescription, String className) { - populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.info(EELFResourceManager.format(Msg.APPC_AUDIT_MSG, - MDC.get(MDC_SERVICE_NAME), - MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), - MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), - MDC.get(MDC_KEY_REQUEST_ID), - MDC.get(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP), - MDC.get(LoggingConstants.MDCKeys.END_TIMESTAMP), - MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE))); - cleanAuditErrorContext(); - } - - public static void auditInfo(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, - String className,EELFResolvableErrorEnum resourceId, String... arguments) { - populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.info(resourceId,arguments); - cleanAuditErrorContext(); - } - - public static void auditWarn(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, - String className,EELFResolvableErrorEnum resourceId, String... arguments) { - populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.warn(resourceId,arguments); - cleanAuditErrorContext(); - } - - - - public static void logMetricsMessage(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, - String targetServiceName, String statusCode, String responseCode, - String responseDescription, String className) { - populateMetricLogContext(beginTimeStamp, endTimeStamp, targetEntity, targetServiceName, statusCode, - responseCode, responseDescription, className); - metricLogger.info(EELFResourceManager.format(Msg.APPC_METRIC_MSG, - MDC.get(MDC_SERVICE_NAME), - MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), - MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), - MDC.get(MDC_KEY_REQUEST_ID), - MDC.get(LoggingConstants.MDCKeys.TARGET_ENTITY), - MDC.get(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME), - MDC.get(LoggingConstants.MDCKeys.ELAPSED_TIME), - MDC.get(LoggingConstants.MDCKeys.STATUS_CODE))); - cleanMetricContext(); - } - - private static void populateAuditLogContext(Instant beginTimeStamp, Instant endTimeStamp, String code, - String responseDescription, String className) { - populateTimeContext(beginTimeStamp, endTimeStamp); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, code); - MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "100".equals(code) || "400".equals(code) ? - LoggingConstants.StatusCodes.COMPLETE : - LoggingConstants.StatusCodes.ERROR); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); - } - - private static void cleanAuditErrorContext() { - cleanTimeContext(); - MDC.remove(LoggingConstants.MDCKeys.STATUS_CODE); - MDC.remove(LoggingConstants.MDCKeys.RESPONSE_CODE); - MDC.remove(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION); - MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); - } - - private static void populateErrorLogContext(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String className) { - populateErrorContext(errorCode, errorDescription); - populateTargetContext(targetEntity, targetServiceName!=null?targetServiceName:""); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); - } - - private static void cleanErrorLogContext() { - cleanErrorContext(); - cleanTargetContext(); - MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); - } - - private static void populateMetricLogContext(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, - String targetServiceName, String statusCode, String responseCode, - String responseDescription, String className) { - populateTimeContext(beginTimeStamp, endTimeStamp); - populateTargetContext(targetEntity, targetServiceName); - populateResponseContext(statusCode, responseCode, responseDescription); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); - } - - private static void cleanMetricContext() { - cleanTimeContext(); - cleanTargetContext(); - cleanResponseContext(); - MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); - } - - private static void populateTargetContext(String targetEntity, String targetServiceName) { - MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, targetEntity!=null?targetEntity:""); - MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, targetServiceName!=null?targetServiceName:""); - } - - private static void cleanTargetContext() { - MDC.remove(LoggingConstants.MDCKeys.TARGET_ENTITY); - MDC.remove(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME); - } - - private static void populateTimeContext(Instant beginTimeStamp, Instant endTimeStamp) { - String beginTime = ""; - String endTime = ""; - String elapsedTime = ""; - - if (beginTimeStamp != null && endTimeStamp != null) { - elapsedTime = String.valueOf(ChronoUnit.MILLIS.between(beginTimeStamp, endTimeStamp)); - beginTime = generateTimestampStr(beginTimeStamp); - endTime = generateTimestampStr(endTimeStamp); - } - - MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, beginTime); - MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, endTime); - MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, elapsedTime); - } - - private static String generateTimestampStr(Instant timeStamp) { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - TimeZone tz = TimeZone.getTimeZone("UTC"); - df.setTimeZone(tz); - return df.format(Date.from(timeStamp)); - } - - private static void cleanTimeContext() { - MDC.remove(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP); - MDC.remove(LoggingConstants.MDCKeys.END_TIMESTAMP); - MDC.remove(LoggingConstants.MDCKeys.ELAPSED_TIME); - } - - private static void populateResponseContext(String statusCode, String responseCode, String responseDescription) { - MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, statusCode!=null?statusCode:""); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, responseCode); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); - } - - private static void cleanResponseContext() { - MDC.remove(LoggingConstants.MDCKeys.STATUS_CODE); - MDC.remove(LoggingConstants.MDCKeys.RESPONSE_CODE); - MDC.remove(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION); - } - - private static void populateErrorContext(String errorCode, String errorDescription) { - MDC.put(LoggingConstants.MDCKeys.ERROR_CODE, errorCode); - MDC.put(LoggingConstants.MDCKeys.ERROR_DESCRIPTION, errorDescription); - } - - private static void cleanErrorContext() { - MDC.remove(LoggingConstants.MDCKeys.ERROR_CODE); - MDC.remove(LoggingConstants.MDCKeys.ERROR_DESCRIPTION); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/metadata/MetadataService.java b/appc-common/src/main/java/org/openecomp/appc/metadata/MetadataService.java deleted file mode 100644 index 29586ea15..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/metadata/MetadataService.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metadata; - -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - - -public interface MetadataService { - String getVnfModel(DependencyModelIdentifier modelIdentifier); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/metadata/impl/MetadataServiceImpl.java b/appc-common/src/main/java/org/openecomp/appc/metadata/impl/MetadataServiceImpl.java deleted file mode 100644 index 0321b7e81..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/metadata/impl/MetadataServiceImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metadata.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -import javax.sql.rowset.CachedRowSet; - -import org.onap.appc.cache.MetadataCache; -import org.onap.appc.cache.impl.MetadataCacheFactory; -import org.onap.appc.metadata.MetadataService; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -import java.sql.SQLException; -import java.util.ArrayList; - - -public class MetadataServiceImpl implements MetadataService { - - private DbLibService dbLibService; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MetadataServiceImpl.class); - - private MetadataCache cache; - - public MetadataServiceImpl(){ - initialize(); - } - - private void initialize(){ - cache = MetadataCacheFactory.getInstance().getMetadataCache(); - // TODO initialze dbLibService - } - - public void setDbLibService(DbLibService dbLibService) { - this.dbLibService = dbLibService; - } - - @Override - public String getVnfModel(DependencyModelIdentifier modelIdentifier) { - logger.debug("Reading Vnf Model data from cache for vnfType : "+ modelIdentifier.getVnfType() +" and catalog version : " +modelIdentifier.getCatalogVersion()); - String vnfModel = cache.getObject(modelIdentifier); - if(vnfModel ==null || vnfModel.length() ==0){ - logger.debug("Vnf Model not available in cache. Reading from database."); - vnfModel = readVnfModel(modelIdentifier); - if(vnfModel !=null && vnfModel.length()>0){ - logger.debug("Adding retrieved Vnf Model to cache."); - addVnfModel(modelIdentifier,vnfModel); - } - } - return vnfModel; - } - - private void addVnfModel(DependencyModelIdentifier modelIdentifier, String vnfModel) { - cache.putObject(modelIdentifier,vnfModel); - } - - private String readVnfModel(DependencyModelIdentifier modelIdentifier) { - - logger.debug("Reading Vnf Model data from database for RESOURCE_NAME : "+ modelIdentifier.getVnfType() +" and RESOURCE_VERSION : " +modelIdentifier.getCatalogVersion()); - StringBuilder query = new StringBuilder(); - String vnfModel =null; - query.append("SELECT ARTIFACT_CONTENT FROM sdnctl.ASDC_ARTIFACTS WHERE RESOURCE_NAME = ? ") ; - ArrayList argList = new ArrayList<>(); - argList.add(modelIdentifier.getVnfType()); - - if (modelIdentifier.getCatalogVersion()==null){ - query.append(" ORDER BY SUBSTRING_INDEX(RESOURCE_VERSION, '.', 1)*1 DESC , " + - "SUBSTRING_INDEX(SUBSTRING_INDEX(RESOURCE_VERSION, '.', 2),'.', -1) *1 DESC , " + - "SUBSTRING_INDEX(RESOURCE_VERSION, '.', -1)*1 DESC ;"); - }else{ - query.append("AND RESOURCE_VERSION = ? ;"); - argList.add(modelIdentifier.getCatalogVersion()); - } - try { - final CachedRowSet data = dbLibService.getData(query.toString(), argList, "sdnctl"); - if (data.first()) { - vnfModel = data.getString("ARTIFACT_CONTENT"); - if (vnfModel == null || vnfModel.isEmpty()) { - logger.error("Invalid dependency model for vnf type : "+ modelIdentifier.getVnfType() +" and catalog version : " +modelIdentifier.getCatalogVersion()); - throw new RuntimeException("Invalid or Empty VNF Model"); - } - logger.debug("Retrieved Vnf Model : " + vnfModel); - }else { - logger.warn("VNF Model not found in datastore for RESOURCE_NAME : "+ modelIdentifier.getVnfType() +" AND RESOURCE_VERSION : " +modelIdentifier.getCatalogVersion()); - } - } catch (SQLException e) { - throw new RuntimeException("Database error occurred"); - } - return vnfModel; - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifier.java b/appc-common/src/main/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifier.java deleted file mode 100644 index ddd035644..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifier.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metadata.objects; - -/** - * Object of identifier for dependency model. - * Currently uses VNF type and catalog version - */ -public class DependencyModelIdentifier { - static final String TO_STRING_FORMAT = "DependencyModelIdentifier : vnfType = %s , catalogVersion = %s"; - static final int prime = 31; - - private String vnfType; - private String catalogVersion; - - /** - * Constructor - * @param vnfType String of the VNF type - * @param catalogVersion String of the catalog version - */ - public DependencyModelIdentifier(String vnfType, String catalogVersion) { - this.vnfType = vnfType; - this.catalogVersion = catalogVersion; - } - - @Override - public int hashCode() { - int result = 1; - result = result * prime + (this.vnfType == null ? 0 :this.vnfType.hashCode()); - result = result * prime + (this.catalogVersion == null ? 0 :this.catalogVersion.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj ==null) { - return false; - } - if (!(obj instanceof DependencyModelIdentifier)) { - return false; - } - - DependencyModelIdentifier modelIdentifier = (DependencyModelIdentifier)obj; - if (this.vnfType == null) { - if (modelIdentifier.vnfType !=null) { - return false; - } - } else if (!this.vnfType.equals(modelIdentifier.vnfType)) { - return false; - } - - if (this.catalogVersion == null) { - if (modelIdentifier.catalogVersion !=null) { - return false; - } - } else if (!this.catalogVersion.equals(modelIdentifier.catalogVersion)) { - return false; - } - - return true; - } - - @Override - public String toString() { - return String.format(TO_STRING_FORMAT, vnfType, catalogVersion); - } - - public String getVnfType() { - return vnfType; - } - - public String getCatalogVersion() { - return catalogVersion; - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/Allocator.java b/appc-common/src/main/java/org/openecomp/appc/pool/Allocator.java deleted file mode 100644 index 4b9f15a90..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/Allocator.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import java.io.Closeable; - -/** - * This interface is used to supply an object that will be called by the pool manager whenever a new widget must be - * allocated. - * @param - * The generic type that we are caching. - */ - -public interface Allocator { - - /** - * Allocate an object of type and return it to the pool - * - * @param pool - * The pool that the object is to be allocated to - * @return An object of type T - */ - T allocate(Pool pool); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/CacheManagement.java b/appc-common/src/main/java/org/openecomp/appc/pool/CacheManagement.java deleted file mode 100644 index 9eb45776f..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/CacheManagement.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.pool; - -public interface CacheManagement { - - /** - * @return The object that is actually being wrapped and cached - */ - Object getWrappedObject(); - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java b/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java deleted file mode 100644 index d7d243d4f..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/CachedElement.java +++ /dev/null @@ -1,215 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import java.io.Closeable; -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is implemented as a - * dynamic proxy, so that it appears to be the same class of object to the client as the interface being cached. The - * generic type being cached MUST be an interface. - * @param - * The generic type that we create a cached element for. This type is used to wrap instances of this type and - * expose access to the {@link java.io.Closeable} interface by using a dynamic proxy. - */ - -public class CachedElement implements Closeable, InvocationHandler, CacheManagement { - - /** - * The pool that is managing this cached element - */ - private Pool pool; - - /** - * The element that we are caching in the pool - */ - private T element; - - /** - * A thread-safe atomic indicator that tells us that the wrapped element has been released to the pool already, and - * not to do it again. - */ - private AtomicBoolean released = new AtomicBoolean(false); - - /** - * Create a new instance of a cached element dynamic proxy for use in the pool. - *

- * This returns an instance of the proxy to the caller that appears to be the same interface(s) as the object being - * cached. The dynamic proxy then intercepts all open and close semantics and directs that element to the pool. - *

- *

- * If the object being proxied does not implement the {@link CacheManagement} interface, then that interface is - * added to the dynamic proxy being created. This interface is actually implemented by the invocation handler (this - * object) for the proxy and allows direct access to the wrapped object inside the proxy. - *

- * - * @param pool - * The pool that we are caching these elements within - * @param element - * The element actually being cached - * @param interfaces - * The interface list of interfaces the element must implement (usually one) - * @return The dynamic proxy - */ - @SuppressWarnings("unchecked") - public static T newInstance(Pool pool, T element, Class[] interfaces) { - ClassLoader cl = element.getClass().getClassLoader(); - CachedElement ce = new CachedElement<>(pool, element); - boolean found = false; - for (Class intf : interfaces) { - if (intf.getName().equals(CacheManagement.class.getName())) { - found = true; - break; - } - } - - int length = found ? interfaces.length : interfaces.length + 1; - Class[] proxyInterfaces = new Class[length]; - System.arraycopy(interfaces, 0, proxyInterfaces, 0, interfaces.length); - - if (!found) { - proxyInterfaces[interfaces.length] = CacheManagement.class; - } - - return (T) Proxy.newProxyInstance(cl, proxyInterfaces, ce); - } - - /** - * Construct a cached element and assign it to the pool as a free element - * - * @param pool - * The pool that the element will be managed within - * @param element - * The element we are caching - */ - @SuppressWarnings("unchecked") - public CachedElement(Pool pool, T element) { - this.pool = pool; - this.element = element; - - try { - pool.release((T) this); - } catch (PoolDrainedException e) { - e.printStackTrace(); - } - } - - /** - * This method delegates the close call to the actual wrapped element. - *

- * NOTE: This is not the same method that is called by the dynamic proxy. This method is in place to satisfy the - * signature of the {@link java.io.Closeable} interface. If it were to be called directly, then we will delegate the - * close to the underlying context. However, when the cached element is called as a synamic proxy, entry is in the - * {@link #invoke(Object, Method, Object[])} method. - *

- * - * @see java.io.Closeable#close() - */ - @Override - public void close() throws IOException { - element.close(); - } - - /** - * This method is the magic part of dynamic proxies. When the caller makes a method call based on the interface - * being proxied, this method is given control. This informs us of the method and arguments of the call. The object - * reference is that of the dynamic proxy itself, which is us. - *

- * Here we will check to see if the user is trying to close the "element" (the dynamic proxy acts like the wrapped - * element). If he is, then we don't really close it, but instead release the element that we are wrapping back to - * the free pool. Once this has happened, we mark the element as "closed" (from the perspective of this dynamic - * proxy) so that we wont try to release it again. - *

- *

- * If the method is the equals method then we assume that we are comparing the cached element in one - * dynamic proxy to the cached element in another. We execute the comparison between the cached elements, and not - * the dynamic proxies themselves. This preserves the allusion to the caller that the dynamic proxy is the object - * being wrapped. - *

- *

- * For convenience, we also implement the getWrappedObject method so that the dynamic proxy can be - * called to obtain the actual wrapped object if desired. Note, to use this method, the caller would have to invoke - * it through reflection. - *

- *

- * If the method being invoked is not one that we intercept, then we simply delegate that method onto the wrapped - * object. - *

- * - * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) - */ - @SuppressWarnings({ - "unchecked", "nls" - }) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Exception { - Object result = null; - - switch (method.getName()) { - case "close": - if (released.compareAndSet(false, true)) { - if (!pool.isDrained()) { - pool.release((T) proxy); - } - } - break; - case "equals": - CacheManagement cm = (CacheManagement) proxy; - T other = (T) cm.getWrappedObject(); - result = element.equals(other); - break; - case "getWrappedObject": - return element; - default: - result = method.invoke(element, args); - break; - } - - return result; - } - - /** - * This method is used to be able to access the wrapped object underneath the dynamic proxy - * - * @see org.onap.appc.pool.CacheManagement#getWrappedObject() - */ - @Override - public T getWrappedObject() { - return element; - } - - @SuppressWarnings("nls") - @Override - public String toString() { - return element == null ? "null" : element.toString(); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/Destructor.java b/appc-common/src/main/java/org/openecomp/appc/pool/Destructor.java deleted file mode 100644 index 46bcd2cd0..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/Destructor.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import java.io.Closeable; - -/** - * @param - * The generic type we are caching - */ - -public interface Destructor { - - /** - * Called to destroy the object when it is no longer being used by the pool - * - * @param obj - * The object to be destroyed - * @param pool - * The pool that the object is being removed from - */ - void destroy(T obj, Pool pool); -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/Pool.java b/appc-common/src/main/java/org/openecomp/appc/pool/Pool.java deleted file mode 100644 index 6d850ae42..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/Pool.java +++ /dev/null @@ -1,372 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import java.io.Closeable; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.List; -import java.util.ListIterator; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * This class is used to manage a pool of things. - *

- * The class is parameterized so that the type of objects maintained in the pool is definable by some provided type. - * This type must implement the Comparable interface so that it can be managed in the pool. - *

- * - * @param - * The type of element being pooled - */ - -public class Pool { - private Deque free; - private List allocated; - private int minPool; - private int maxPool; - private Allocator allocator; - private Destructor destructor; - private ReadWriteLock lock; - private AtomicBoolean drained; - private Properties properties; - - /** - * Create the pool - * - * @param minPool - * The minimum size of the pool - * @param maxPool - * The maximum size of the pool, set to zero (0) for unbounded - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - public Pool(int minPool, int maxPool) throws PoolSpecificationException { - - if (minPool < 0) { - throw new PoolSpecificationException(String.format("The minimum pool size must be a " - + "positive value or zero, %d is not valid.", minPool)); - } - if (maxPool != 0 && maxPool < minPool) { - throw new PoolSpecificationException(String.format("The maximum pool size must be a " - + "positive value greater than the minimum size, or zero. %d is not valid.", maxPool)); - } - - this.minPool = minPool; - this.maxPool = maxPool; - - properties = new Properties(); - free = new ArrayDeque(); - allocated = new ArrayList(); - lock = new ReentrantReadWriteLock(); - drained = new AtomicBoolean(false); - } - - /** - * Returns the amount of objects on the free collection - * - * @return The number of objects on the free collection - */ - public int getFreeSize() { - Lock readLock = lock.readLock(); - readLock.lock(); - try { - return free.size(); - } finally { - readLock.unlock(); - } - } - - /** - * Returns the value for a specified property of this pool, if defined. - * - * @param key - * The key of the desired property - * @return The value of the property, or null if not defined - */ - public String getProperty(String key) { - return properties.getProperty(key); - } - - /** - * Sets the value of the specified property or replaces it if it already exists - * - * @param key - * The key of the property to be set - * @param value - * The value to set the property to - */ - public void setProperty(String key, String value) { - properties.setProperty(key, value); - } - - /** - * @return The properties object for the pool - */ - public Properties getProperties() { - return properties; - } - - /** - * Returns the number of objects that are currently allocated - * - * @return The allocate collection size - */ - public int getAllocatedSize() { - Lock readLock = lock.readLock(); - readLock.lock(); - try { - return allocated.size(); - } finally { - readLock.unlock(); - } - } - - /** - * @return the value of allocator - */ - public Allocator getAllocator() { - return allocator; - } - - /** - * @param allocator - * the value for allocator - */ - public void setAllocator(Allocator allocator) { - this.allocator = allocator; - } - - /** - * @return the value of destructor - */ - public Destructor getDestructor() { - return destructor; - } - - /** - * @return the value of minPool - */ - public int getMinPool() { - return minPool; - } - - /** - * @return the value of maxPool - */ - public int getMaxPool() { - return maxPool; - } - - /** - * @param destructor - * the value for destructor - */ - public void setDestructor(Destructor destructor) { - this.destructor = destructor; - } - - /** - * Drains the pool, releasing and destroying all pooled objects, even if they are currently allocated. - */ - public void drain() { - if (drained.compareAndSet(false, true)) { - Lock writeLock = lock.writeLock(); - writeLock.lock(); - try { - int size = getAllocatedSize(); - /* - * We can't use the "release" method call here because we are modifying the list we are iterating - */ - ListIterator it = allocated.listIterator(); - while (it.hasNext()) { - T obj = it.next(); - it.remove(); - free.addFirst(obj); - } - size = getFreeSize(); - trim(size); - } finally { - writeLock.unlock(); - } - } - } - - /** - * Returns an indication if the pool has been drained - * - * @return True indicates that the pool has been drained. Once a pool has been drained, it can no longer be used. - */ - public boolean isDrained() { - return drained.get(); - } - - /** - * Reserves an object of type T from the pool for the caller and returns it - * - * @return The object of type T to be used by the caller - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws PoolDrainedException - * If the caller is trying to reserve an element from a drained pool - */ - @SuppressWarnings("unchecked") - public T reserve() throws PoolExtensionException, PoolDrainedException { - if (isDrained()) { - throw new PoolDrainedException("The pool has been drained and cannot be used."); - } - - T obj = null; - Lock writeLock = lock.writeLock(); - writeLock.lock(); - try { - int freeSize = getFreeSize(); - int allocatedSize = getAllocatedSize(); - - if (freeSize == 0) { - if (allocatedSize == 0) { - extend(minPool == 0 ? 1 : minPool); - } else if (allocatedSize >= maxPool && maxPool > 0) { - throw new PoolExtensionException(String.format("Unable to add " - + "more elements, pool is at maximum size of %d", maxPool)); - } else { - extend(1); - } - } - - obj = free.removeFirst(); - allocated.add(obj); - } finally { - writeLock.unlock(); - } - - /* - * Now that we have the real object, lets wrap it in a dynamic proxy so that we can intercept the close call and - * just return the context to the free pool. obj.getClass().getInterfaces(). We need to find ALL interfaces that - * the object (and all superclasses) implement and have the proxy implement them too - */ - Class cls = obj.getClass(); - Class[] array; - List> interfaces = new ArrayList>(); - while (!cls.equals(Object.class)) { - array = cls.getInterfaces(); - for (Class item : array) { - if (!interfaces.contains(item)) { - interfaces.add(item); - } - } - cls = cls.getSuperclass(); - } - array = new Class[interfaces.size()]; - array = interfaces.toArray(array); - return CachedElement.newInstance(this, obj, array); - } - - /** - * releases the allocated object back to the free pool to be used by another request. - * - * @param obj - * The object to be returned to the pool - * @throws PoolDrainedException - * If the caller is trying to release an element to a drained pool - */ - public void release(T obj) throws PoolDrainedException { - if (isDrained()) { - throw new PoolDrainedException("The pool has been drained and cannot be used."); - } - Lock writeLock = lock.writeLock(); - writeLock.lock(); - try { - if (allocated.remove(obj)) { - free.addFirst(obj); - } - } finally { - writeLock.unlock(); - } - } - - /** - * Extend the free pool by some number of elements - * - * @param count - * The number of elements to add to the pool - * @throws PoolExtensionException - * if the pool cannot be extended because no allocator has been specified. - */ - private void extend(int count) throws PoolExtensionException { - if (allocator == null) { - throw new PoolExtensionException(String.format("Unable to extend pool " - + "because no allocator has been specified")); - } - Lock writeLock = lock.writeLock(); - writeLock.lock(); - try { - for (int index = 0; index < count; index++) { - T obj = allocator.allocate(this); - if (obj == null) { - throw new PoolExtensionException( - "The allocator failed to allocate a new context to extend the pool."); - } - free.push(obj); - } - } finally { - writeLock.unlock(); - } - } - - /** - * Used to trim the free collection by some specified number of elements, or the free element count, whichever is - * less. The elements are removed from the end of the free element deque, thus trimming the oldest elements first. - * - * @param count - * The number of elements to trim - */ - private void trim(int count) { - Lock writeLock = lock.writeLock(); - writeLock.lock(); - try { - int trimCount = count; - if (getFreeSize() < count) { - trimCount = getFreeSize(); - } - for (int i = 0; i < trimCount; i++) { - T obj = free.removeLast(); - if (destructor != null) { - destructor.destroy(obj, this); - } - } - } finally { - writeLock.unlock(); - } - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/PoolDrainedException.java b/appc-common/src/main/java/org/openecomp/appc/pool/PoolDrainedException.java deleted file mode 100644 index 260dc7b45..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/PoolDrainedException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -/** - * This exception is thrown whenever an attempt is made to access a pool of resources where the pool has been drained. - * Once drained, the pool is no longer usable. - * - */ -public class PoolDrainedException extends PoolException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * PoolDrainedException constructor - * - * @param msg - * The error message - */ - public PoolDrainedException(String msg) { - super(msg); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/PoolException.java b/appc-common/src/main/java/org/openecomp/appc/pool/PoolException.java deleted file mode 100644 index 76d798be1..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/PoolException.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -/** - * A pool exception is a specialization of checked exceptions that define various pool abnormal states or requests. - * - */ -public class PoolException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * PoolException constructor - */ - public PoolException() { - } - - /** - * PoolException constructor - * - * @param message - * The error message - */ - public PoolException(String message) { - super(message); - } - - /** - * PoolException constructor - * - * @param cause - * The cause of the exception - */ - public PoolException(Throwable cause) { - super(cause); - } - - /** - * PoolException constructor - * - * @param message - * The error message - * @param cause - * The cause of the exception - */ - public PoolException(String message, Throwable cause) { - super(message, cause); - } - - /** - * PoolException constructor - * - * @param message - * The error message - * @param cause - * The cause of the exception - * @param enableSuppression - * whether or not suppression is enabled or disabled - * @param writableStackTrace - * whether or not the stack trace should be writable - */ - public PoolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/PoolExtensionException.java b/appc-common/src/main/java/org/openecomp/appc/pool/PoolExtensionException.java deleted file mode 100644 index c95c407c2..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/PoolExtensionException.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -/** - * An error occurred trying to extend the pool - * - */ -public class PoolExtensionException extends PoolException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * PoolExtensionException constructor - * - * @param msg - * The error message - */ - public PoolExtensionException(String msg) { - super(msg); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/pool/PoolSpecificationException.java b/appc-common/src/main/java/org/openecomp/appc/pool/PoolSpecificationException.java deleted file mode 100644 index 361e50a54..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/pool/PoolSpecificationException.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -/** - * This exception is thrown whenever the pool is not specified correctly - * - */ -public class PoolSpecificationException extends PoolException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * PoolSpecificationException constructor - * - * @param msg - * The error message - */ - public PoolSpecificationException(String msg) { - super(msg); - } - -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/JsonUtil.java b/appc-common/src/main/java/org/openecomp/appc/util/JsonUtil.java deleted file mode 100644 index c1906362e..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/JsonUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.util.Map; - - -public class JsonUtil { - /** - * @param valueAsString a valid json Map represented as String - * @return a flat map that each entry key derived from hierarchy path in the json object and flatted to a dotted separated string. - * e.g. "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} - * when it required that the input will not be flatted the json string should be formatted as below example: - * e.g. "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}" will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}} - * @throws IOException when the object is not valid json Map - */ - public static Map convertJsonStringToFlatMap(String valueAsString) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - Map readValueMap = objectMapper.readValue(valueAsString,Map.class); - return org.onap.appc.util.ObjectMapper.map(readValueMap); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/MessageFormatter.java b/appc-common/src/main/java/org/openecomp/appc/util/MessageFormatter.java deleted file mode 100644 index 44095fb71..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/MessageFormatter.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import org.apache.commons.lang3.StringUtils; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class MessageFormatter { - private final static String paramNameRegexGroupName = "paramName"; - private final static String paramRegex = "\\$\\{(?[^}$]+)\\}"; //start with ${ and after there is one or more characters that are not $ and not } and ended with } - - - public static String format(String messageTemplate, Map params) { - if (StringUtils.isEmpty(messageTemplate)) - return ""; - if (params == null || params.isEmpty()) - return messageTemplate; - - String formattedMessage = messageTemplate; - if (formattedMessage.contains("$")) { - for (Map.Entry entry : params.entrySet()) { - formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}", String.valueOf(entry.getValue())); - } - } - - return formattedMessage; - } - - public static List getParamsNamesList(String messageTemplate) { - List paramsNames = null; - if(!StringUtils.isEmpty(messageTemplate)){ - paramsNames = new ArrayList(); - Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate); - while (m.find()) { - String paramName = m.group(paramNameRegexGroupName); - paramsNames.add(paramName); - } - } - return paramsNames; - } - public static Set getParamsNamesSet(String messageTemplate) { - List paramsNamesList = getParamsNamesList(messageTemplate); - Set paramsNamesSet = null; - if(paramsNamesList != null && !paramsNamesList.isEmpty()){ - paramsNamesSet = new HashSet(); - for(String paramName : paramsNamesList){ - paramsNamesSet.add(paramName); - } - } - return paramsNamesSet; - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/ObjectMapper.java b/appc-common/src/main/java/org/openecomp/appc/util/ObjectMapper.java deleted file mode 100644 index df0b24a78..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/ObjectMapper.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import java.lang.reflect.Array; -import java.util.Map; - -public class ObjectMapper { - - private ObjectMapper() { - } - - private static void dispatch(PathContext context, Object obj) { - - if (obj == null) { - return; - } - - final Class cls = obj.getClass(); - - if (cls.isPrimitive() - || String.class.isAssignableFrom(cls) - || Number.class.isAssignableFrom(cls) - || Boolean.class.isAssignableFrom(cls)) { - handlePrimitive(context, obj); - } else if (cls.isArray()) { - handleArray(context, obj); - } else if (Map.class.isAssignableFrom(cls)) { - handleMap(context, (Map) obj); - } else if (Iterable.class.isAssignableFrom(cls)) { - handleCollection(context, Iterable.class.cast(obj)); - } else { - throw new IllegalArgumentException(obj.getClass().getName()); - } - } - - public static Map map(Object obj) { - PathContext context = new PathContext(); - dispatch(context, obj); - return context.entries(); - } - - private static void handleMap(PathContext context, Map val) { - for (Map.Entry entry : val.entrySet()) { - context.pushToken(entry.getKey().toString()); - dispatch(context, entry.getValue()); - context.popToken(); - } - } - - private static void handleCollection(PathContext context, Iterable val) { - int index = 0; - for (Object elem : val) { - handleElement(context, index++, elem); - } - } - - private static void handleArray(PathContext context, Object val) { - for (int i = 0, n = Array.getLength(val); i < n; i++) { - handleElement(context, i, Array.get(val, i)); - } - } - - private static void handleElement(PathContext context, int index, Object val) { - if (val == null) { - return; - } - - String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString(); - - context.pushModifier(modifier); - dispatch(context, val); - context.popModifier(); - } - - private static void handlePrimitive(PathContext context, Object val) { - context.entry(context.getPath(), val.toString()); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/PathContext.java b/appc-common/src/main/java/org/openecomp/appc/util/PathContext.java deleted file mode 100644 index 79b75d1a4..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/PathContext.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; - -class PathContext { - - private StringBuilder path = new StringBuilder(128); - - private LinkedList indexes = new LinkedList<>(); - private Map entries = new LinkedHashMap<>(); - private int offset = 0; - - private final String delimiter; - - PathContext() { - this("."); - } - - PathContext(String delimiter) { - this.delimiter = delimiter; - } - - private void push(String elem, boolean delimit) { - if (elem == null) { - throw new IllegalArgumentException(); - } - - int length = elem.length(); - - if (delimit && !indexes.isEmpty()) { - path.append(delimiter); - length += delimiter.length(); - } - - path.append(elem); - offset += length; - indexes.addLast(Integer.valueOf(length)); - } - - private void pop() { - if (indexes.isEmpty()) { - throw new IllegalStateException(); - } - offset -= indexes.removeLast(); - path.setLength(offset); - } - - void pushToken(String token) { - push(token, true); - } - - void popToken() { - pop(); - } - - void pushModifier(String modifier) { - push(modifier, false); - } - - void popModifier() { - pop(); - } - - String getPath() { - return path.substring(0, offset); - } - - void entry(String name, String value) { - entries.put(name, value); - } - - Map entries() { - return Collections.unmodifiableMap(entries); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/StringHelper.java b/appc-common/src/main/java/org/openecomp/appc/util/StringHelper.java deleted file mode 100644 index 2e68cbba4..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/StringHelper.java +++ /dev/null @@ -1,595 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class contains several static helper methods that can be used to perform string manipulation algorithms. - * - */ - -public final class StringHelper { - - public static final String DASH = "-"; - public static final String DOT = "."; - public static final String ELLIPSES = "..."; - public static final String LINE_FEED = "\n"; - public static final String SLASH = "/"; - public static final String COMMA = ","; - - /** - * Converts the specified string pattern to a regular expression string. If the supplied string is null or empty, - * then a regular expression that matches all strings (.*) is returned. - *

- * The expression passed to this method should not already be a regular expression. If it contains problematic - * meta-characters for this routine (such as period, asterisk, and plus), they will be escaped and matched literally - * in the resulting regular expression returned. - *

- * - * @param value - * The pattern that we need to convert to a regular expression - * @return The regular expression that is equivalent to the pattern - */ - public static String convertToRegex(String value) { - if (value == null || value.trim().length() == 0) { - return ".*"; - } - boolean appendEOL = false; - StringBuffer buffer = new StringBuffer(value.trim()); - - /* - * If there are any period characters, we need to escape them so that they are exactly matched - */ - Pattern pattern = Pattern.compile("\\."); - Matcher matcher = pattern.matcher(buffer); - int position = 0; - while (matcher.find(position)) { - buffer.replace(matcher.start(), matcher.end(), "\\."); - position = matcher.end() + 1; - } - - /* - * If there are any asterisks or pluses, which we need to interpret as wildcard characters, we need to convert - * them into .* or . - */ - pattern = Pattern.compile("\\*|\\+"); - matcher = pattern.matcher(buffer); - position = 0; - while (matcher.find(position)) { - String metachar = buffer.substring(matcher.start(), matcher.end()); - if (metachar.equals("*")) { - buffer.replace(matcher.start(), matcher.end(), ".*"); - position = matcher.end() + 1; - if (matcher.end() < buffer.length() - 1) { - appendEOL = true; - } - } else if (metachar.equals("+")) { - buffer.replace(matcher.start(), matcher.end(), "."); - position = matcher.end(); - if (matcher.end() == buffer.length()) { - appendEOL = true; - } - } - } - - /* - * If the string contains a .* meta-character sequence anywhere in the middle of the string (i.e., there are - * other characters following the .* meta-characters), OR the string ends with the .+ sequence, then we need to - * append the "end-of-line" boundary condition to the end of the string to get predictable results. - */ - if (appendEOL) { - buffer.append("$"); - } - return buffer.toString(); - } - - /** - * Takes a string that may possibly be very long and return a string that is at most maxLength. If the string is - * longer than maxLength, the last three characters will be the ellipses (...) to indicate that the string was - * shortened. - * - * @param possiblyLongString - * @param maxLength - * must be at least 4 (one character plus ellipses) - * @return possibly shortened string - */ - public static String getShortenedString(String possiblyLongString, int maxLength) { - if ((possiblyLongString != null) && (maxLength > ELLIPSES.length()) - && (possiblyLongString.length() > maxLength)) { - return possiblyLongString.substring(0, maxLength - ELLIPSES.length()) + ELLIPSES; - - } - return possiblyLongString; - } - - /** - * Determines that a provided string is not null and not empty (length = 0 after trimming) - * - * @param theString - * The string to be tested - * @return true if the string IS NOT null and is NOT empty - */ - public static boolean isNotNullNotEmpty(String theString) { - return ((theString != null) && (!theString.trim().isEmpty())); - } - - /** - * Determines that a provided string IS null or an empty string (length = 0 after trimming) - * - * @param theString - * The string to be tested - * @return true if the string IS null OR is empty - */ - public static boolean isNullOrEmpty(String theString) { - return ((theString == null) || (theString.trim().isEmpty())); - } - - /** - * Returns an indication if the first string is equal to the second string, allowing for either or both strings to - * be null. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @return True if both strings are null, or both strings are non-null AND they are equal. False otherwise. - */ - public static boolean equals(String a, String b) { - return equals(a, b, false); - } - - /** - * Returns an indication if the first string is equal to the second string, allowing for either or both strings to - * be null, and ignoring case. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @return True if both strings are null, or both strings are non-null AND they are equal (without regard to case). - * False otherwise. - */ - public static boolean equalsIgnoreCase(String a, String b) { - return equals(a, b, true); - } - - /** - * Compares two strings (allowing either or both to be null), and allowing for optional case sensitive or - * insensitive comparison. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @param caseInsensitive - * True if the comparison is to be case in-sensitive. - * @return True if both strings are null, or both strings are non-null and they are equal - */ - private static boolean equals(String a, String b, boolean caseInsensitive) { - if (a == null && b == null) { - return true; - } - if (a != null && b != null) { - if (caseInsensitive) { - return a.equalsIgnoreCase(b); - } else { - return a.equals(b); - } - } - - return false; - } - - /** - * This method is used to mangle a name. - *

- * This method will first remove all unacceptable characters from the name and translate all characters to lower - * case. This is done to eliminate any potentially troublesome characters. If the resulting string is empty, then a - * random string of characters for the minimum desired length is returned. If the string is too short to meet the - * minimum length requirement, it is padded with random characters. - *

- *

- * Once the string has been scrubbed and possibly padded, it may be truncated (if longer than the maximum value) and - * the result is returned. To make the string as unique as possible, the algorithm removes excess letters from the - * center of the string, concatenating the first nad last parts of the name together. The assumption is that users - * tend to start the names of multiple things in similar ways, and get more descriptive as the name progresses. If - * for example, several objects were named "A test Object", "A test Object1", and "A test Object2", shortening the - * name only from the left does not generate a unique name. - *

- * - * @param name - * The name to be mangled - * @param minLen - * minimum number of characters for the name - * @param maxLen - * maximum number of characters for the name - * @return The mangled name, or an empty string if the value is null or an empty string. - */ - public static String mangleName(String name, int minLen, int maxLen) { - StringBuffer buffer = new StringBuffer(name == null ? "" : name); - Pattern pattern = Pattern.compile("[^a-z0-9]+", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(buffer); - int position = 0; - while (matcher.find(position)) { - buffer.delete(matcher.start(), matcher.end()); - position = matcher.start(); - } - - if (buffer.length() < minLen) { - for (int i = buffer.length(); i <= minLen; i++) { - buffer.append("A"); - } - } - - /* - * Remove out of the center of the name to preserve start and end and result in a string of max len - */ - if (buffer.length() > maxLen) { - int excess = buffer.length() - maxLen; - int left = maxLen / 2; - - buffer.delete(left, excess + left); - } - - return buffer.toString().toLowerCase(); - } - - /** - * This method is used to normalize a string value. - *

- * This method will ensure that the string value is trimmed of all leading and trailing whitespace if not null. If - * it is null or an empty string, then it will return null. - *

- * - * @param value - * The value to be normalized - * @return The normalized (no leading or trailing whitespace) value, or null if the string was null or an empty - * string (or all whitespace). This method will never return an empty string. - */ - public static String normalizeString(String value) { - if (value != null) { - String temp = value.trim(); - if (temp.length() > 0) { - return temp; - } - } - return null; - } - - /** - * This method is used to strip all carriage returns and line feed characters from a string - * - * @param value - * @return The original value less all carriage returns and line feeds - */ - public static String stripCRLF(String value) { - - if (value == null) { - return null; - } - String[] tokens = value.split("\r\n|\n\r|\r|\n"); - StringBuffer buffer = new StringBuffer(); - for (String token : tokens) { - buffer.append(token.trim()); - } - return buffer.toString(); - } - - /** - * Converts UNIX-style line endings to DOS-style. Replaces LF with CR+LF as long as the LF does not already exist - * paired with a CR. - * - * @param content - * The content to be converted - * @return The converted content. - */ - public static String toDOSLines(String content) { - if (content == null) { - return null; - } - - StringBuffer buffer = new StringBuffer(content); - Pattern pattern = Pattern.compile("^(\n)[^\r]|[^\r](\n)[^\r]|[^\r](\n)$"); - Matcher matcher = pattern.matcher(buffer); - int position = 0; - while (matcher.find(position)) { - int index = matcher.start(1); - if (index == -1) { - index = matcher.start(2); - } - if (index == -1) { - index = matcher.start(3); - } - - buffer.replace(index, index + 1, "\r\n"); - position = index + 1; - } - - return buffer.toString(); - } - - /** - * This method will convert a string contents to use the UNIX-style line endings. That is, all occurrences of CR - * (Carriage Return) and LF (Line Feed) are reduced to just use LF. - * - * @param content - * The buffer to be processed - * @return The converted contents - */ - public static String toUnixLines(String content) { - if (content == null) { - return null; - } - - StringBuffer buffer = new StringBuffer(content); - Pattern pattern = Pattern.compile("\r\n|\n\r"); - Matcher matcher = pattern.matcher(buffer); - int position = 0; - while (matcher.find(position)) { - buffer.replace(matcher.start(), matcher.end(), "\n"); - position = matcher.start(); - } - - return buffer.toString(); - } - - /** - * This method is used to translate characters in the input sequence that match the characters in the match list to - * the corresponding character in the replacement list. If the replacement list is shorter than the match list, then - * the character from the replacement list is taken as the modulo of the match character position and the length of - * the replacement list. - * - * @param sequence - * The input sequence to be processed - * @param match - * The list of matching characters to be searched - * @param replacement - * The list of replacement characters, positional coincident with the match list. If shorter than the - * match list, then the position "wraps" around on the replacement list. - * @return The translated string contents. - */ - public static Object translate(String sequence, String match, String replacement) { - - if (sequence == null) { - return sequence; - } - - StringBuffer buffer = new StringBuffer(sequence); - - for (int index = 0; index < buffer.length(); index++) { - char ch = buffer.charAt(index); - - int position = match.indexOf(ch); - if (position == -1) { - continue; - } - - if (position >= replacement.length()) { - position %= replacement.length(); - } - buffer.setCharAt(index, replacement.charAt(position)); - } - - return buffer.toString(); - } - - /** - * Ensures that the name provided is a valid identifier. This means that no spaces are allowed as well as special - * characters. This method translates all spaces and illegal characters to underscores (_). - * - * @param name - * The name to be checked and converted to an identifier if needed - * @return The valid identifier from the name - */ - public static String validIdentifier(String name) { - if (name == null || name.length() == 0) { - return name; - } - - StringBuffer buffer = new StringBuffer(name); - for (int index = 0; index < buffer.length(); index++) { - char ch = buffer.charAt(index); - - if ((index == 0 && !Character.isJavaIdentifierStart(ch)) || (!Character.isJavaIdentifierPart(ch))) { - buffer.setCharAt(index, '_'); - } - } - return buffer.toString(); - } - - /** - * This method verifies that the provided string only contains characters from the legal set, and replaces any - * character not in the legal set with the specified replacement character. - * - * @param sequence - * The sequence to be verified - * @param legal - * The set of all legal characters - * @param replacement - * The replacement character if a character is not in the legal set - * @return The verified *and possibly updated) string - */ - public static String verify(String sequence, String legal, char replacement) { - if (sequence == null) { - return sequence; - } - - StringBuffer buffer = new StringBuffer(sequence); - for (int index = 0; index < buffer.length(); index++) { - char ch = buffer.charAt(index); - if (legal.indexOf(ch) == -1) { - buffer.setCharAt(index, replacement); - } - } - return buffer.toString(); - } - - /** - * Private constructor to prevent instantiation of this class - All methods are static! - */ - private StringHelper() { - - } - - /** - * @param list - * The list of elements - * @return The list of elements formatted as a comma-delimited list - */ - public static String asList(List list) { - StringBuffer buffer = new StringBuffer(); - if (list != null) { - if (list.size() == 1) { - buffer.append(list.get(0)); - } else { - for (String element : list) { - buffer.append(element); - buffer.append(", "); - } - - if (buffer.length() > 2) { - buffer.delete(buffer.length() - 2, buffer.length()); - } - } - } - return buffer.toString(); - } - - /** - * @param map - * A map of strings - * @return A map expressed as a comma-delimited list of name=value tuples - */ - public static String asList(Map map) { - StringBuffer buffer = new StringBuffer(); - if (map != null) { - Set keys = map.keySet(); - for (String key : keys) { - buffer.append(String.format("%s=%s, ", key, map.get(key))); - } - - if (buffer.length() > 2) { - buffer.delete(buffer.length() - 2, buffer.length()); - } - } - return buffer.toString(); - } - - /** - * @param values - * An array or varargs of Strings to be concatenated into a comma-separated list - * @return The comma-seprated list of values - */ - public static String asList(String... values) { - StringBuilder builder = new StringBuilder(); - builder.append('['); - if (values != null && values.length > 0) { - int count = values.length; - for (int index = 0; index < count - 1; index++) { - builder.append(values[index]); - builder.append(','); - } - builder.append(values[count - 1]); - } - builder.append(']'); - return builder.toString(); - } - - public static Object resolveToType(String input) { - String intRegex = "^(\\-)?[0-9]+$"; - String doubleRegex = "^(\\-)?[0-9\\.]+$"; - String boolRegex = "(^(?i)((true)|(false))$)"; - - // Check for null - if (input == null) { - return null; - } - - // Check int first - if (input.matches(intRegex)) { - try { - return Integer.parseInt(input); - } catch (NumberFormatException nfe) { - // Should not happen - nfe.printStackTrace(); - } - } - - // Check double (int + decimal point) - if (input.matches(doubleRegex)) { - try { - return Double.parseDouble(input); - } catch (NumberFormatException | NullPointerException e) { - // NPE won't happen bc of regex check - } - } - - // Check boolean - if (input.matches(boolRegex)) { - return Boolean.parseBoolean(input); - } - - // Try to parse a date - Date date = Time.utcParse(input); - if (date != null) { - return date; - } - - // No special type, return string - return input; - } - - /** - * Converts a properties object to a string in the format of
[ key=value, key=value, ... ]
- * - * @param props - * The properties object to format - * @return A string in the format
[ key=value, ... ]
or null if the input was null - */ - public static String propertiesToString(Properties props) { - if (props == null) { - return null; - } - StringBuilder out = new StringBuilder(); - out.append("["); - for (Object key : props.keySet()) { - out.append(String.format(" %s = %s,", key.toString(), props.getProperty(key.toString()))); - } - if (props.size() > 0) { - out.deleteCharAt(out.lastIndexOf(",")); - } - out.append(" ]"); - return out.toString(); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/StructuredPropertyHelper.java b/appc-common/src/main/java/org/openecomp/appc/util/StructuredPropertyHelper.java deleted file mode 100644 index b610b5a3e..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/StructuredPropertyHelper.java +++ /dev/null @@ -1,260 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class is used to assemble properties that are defined using a structured name into groups, and allow them to be - * processed as sets of definitions. - *

- * For example, a structured name uses a dotted-notation, like "provider.name". Further, the nodes of the structured - * name may be serialized using a suffix ordinal number (e.g., "provider1.name"). These structured properties form a - * hierarchical name space where the names are grouped together and can be retrieved as a set. - *

- * - */ - -public class StructuredPropertyHelper { - - /** - * This method scans the properties object for all properties that match the root name and constructs a list of - * structured property node graphs that represents the namespaces of the properties. - *

- * For example, assume that there are structured properties of the form "provider1.name", "provider2.name", - * "provider3.name", and so forth. There may also be other subordinate properties as well (e.g., "provider1.type"). - * This method would construct a list of graphs of nodes, where each node represents one value of the structured - * name. The roots would be the values "provider1", "provider2", "provider3", and so forth. The values of the - * subordinate nodes would be the second, third, and so forth name nodes of the compound name. The value of the - * property is associated with nodes that are representative of the leaf of the name space. - *

- * - * @param properties - * The properties to be processed - * @param prefix - * The prefix of the root structured property name - * @return The node graph of the properties - */ - public static List getStructuredProperties(Properties properties, String prefix) { - List roots = new ArrayList<>(); - - for (String name : properties.stringPropertyNames()) { - if (name.startsWith(prefix)) { - String value = properties.getProperty(name); - processNamespace(roots, name, value); - } - } - - return roots; - } - - /** - * This method recursively walks the name space of the structured property and constructs the node graph to - * represent the property - * - * @param nodes - * The collection of nodes for the current level of the name space - * @param propertyName - * The name of the node - * @param value - * The value, if any - * @return The node for this level in the namespace - */ - @SuppressWarnings("nls") - private static Node processNamespace(List nodes, String propertyName, String value) { - String[] tokens = propertyName.split("\\.", 2); - String nodeName = normalizeNodeName(tokens[0]); - - Node namespaceNode = null; - for (Node node : nodes) { - if (node.getName().equals(nodeName)) { - namespaceNode = node; - break; - } - } - if (namespaceNode == null) { - namespaceNode = new Node(); - namespaceNode.setName(nodeName); - nodes.add(namespaceNode); - } - - if (tokens.length == 1 || tokens[1] == null || tokens[1].length() == 0) { - namespaceNode.setValue(value); - } else { - processNamespace(namespaceNode.getChildren(), tokens[1], value); - } - - return namespaceNode; - } - - /** - * This method normalizes a node name of the structured property name by removing leading and trailing whitespace, - * and by converting any ordinal position to a simple expression without leading zeroes. - * - * @param token - * The token to be normalized - * @return The normalized name, or null if the token was null; - */ - @SuppressWarnings("nls") - private static String normalizeNodeName(String token) { - if (token == null) { - return null; - } - - StringBuffer buffer = new StringBuffer(token.trim()); - Pattern pattern = Pattern.compile("([^0-9]+)([0-9]*)"); - Matcher matcher = pattern.matcher(buffer); - if (matcher.matches()) { - String nameRoot = matcher.group(1); - String ordinal = matcher.group(2); - if (ordinal != null && ordinal.length() > 0) { - int i = Integer.parseInt(ordinal); - buffer.setLength(0); - buffer.append(nameRoot); - buffer.append(Integer.toString(i)); - } - } - return buffer.toString(); - } - - /** - * This class represents a node in the structured property name space - * - */ - public static class Node implements Comparable { - - /** - * The name of the structured property node - */ - private String name; - - /** - * If the node is a leaf, then the value of the property - */ - private String value; - - /** - * If the node is not a leaf, then the sub-nodes of the property - */ - private List children; - - /** - * @return the value of name - */ - public String getName() { - return name; - } - - /** - * @param name - * the value for name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the value of value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value for value - */ - public void setValue(String value) { - this.value = value; - } - - /** - * @return the value of children - */ - public List getChildren() { - if (children == null) { - children = new ArrayList<>(); - } - return children; - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return name.hashCode() + (value != null ? value.hashCode() : children.hashCode()); - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (this.getClass() != obj.getClass()) - return false; - - Node other = (Node) obj; - boolean result = name.equals(other.name); - - if (value == null) { - result &= other.value == null; - } else { - result &= value.equals(other.value); - } - if (children == null) { - result &= other.children == null; - } else { - result &= children.equals(other.children); - } - return result; - } - - /** - * @see java.lang.Object#toString() - */ - @SuppressWarnings("nls") - @Override - public String toString() { - if (value != null) { - return String.format("%s = %s", name, value); - } - return String.format("%s.%s", name, children.toString()); - } - - @Override - public int compareTo(StructuredPropertyHelper.Node o) { - return name.compareTo(o.name); - } - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/Time.java b/appc-common/src/main/java/org/openecomp/appc/util/Time.java deleted file mode 100644 index ce2babdc3..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/Time.java +++ /dev/null @@ -1,611 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import java.util.SimpleTimeZone; -import java.util.TimeZone; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is a general purpose helper class to augment standard Java time support. - * - */ - -public final class Time { - - /** - * Logger to log operations - */ - private static final Logger LOG = LoggerFactory.getLogger(Time.class); - - /** - * A formatter to be used to format values - */ - private static SimpleDateFormat dateformatter = null; - - /** - * The UTC timezone (for UTC or GMT time) - */ - @SuppressWarnings("nls") - private static final TimeZone utcTZ = TimeZone.getTimeZone("UTC"); - - /** - * The cached reference to the datatype factory - */ - private static DatatypeFactory xmlDatatypeFactory = null; - - /** - * Private default constructor prevents instantiation - */ - private Time() { - // - } - - /** - * Increments a date by the indicated months, days, hours, minutes, and seconds, and returns the updated date. - * - * @param date - * The date to be manipulated - * @param months - * The number of months to be added to the date - * @param days - * The number of days to be added to the date - * @param hours - * The number of hours to be added to the date - * @param minutes - * The number of minutes to be added to the date - * @param seconds - * The number of seconds to be added to the date - * @return The updated date. - */ - public static Date addTime(final Date date, final int months, final int days, final int hours, final int minutes, - final int seconds) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.add(Calendar.MONTH, months); - cal.add(Calendar.DATE, days); - cal.add(Calendar.HOUR_OF_DAY, hours); - cal.add(Calendar.MINUTE, minutes); - cal.add(Calendar.SECOND, seconds); - return cal.getTime(); - } - - /** - * Clears the time components of a calendar to zero, leaving the date components unchanged. - * - * @param cal - * the calendar to be updated - * @return The updated calendar object - */ - public static Calendar dateOnly(final Calendar cal) { - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - return cal; - } - - /** - * This method returns the local time that corresponds to the end of the current day - * - * @return The time that corresponds to the end of the current day, expressed as local time - */ - public static Date endOfDayLocal() { - return endOfDayLocal(new Date()); - } - - /** - * This method returns the last moment of the day for the supplied local time. This is defined as the millisecond - * before midnight of the current date represented by the local time. - * - * @param localTime - * The local time for which the last moment of the day is desired. - * @return The millisecond prior to midnight, local time. - */ - public static Date endOfDayLocal(final Date localTime) { - // @sonar:off - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTime(localTime); - calendar.set(Calendar.HOUR, 11); - calendar.set(Calendar.AM_PM, Calendar.PM); - calendar.set(Calendar.MINUTE, 59); - calendar.set(Calendar.SECOND, 59); - calendar.set(Calendar.MILLISECOND, 999); - // @sonar:on - - return calendar.getTime(); - } - - /** - * The end of the current day and in the current time zone expressed as a UTC time. - * - * @return The UTC time that corresponds to the end of the current day - */ - public static Date endOfDayUTC() { - return endOfDayUTC(new Date()); - } - - /** - * Returns the UTC time that corresponds to the end of the day for the local time specified, using the current - * (default) time zone. - * - * @param localTime - * The local time for which we are requesting the UTC time that corresponds to the end of the day - * @return The UTC time that corresponds to the end of the local day specified by the local time. - */ - public static Date endOfDayUTC(final Date localTime) { - return endOfDayUTC(localTime, TimeZone.getDefault()); - } - - /** - * Returns the time expressed in UTC time of the end of the day specified in local time and within the local time - * zone. - * - * @param localTime - * The local time for which we will compute the end of the local day, and then convert to UTC time. - * @param localTimeZone - * The time zone that the local time is within. - * @return The UTC date that corresponds to the end of the day local time and in the local time zone. - */ - public static Date endOfDayUTC(final Date localTime, final TimeZone localTimeZone) { - Date endOfDay = endOfDayLocal(localTime); - return utcDate(endOfDay, localTimeZone); - } - - /** - * returns current Date in 'UTC' Timezone - * - * @return The current date, expressed in the UTC timezone. - */ - @SuppressWarnings("nls") - public static Date getCurrentUTCDate() { - - // This code incorrectly changes the default timezone for the entire JVM in order to compute the UTC - // date for the current time. - - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.setTimeInMillis(utcTime()); - return calendar.getTime(); - } - - /** - * This method loads and caches the reference to the XML data type factory object. - * - * @return The XML Data Type Factory object - */ - public static DatatypeFactory getDatatypeFactory() { - if (xmlDatatypeFactory == null) { - try { - xmlDatatypeFactory = DatatypeFactory.newInstance(); - } catch (DatatypeConfigurationException e) { - e.printStackTrace(System.err); - } - } - return xmlDatatypeFactory; - } - - /** - * Gives the date-time String based on given Locale and Timezone - * - * @param date - * The date to be formatted - * @param locale - * The locale that we want to format the value for - * @param timezone - * The time zone that the date is within - * @return The formatted value - */ - public static String getDateByLocaleAndTimeZone(final Date date, final Locale locale, final TimeZone timezone) { - String strDate = null; - DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); - df.setTimeZone(timezone); - synchronized (df) { - strDate = df.format(date); - } - return strDate; - } - - /** - * Returns singleton UTC date formatter. - * - * @return - */ - @SuppressWarnings("nls") - private static SimpleDateFormat getDateFormatter() { - if (dateformatter == null) { - dateformatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); - dateformatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); - } - return dateformatter; - } - - /** - * This method returns the local time that corresponds to a given UTC time in the current time zone. - * - * @param utcTime - * The UTC time for which we desire the equivalent local time in the current time zone. - * @return The local time that is equivalent to the given UTC time for the current time zone - */ - public static long localTime(final long utcTime) { - return localTime(utcTime, TimeZone.getDefault()); - } - - /** - * This method can be used to get the local time that corresponds to a specific UTC time. - *

- * This method has a problem since the offset can only be determined by having a local time. So, we take the UTC - * time and add the raw offset to it to come up with an approximation of the local time. This gives us a local time - * that we can use to determine what the offset should be, which is what we actually add to the UTC time to get the - * local time. - *

- * - * @param utcTime - * The UTC time for which we want to obtain the equivalent local time - * @param localTZ - * The time zone that we want the local time to be within - * @return The local time for the specified time zone and the given UTC time - */ - public static long localTime(final long utcTime, final TimeZone localTZ) { - int offset = localTZ.getOffset(utcTime + localTZ.getRawOffset()); - long result = utcTime + offset; - - return result; - } - - /** - * Sets the date components of a calendar to the specified values, leaving the time components unchanged. - * - * @param cal - * The calendar to be updated - * @param year - * The year to be set - * @param month - * The month to be set - * @param day - * The day to be set - * @return The updated calendar object - */ - public static Calendar setDate(final Calendar cal, final int year, final int month, final int day) { - cal.set(Calendar.YEAR, year); - cal.set(Calendar.MONTH, month); - cal.set(Calendar.DAY_OF_MONTH, day); - return cal; - } - - /** - * Returns the start of the day expressed in local time for the current local time. - * - * @return The start of the day - */ - public static Date startOfDayLocal() { - return startOfDayLocal(new Date()); - } - - /** - * This method returns the date that corresponds to the start of the day local time. The date returned represents - * midnight of the previous day represented in local time. If the UTC time is desired, use the methods - * {@link #startOfDayUTC(Date, TimeZone)}, {@link #startOfDayUTC(Date)}, or {@link #startOfDayUTC()} - * - * @param localTime - * The local date that we wish to compute the start of day for. - * @return The date that corresponds to the start of the local day - */ - public static Date startOfDayLocal(final Date localTime) { - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTime(localTime); - calendar.set(Calendar.HOUR, 0); - calendar.set(Calendar.AM_PM, Calendar.AM); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - - return calendar.getTime(); - } - - /** - * This method returns the UTC date that corresponds to the start of the local day based on the current time and the - * default time zone (the time zone we are running in). - * - * @return The start of the local day expressed as a UTC time. - */ - public static Date startOfDayUTC() { - return startOfDayUTC(new Date()); - } - - /** - * This method returns the UTC date that corresponds to the start of the local day specified in the current time - * zone. - * - * @param localTime - * The local time to be used to compute the start of the day - * @return The start of the local day expressed as a UTC time. - */ - public static Date startOfDayUTC(final Date localTime) { - return startOfDayUTC(localTime, TimeZone.getDefault()); - } - - /** - * This method returns the UTC date that corresponds to the start of the local day specified in the local timezone. - * - * @param localTime - * The local time to be used to compute start of day - * @param localTimeZone - * The time zone that the local time was recorded within - * @return The corresponding UTC date - */ - public static Date startOfDayUTC(final Date localTime, final TimeZone localTimeZone) { - Date startOfDay = startOfDayLocal(localTime); - return utcDate(startOfDay, localTimeZone); - } - - /** - * This method creates and returns an XML timestamp expressed as the current UTC value for the system. The caller - * does not specify the time value or time zone using this method. This ensures that the timestamp value is always - * expressed as UTC time. - * - * @return The XMLGregorianCalendar that can be used to record the timestamp - */ - - public static XMLGregorianCalendar timestamp() { - getDatatypeFactory(); - XMLGregorianCalendar ts = xmlDatatypeFactory.newXMLGregorianCalendar(); - GregorianCalendar utc = new GregorianCalendar(); - utc.setTime(utcDate()); - ts.setTimezone(0); - ts.setYear(utc.get(Calendar.YEAR)); - // Calendar Months are from 0-11 need to +1 - ts.setMonth(utc.get(Calendar.MONTH) + 1); - ts.setDay(utc.get(Calendar.DAY_OF_MONTH)); - ts.setHour(utc.get(Calendar.HOUR_OF_DAY)); - ts.setMinute(utc.get(Calendar.MINUTE)); - ts.setSecond(utc.get(Calendar.SECOND)); - ts.setMillisecond(utc.get(Calendar.MILLISECOND)); - return ts; - } - - /** - * Converts XMLGregorianCalendar to java.util.Date in Java - * - * @param calendar - * the calendar object to be converted - * @return The equivalent Date object - */ - public static Date toDate(final XMLGregorianCalendar calendar) { - if (calendar == null) { - return null; - } - return calendar.toGregorianCalendar().getTime(); - } - - /** - * Converts java Date to XMLGregorianCalendar. - * - * @param date - * The date to convert - * @return The XMLGregorianCalendar for the specified date - */ - @SuppressWarnings("nls") - public static XMLGregorianCalendar toXMLCalendar(final Date date) { - GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); - cal.setTime(date); - - XMLGregorianCalendar xmlCal = null; - try { - xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); - } catch (DatatypeConfigurationException e) { - LOG.error("toXMLCalendar", e); - } - return xmlCal; - } - - /** - * Truncates the provided date so that only the date, hours, and minutes portions are significant. This method - * returns the date with the seconds and milliseconds forced to zero. - * - * @param date - * The date to truncate - * @return The date with only the year, month, day, hours, and minutes significant. - */ - public static Date truncDate(final Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - return cal.getTime(); - } - - /** - * The UTC date that corresponds to the current date in the local time zone. - * - * @return The UTC date for now in the current time zone. - */ - public static Date utcDate() { - return new Date(); - } - - /** - * The UTC date for the specified date in the current (default) time zone. - * - * @param date - * The local date for which the UTC date is desired. - * @return The UTC date that corresponds to the date in the current time zone. - */ - public static Date utcDate(final Date date) { - TimeZone tz = TimeZone.getDefault(); - return utcDate(date, tz); - } - - /** - * Returns the UTC date for the specified date in the specified time zone. - * - * @param date - * The date for which the UTC date is desired in the specified zone - * @param tz - * The time zone that corresponds to the date to be converted to UTC - * @return The UTC date that corresponds to the local date in the local time zone. - */ - public static Date utcDate(final Date date, final TimeZone tz) { - return new Date(utcTime(date.getTime(), tz)); - } - - /** - * Format incoming date as string in GMT or UTC. - * - * @param dt - * The date to be formatted - * @return The date formatted for UTC timezone - */ - public static String utcFormat(final Date dt) { - String strDate = null; - DateFormat df = getDateFormatter(); - synchronized (df) { - strDate = df.format(dt); - } - return strDate; - } - - /** - * Parse previously formated Date object back to a Date object. - * - * @param dateStr - * The representation of a UTC date as a string - * @return The date object containing the parsed representation, or null if the representation cannot be parsed - */ - @SuppressWarnings("nls") - public static Date utcParse(final String dateStr) { - String[] adtl = { - "yyyy-MM-dd" - }; - return utcParse(dateStr, adtl); - } - - /** - * Parse previously formated Date object back to a Date object. - * - * @param dateStr - * The representation of a UTC date as a string - * @param adtlFormatStrings - * A list of strings that represent additional date format representations to try and parse. - * @return The date object containing the parsed representation, or null if the representation cannot be parsed - */ - @SuppressWarnings("nls") - public static Date utcParse(final String dateStr, String... adtlFormatStrings) { - if (dateStr != null) { - // Build the list of formatters starting with the default defined in the class - List formats = new ArrayList<>(); - formats.add(getDateFormatter()); - - if (adtlFormatStrings != null) { - for (String s : adtlFormatStrings) { - formats.add(new SimpleDateFormat(s)); - } - } - - // Return the first matching date formatter's result - for (DateFormat df : formats) { - df.setTimeZone(utcTZ); - try { - return df.parse(dateStr); - } catch (ParseException e) { - LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", dateStr, - df.toString())); - } - } - } - return null; - } - - /** - * This method returns the current time for the UTC timezone - * - * @return The time in the UTC time zone that corresponds to the current local time. - */ - public static long utcTime() { - return new Date().getTime(); - } - - /** - * Get the UTC time that corresponds to the given time in the default time zone (current time zone for the system). - * - * @param localTime - * The time in the current time zone for which the UTC time is desired. - * @return The UTC time - */ - public static long utcTime(final long localTime) { - TimeZone tz = TimeZone.getDefault(); - return utcTime(localTime, tz); - } - - /** - * Get the UTC time that corresponds to the given time in the specified timezone. - *

- * Note that the java getOffset() method works a little counter-intuitive. It returns the offset that - * would be added to the current UTC time to get the LOCAL time represented by the local time zone. That means to - * get the UTC time, we need to SUBTRACT this offset from the local time. - *

- * - * @param localTime - * The time in the specified time zone for which the UTC time is desired. - * @param localTZ - * The time zone which the local time is in. - * @return The UTC time for the specified local time in the specified local time zone. - */ - public static long utcTime(final long localTime, final TimeZone localTZ) { - int offset = localTZ.getOffset(localTime); - return localTime - offset; - - } - - /** - * Creates a timestamp value from a time - * - * @param utcTime - * The UTC time to convert to a timestamp - * @return The timestamp - */ - public static Timestamp utcTimestamp(final long utcTime) { - TimeZone tz = TimeZone.getDefault(); - return new Timestamp(utcTime(utcTime, tz)); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/UnmodifiableProperties.java b/appc-common/src/main/java/org/openecomp/appc/util/UnmodifiableProperties.java deleted file mode 100644 index 831f0f503..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/UnmodifiableProperties.java +++ /dev/null @@ -1,356 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.InvalidPropertiesFormatException; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * This utility class is used to wrap a properties object and to delegate all read operations to the property object, - * while disallowing any write or modification to the property object. - * - */ -public class UnmodifiableProperties extends Properties implements Cloneable { - - /** - * Serial number - */ - private static final long serialVersionUID = 1L; - - private static final String PROPERTY_CANNOT_BE_MODIFIED_MSG = "Property cannot be modified!"; - - /** - * The properties object which we are wrapping - */ - private Properties properties; - - /** - * Create the unmodifiable wrapper around the provided properties object - * - * @param properties - * The properties to be wrapped and protected from modification - */ - public UnmodifiableProperties(Properties properties) { - this.properties = properties; - } - - /** - * @see java.util.Hashtable#clear() - */ - @Override - public synchronized void clear() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#clone() - */ - // @sonar:off - @Override - public synchronized Object clone() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - // @sonar:on - - /** - * @see java.util.Hashtable#contains(java.lang.Object) - */ - @Override - public synchronized boolean contains(Object value) { - return properties.contains(value); - } - - /** - * @see java.util.Hashtable#containsKey(java.lang.Object) - */ - @Override - public synchronized boolean containsKey(Object key) { - return properties.containsKey(key); - } - - /** - * @see java.util.Hashtable#containsValue(java.lang.Object) - */ - @Override - public boolean containsValue(Object value) { - return properties.containsValue(value); - } - - /** - * @see java.util.Hashtable#elements() - */ - @Override - public synchronized Enumeration elements() { - return properties.elements(); - } - - /** - * @see java.util.Hashtable#entrySet() - */ - @Override - public Set> entrySet() { - return Collections.unmodifiableSet(properties.entrySet()); - } - - /** - * @see java.util.Hashtable#equals(java.lang.Object) - */ - @Override - public synchronized boolean equals(Object o) { - return properties.equals(o); - } - - /** - * @see java.util.Hashtable#get(java.lang.Object) - */ - @Override - public synchronized Object get(Object key) { - return properties.get(key); - } - - /** - * @see java.util.Properties#getProperty(java.lang.String) - */ - @Override - public String getProperty(String key) { - return properties.getProperty(key); - } - - /** - * @see java.util.Properties#getProperty(java.lang.String, java.lang.String) - */ - @Override - public String getProperty(String key, String defaultValue) { - return properties.getProperty(key, defaultValue); - } - - /** - * @see java.util.Hashtable#hashCode() - */ - @Override - public synchronized int hashCode() { - return properties.hashCode(); - } - - /** - * @see java.util.Hashtable#isEmpty() - */ - @Override - public synchronized boolean isEmpty() { - return properties.isEmpty(); - } - - /** - * @see java.util.Hashtable#keys() - */ - @Override - public synchronized Enumeration keys() { - return properties.keys(); - } - - /** - * @see java.util.Hashtable#keySet() - */ - @Override - public Set keySet() { - return Collections.unmodifiableSet(properties.keySet()); - } - - /** - * @see java.util.Properties#list(java.io.PrintStream) - */ - @Override - public void list(PrintStream out) { - properties.list(out); - } - - /** - * @see java.util.Properties#list(java.io.PrintWriter) - */ - @Override - public void list(PrintWriter out) { - properties.list(out); - } - - /** - * @see java.util.Properties#load(java.io.InputStream) - */ - @Override - public synchronized void load(InputStream inStream) throws IOException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#load(java.io.Reader) - */ - @Override - public synchronized void load(Reader reader) throws IOException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#loadFromXML(java.io.InputStream) - */ - @Override - public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#propertyNames() - */ - @Override - public Enumeration propertyNames() { - return properties.propertyNames(); - } - - /** - * @see java.util.Hashtable#put(java.lang.Object, java.lang.Object) - */ - @Override - public synchronized Object put(Object key, Object value) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#putAll(java.util.Map) - */ - @Override - public synchronized void putAll(Map t) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#rehash() - */ - @Override - protected void rehash() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#remove(java.lang.Object) - */ - @Override - public synchronized Object remove(Object key) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#save(java.io.OutputStream, java.lang.String) - */ - @Override - @Deprecated - public synchronized void save(OutputStream out, String comments) { - properties.save(out, comments); - } - - /** - * @see java.util.Properties#setProperty(java.lang.String, java.lang.String) - */ - @Override - public synchronized Object setProperty(String key, String value) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#size() - */ - @Override - public synchronized int size() { - return properties.size(); - } - - /** - * @see java.util.Properties#store(java.io.OutputStream, java.lang.String) - */ - @Override - public void store(OutputStream out, String comments) throws IOException { - properties.store(out, comments); - } - - /** - * @see java.util.Properties#store(java.io.Writer, java.lang.String) - */ - @Override - public void store(Writer writer, String comments) throws IOException { - properties.store(writer, comments); - } - - /** - * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String) - */ - @Override - public synchronized void storeToXML(OutputStream os, String comment) throws IOException { - properties.storeToXML(os, comment); - } - - /** - * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) - */ - @Override - public synchronized void storeToXML(OutputStream os, String comment, String encoding) throws IOException { - properties.storeToXML(os, comment, encoding); - } - - /** - * @see java.util.Properties#stringPropertyNames() - */ - @Override - public Set stringPropertyNames() { - return properties.stringPropertyNames(); - } - - /** - * @see java.util.Hashtable#toString() - */ - @Override - public synchronized String toString() { - return properties.toString(); - } - - /** - * @see java.util.Hashtable#values() - */ - @Override - public Collection values() { - return Collections.unmodifiableCollection(properties.values()); - } -} diff --git a/appc-common/src/main/java/org/openecomp/appc/util/httpClient.java b/appc-common/src/main/java/org/openecomp/appc/util/httpClient.java deleted file mode 100644 index edb27c6f6..000000000 --- a/appc-common/src/main/java/org/openecomp/appc/util/httpClient.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; - - -public class httpClient { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(httpClient.class); - - private static Configuration configuration = ConfigurationFactory.getConfiguration(); - - @SuppressWarnings("deprecation") - public static int postMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { - - logger.info("Sending POST request to " + path); - - HttpPost post; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - post = new HttpPost(serviceUrl.toExternalForm()); - post.setHeader("Content-Type", contentType); - - StringEntity entity = new StringEntity(payload); - entity.setContentType(contentType); - post.setEntity(new StringEntity(payload)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - logger.debug("Sending request " + post); - - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); - - int httpCode; - try { - HttpResponse response = client.execute(post); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - return httpCode; - } - - @SuppressWarnings("deprecation") - public static int putMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { - - logger.info("Sending PUT request to " + path); - - HttpPut put; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - put = new HttpPut(serviceUrl.toExternalForm()); - put.setHeader("Content-Type", contentType); - - StringEntity entity = new StringEntity(payload); - entity.setContentType(contentType); - put.setEntity(new StringEntity(payload)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - logger.debug("Sending request " + put); - - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); - - int httpCode; - try { - HttpResponse response = client.execute(put); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - return httpCode; - } - - @SuppressWarnings("deprecation") - public static String getMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { - - logger.info("Sending GET request to " + path); - - HttpGet get; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - get = new HttpGet(serviceUrl.toExternalForm()); - get.setHeader("Content-Type", contentType); - } catch (MalformedURLException e) { - throw new APPCException(e); - } - - logger.debug("Sending request " + get); - - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); - - int httpCode; - String result; - - try { - HttpResponse response = client.execute(get); - httpCode = response.getStatusLine().getStatusCode(); - result = (httpCode == HttpStatus.SC_OK) ? response.getEntity().toString() : null; - } catch (IOException e) { - throw new APPCException(e); - } - - return result; - } - - @SuppressWarnings("deprecation") - public static int deleteMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { - - logger.info("Sending DELETE request to " + path); - - HttpDelete delete; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - delete = new HttpDelete(serviceUrl.toExternalForm()); - delete.setHeader("Content-Type", contentType); - } catch (MalformedURLException e) { - throw new APPCException(e); - } - - logger.debug("Sending request " + delete); - - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); - - int httpCode; - String result; - - try { - HttpResponse response = client.execute(delete); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - - return httpCode; - } -} diff --git a/appc-common/src/main/resources/org/onap/appc/i18n/MessageResources.properties b/appc-common/src/main/resources/org/onap/appc/i18n/MessageResources.properties new file mode 100644 index 000000000..7ffb220a1 --- /dev/null +++ b/appc-common/src/main/resources/org/onap/appc/i18n/MessageResources.properties @@ -0,0 +1,1020 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# This property file contains all message definitions used by APPC +# +# Message resources are identified by a key, which is defined in the Msg enumeration. This key is +# assigned a value which consists of 4 parts separated by a pipe (|) symbol. These parts are: +# +# 1. The message identifier +# 2. The Message text to be formatted and issued to the user +# 3. The suggested resolution text, how to fix the problem. +# 4. The description text, what is the problem so the user can understand +# +CONFIGURATION_STARTED=APPC0001I|\ + ECOMP Application Controller (APP-C) initialization started at {0}|\ + No resolution is required, this is an informational message|\ + The APP-C component configuration has been started because the component is being \ + initialized or loaded for the first time, or a new instance of the component is \ + being created. This message indicates that the component is starting. + +CONFIGURATION_CLEARED=APPC0002I|\ + All prior configuration has been cleared|\ + No resolution is required, this is an informational message|\ + The APP-C component is being started or restarted and any prior configuration \ + (if present), is cleared. This is normal. + +LOADING_CONFIGURATION_OVERRIDES=APPC0003I|\ + Loading configuration properties from file "{0}"|\ + No resolution is required, this is an informational message|\ + This message indicates that the configuration of the APP-C component was located \ + and is being loaded from the specified file. + +LOADING_DEFAULTS=APPC0004I|\ + Configuration defaults loaded from resource file "{0}"|\ + No resolution is required, this is an informational message|\ + This is a normal indication that the default configuration settings were loaded \ + from the resource file. The APP-C components load a default configuration first \ + so that all configuration values have valid default settings. Any user configuation \ + that may be specified then overrides these defaults. + +NO_DEFAULTS_FOUND=APPC0005E|\ + No default property resource "{0}" was found!|\ + This is an internal error. Contact support.|\ + This is an internal error that indicates that the default resource property file \ + could not be located. This is likely a packaging error and is indicative of \ + a construction problem. Refer this to development or level 3 support for assistance. + +PROPERTY_VALUE=APPC0006I|\ + Property "{0}" ="{1}"|\ + No resolution is required, this is an informational message|\ + This message is issued to show the value of configuration properties and is used to \ + debug start up of the component. + +NO_OVERRIDE_PROPERTY_FILE_LOADED=APPC0007E|\ + No configuration file named [{0}] was found on the configuration search path [{1}]. \ + If a configuration file should have been loaded, check the file name and search \ + path specified. APPC will proceed using the default values and command-line \ + overrides (if any).|\ + If a configuration file was expected, verify the file name and that it exists on \ + the search path for the configuration properties. The search path defaults to \ + ${user.home},/opt/app/appc/etc,etc,../etc,/etc,. and can be overridden \ + by specification of the property org.onap.appc.bootstrap.path. The \ + property file name defaults to appc.properties and can also be \ + overridden by the org.onap.appc.bootstrap.file property.|\ + This message indicates that the bootstrap path was searched for the bootstrap \ + property file (a file that can be supplied to configure APPC) and that no file \ + with the specified name was found on any of the path elements of the path. + +SEARCHING_CONFIGURATION_OVERRIDES=APPC0008I|\ + Searching path "{0}" for configuration settings "{1}"|\ + No resolution is required|\ + This message indicates that the specified path is being examined for a configuration \ + file of the indicated name. The configuration file defaults to appc.properties \ + but can be overridden by specification of the org.onap.appc.bootstrap.file \ + property (using a command-line override, for example). This message is intended to \ + assist in the debugging and analysis of configuration issues where the indicated \ + file may not be processed or found. The path that is searched is a comma-delimited \ + list of directories and defaults to ${user.home},/opt/app/appc/etc,etc,../etc,/etc,. \ + but can also be overridden by specification of the org.onap.appc.bootstrap.path \ + property. + +LOADING_APPLICATION_OVERRIDES=APPC0009I|\ + Loading application-specific override properties|\ + No resolution required|\ + This message indicates that the APPC component was invoked as an embedded component \ + and that the caller has supplied an override property object. + +NO_APPLICATION_OVERRIDES=APPC0010I|\ + No application-specific override properties were provided!|\ + No resolution required|\ + This message indicates that the APPC component was invoked as an embedded component \ + and that the caller has supplied an override property object, but that object was \ + empty. + +MERGING_SYSTEM_PROPERTIES=APPC0011I|\ + Merging system properties into configuration|\ + No resolution is required|\ + This message indicates that the java virtual machine system properties are being \ + examined and merged into the APP-C component configuration. This allows for command \ + line specification of any APP-C configuration property as a standard java define \ + JVM option (ex: -Dproperty=value). + +SETTING_SPECIAL_PROPERTY=APPC0012I|\ + Setting property "{0}={1}" in system properties|\ + No resolution required.|\ + This message indicates that the specified property loaded from defaults, property \ + file overrides, application overrides, or command-line overrides is being placed \ + in the system (java virtual machine) properties object. Some libraries that may \ + be integrated with APP-C (for example, DME2 or AFT libraries) may only look for \ + their properties in the system properties object. This allows those components \ + to be configured from the APP-C configuration. + +LOADING_RESOURCE_BUNDLE=APPC0013I|\ + Loading resource bundle "{0}"|\ + No resolution required|\ + This message indicates that the specified resource bundle is being loaded. + +LOGGING_ALREADY_INITIALIZED=APPC0014W|\ + Logging has already been initialized, check the container logging definitions to ensure \ + they represent your desired logging configuration.|\ + If logging is configured incorrectly, move the definitions to the container or component \ + that first initialized logging. If they are ok, no resolution is required.|\ + This message indicates that the logging environment already exists and has been configured. + +SEARCHING_LOG_CONFIGURATION=APPC0015I|\ + Searching path "{0}" for log configuration file "{1}"|\ + No resolution is required|\ + This message indicates that the APP-C component configuration file specified a logging \ + configuration file and/or search path and the path is being searched. This is used to \ + assist in debugging the configuration process. + +LOADING_DEFAULT_LOG_CONFIGURATION=APPC0016I|\ + Loading default logging configuration from system resource file "{0}"|\ + No resolution is required|\ + A default logging configuration for the component is loaded from system resources to \ + ensure that a valid logging environment exists. This is a normal message, and will \ + be followed by APPC0019I if a user-specified logging configuration overrides the \ + defaults. + +NO_LOG_CONFIGURATION=APPC0017E|\ + No log configuration could be found or defaulted!|\ + A valid logging configuration cannot be found, and no default configuration resource \ + was loaded. This is likely a packaging issue and should be referred to development \ + or level 3 support for assistance.|\ + This is an internal error. + +UNSUPPORTED_LOGGING_FRAMEWORK=APPC0018E|\ + An unsupported logging framework is bound to SLF4J. Only Logback or Log4J are supported.|\ + This is a compatibility error with logging frameworks used in the application environment \ + and should be referred to development or level 3 support for assistance.|\ + This is an internal error. + +LOADING_LOG_CONFIGURATION=APPC0019I|\ + Loading logging configuration from file "{0}"|\ + No resolution is required|\ + The specified logging configuration is being loaded. + +UNKNOWN_PROVIDER=APPC0020E|\ + Provider {0} cannot be found or cannot be resolved to one of the known providers, [{1}].|\ + Specify the name of a valid provider. The IAAS adapter contains a set of providers \ + that are defined. Each of these providers is assigned a logical name. The call \ + to the IAAS adapter must specify the name of the provider that is desired. This \ + could be the result of an incorrect call, or the IAAS adapter configuration is \ + wrong.|\ + The APP-C IAAS adapter is being called to request a service on a specific provider, but \ + the name of the provider cannot be found in the list of defined providers. This may \ + be an error in the directed graph that contains the call to the IAAS adapter, or it \ + may be an error in the request, or the configuration of the IAAS adapter may need \ + to be updated. + +SERVER_STATE_CHANGE_TIMEOUT=APPC0021E|\ + Server name "{0}" with id "{1}" in tenant "{2}" and region "{3}" did not change state \ + within the alloted time. Current state is "{4}" and the desired state(s) are "{5}"|\ + This is likely a provider issue. If the provider is OpenStack, check the virtual \ + machine on the horizon dashboard. If the machine is in an invalid state, you may \ + need to contact Openstack support. The exact mechanisms for recovery of a machine \ + in an invalid state are varied and will be different from provider to provider.|\ + This message indicates that the IAAS adapter has performed some requested action \ + on the specified server (virtual machine) but the server did not enter a valid \ + state (running, stopped, etc) within the timeout period. The last state (current state) \ + is shown, as well as the state that was expected. The servers name, UUID, containing \ + tenant, and region are shown so that the correct provider can be examined. + +SERVER_DELETED=APPC0022E|\ + Server name "{0}" with id "{1}" in tenant "{2}" has a state of deleted and cannot be {3}.|\ + The specified server has been deleted on the provider. This is likely an incorrect \ + request. Make sure that you are specifying the correct server ID/name, provider, \ + and region. If the self-link URL is used, make sure that the correct server resource \ + is specified. If the machine was correct, recreate or rebuild the machine to make \ + it usable. Correct the request.|\ + This message indicates that the server specified was found to have been deleted in the \ + target provider and that the requested action cannot be performed. This may be caused \ + by several things:\ +
    \ +
  1. The UUID of the server is wrong and specifies a machine that no longer exists
  2. \ +
  3. The machine was deleted by a different process or request
  4. \ +
  5. The wrong provider was requested
  6. \ +
  7. The request was out-of-order
  8. \ +
+ +UNKNOWN_SERVER_STATE=APPC0023E|\ + Server name "{0}" with id "{1}" in tenant "{2}" has an unknown state of "{3}".|\ + Check the machine to determine the state of the machine. Correct that state to a valid \ + state if possible. This may also be caused by an internal error in the PAL (Provider \ + Abstraction Layer) used by the IAAS if a new state definition has been added to the \ + provider (such as a new version or the installation of an unknown or unsupported \ + extension). If the machine's state is valid, refer this error to development or \ + level 3 support for assistance.|\ + This message indicates that a request was made to the IAAS adapter to take some action \ + on the specified virtual machine, but the machine was found to be in a state that \ + prevents that action from being performed. + +COMPONENT_INITIALIZING=APPC0024I|\ + {0} component {1} is being initialized...|\ + No resolution needed|\ + The IAAS adapter is being initialized + +COMPONENT_INITIALIZED=APPC0025I|\ + {0} component {1} has completed initialization|\ + No resolution needed|\ + The IAAS adapter has been initialized + +COMPONENT_TERMINATING=APPC0026I|\ + {0} component {1} is terminating...|\ + No resolution needed|\ + The IAAS adapter is being terminated + +COMPONENT_TERMINATED=APPC0027I|\ + {0} component {1} has terminated|\ + No resolution needed|\ + The IAAS adapter has been terminated + +IAAS_ADAPTER_UNSUPPORTED_OPERATION=APPC0028E|\ + Operation {0} is not supported or implemented at this time.|\ + Change the request to a supported operation|\ + The IAAS adapter has been requested to perform some operation that it cannot \ + perform at this time. + +IAAS_ADAPTER_RPC_CALLED=APPC0029I|\ + Operation [{0}] called. Input document:\n{1}|\ + No resolution required|\ + The IAAS adapter operation indicated was called with the requested input \ + parameters. + +NO_SERVICE_FOUND=APPC0030E|\ + Unable to locate the [{0}] service in the OSGi container|\ + Ensure that the feature containing that service is installed and running|\ + This indicates that the required feature could not be located + +CONTEXT_PARAMETERS_DISPLAY=APPC0031I|\ + Dump of context parameters for module [{0}], RPC [{1}], and version [{2}]|\ + No resolution required|\ + The specified RPC is being called and the context properties are being \ + displayed. This is a debugging message and preceeds the display of \ + each context property. + +RESPONSE_PARAMETERS_DISPLAY=APPC0032I|\ + Response properties from execution of module [{0}], RPC [{1}], and version [{2}] are:|\ + No resolution required|\ + The service logic directed graph has been executed and returned the response properties. \ + This message preceeds the dump of the response properties. It is used for debugging \ + of service logic and execution problems. + +NULL_OR_INVALID_ARGUMENT=APPC0033E|\ + Service {0}:{1} was provided a null (empty) or invalid argument, [{2}] = [{3}]|\ + This is likely an internal error, refer to support for assistance|\ + The indicated service was called, but the specified parameter or argument was either \ + null or empty, or it was invalid. If it has a value, the value is shown. If the \ + value is null, the value is shown as 'null'. + +PROCESSING_REQUEST=APPC0034I|\ + Service {0}:{1} is processing service [{2}] with request id [{3}]|\ + No resolution required|\ + The indicated application and RPC is processing the specified service request. + +INVALID_SERVICE_REQUEST=APPC0035E|\ + Service {0}:{1} received request for service [{2}] but that service is invalid or unknown.|\ + Correct the service request, likely a directed graph issue|\ + The RPC was invoked to process a service request, but the service is not valid. + +REGISTERING_SERVICE=APPC0036I|\ + {0} registering service {1} using class {2}|\ + No resolution required|\ + The indicated application service is registering itself with the OSGi container using the \ + indicated java class name. + +UNREGISTERING_SERVICE=APPC0037I|\ + {0} unregistering service {1}|\ + No resolution required|\ + The application service is being unregistered from the OSGi container services list. + +LOADING_PROVIDER_DEFINITIONS=APPC0038I|\ + {0} IAAS Adapter initializing provider {1} as {2}|\ + No resolution is required|\ + The IAAS adapter is loading the definition of the specified provider from its \ + configuration file. + +RESTARTING_SERVER=APPC0039I|\ + {0} IAAS Adapter restart of server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the restart of a server. The \ + properties that govern the request are echoed immediately following this message. + +REBUILDING_SERVER=APPC0040I|\ + {0} IAAS Adapter rebuild of server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the rebuilding of a server. The \ + properties that govern the request are echoed immediately following this message. + +INVALID_SELF_LINK_URL=APPC0041E|\ + {0} IAAS Adapter cannot perform requested service, VM url [{1}] is invalid|\ + Correct the call to the adapter with a valid self-link URL|\ + The IAAS adapter has been called to perform some operation on a virtual machine \ + but the vm_id of the virtual machine is not valid. + +SERVER_FOUND=APPC0042I|\ + Located server {0} on tenant [{1}] and in state [{2}]|\ + No resolution required|\ + This message indicates that a service request was made to perform some action on the server \ + and the indicated server was located on the specified tenant.\ + + +STACK_FOUND=APPC0042I|\ + Located stack {0} on tenant [{1}] and in state [{2}]|\ + No resolution required|\ + This message indicates that a service request was made to perform some action on the server \ + and the indicated server was located on the specified tenant. + + + +SERVER_NOT_FOUND=APPC0043E|\ + No server found in provider with self-link URL [{0}]|\ + Correct the server URL|\ + The requested server, identified by its self link URL, could not be found in the provider + +SERVER_OPERATION_EXCEPTION=APPC0044E|\ + Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}]|\ + Contact support for assistance|\ + An exception was caught while trying to perform the indicated operation on the server. The \ + exception may yield more information about the cause of the error. This may be because \ + of access security, or the server is in an invalid state, or any number of reasons. This \ + message should be referred to support for assistance. + + +STACK_NOT_FOUND=APPC0043E|\ + No stack found in provider with self-link URL [{0}]|\ + Correct the server URL|\ + The requested stack, identified by its self link URL, could not be found in the provider + +STACK_OPERATION_EXCEPTION=APPC0044E|\ + Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}]|\ + Contact support for assistance|\ + An exception was caught while trying to perform the indicated operation on the stack. The \ + exception may yield more information about the cause of the error. This may be because \ + of access security, or the stack is in an invalid state, or any number of reasons. This \ + message should be referred to support for assistance. + +MISSING_REQUIRED_PROPERTIES=APPC0045E|\ + One or more properties for [{0}] are missing, null, or empty. They are:|\ + A request to execute the adapter indicated was made from a directed graph, but the properties \ + of the request that are required by the adapter are missing or do not have a value. Correct \ + the directed graph to supply the missing properties.|\ + The specified properties for the indicated adapter operation are invalid or missing. + +SERVER_ERROR_STATE=APPC0046E|\ + The server [{0}] (id={1}) in tenant {2} is in error state, {3} is not allowed|\ + Destroy and recreate the instance|\ + A request to restart or rebuild a server in an error state was received, but those operations \ + are not allowed on a server in this state. OpenStack only allows a deletion of a server \ + that is in the error state. + +IMAGE_NOT_FOUND=APPC0047E|\ + The image {0} could not be located for {1}.|\ + The image indicated could not be found. If the operation being requested is a rebuild of \ + a server, then there is no action that can be taken other than to destroy the server and \ + rebuild it using an image that exists.|\ + This is likely caused by an image being deleted after it was used to build a server. If the \ + request is for a server rebuild, then the image used to create the server was later deleted \ + and no longer exists. The server cannot be rebuilt, because the image doesnt exist. \ + The server must be deleted and reconstructed using a valid, existing image. + +STATE_CHANGE_TIMEOUT=APPC0048E|\ + Time out waiting for {0} with name {1} (and id {2}) to reach one of {3} states, current state is {4}|\ + Recover the resource in whatever means is appropriate|\ + The resource indicated (by name and id) was expected to change it's state (status) to one of the \ + indicated expected states within a specified timeout but the resource did not complete the \ + state change. It's current state is also shown. This can be caused by any number of factors \ + but is normally a problem or conflict within the IaaS provider (OpenStack). + +STATE_CHANGE_EXCEPTION=APPC0049E|\ + Exception {0} waiting for {1} with name {2} (and id {3}) to reach one of {4} states, current state is {5}\n\ + cause={6}|\ + Recover the resource in whatever means is appropriate|\ + The resource indicated (by name and id) was expected to change it's state (status) to one of the \ + indicated expected states within a specified timeout but the resource did not complete the \ + state change. It's current state is also shown. This can be caused by any number of factors \ + but is normally a problem or conflict within the IaaS provider (OpenStack). + +STOP_SERVER=APPC0050I|\ + Server {0} is being stopped...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be stopped. + +START_SERVER=APPC0051I|\ + Server {0} is being started...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be started. + +RESUME_SERVER=APPC0052I|\ + Server {0} is being resumed...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be resumed from a suspended state. + +UNPAUSE_SERVER=APPC0053I|\ + Server {0} is being unpaused...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be unpaused from a paused state. + +CONNECTION_FAILED_RETRY=APPC0054E|\ + Connection to provider {0} at identity {1} using tenant name {2} (id {3}) failed, reason={4}, \ + retrying in {5} seconds, attempt {6} of {7}.|\ + The connection to the provider could not be obtained for the indicated reason. The application \ + controller will retry the attempt to connect to the provider a maximum number of times. The \ + message contains the amount of time the system will wait to retry the connection, and the \ + current attempt and the maximum number of attempts.|\ + Correct the cause of the connection failure as indicated by the reason. + +CONNECTION_FAILED=APPC0055E|\ + Connection to provider {0} at service {1} failed after all retry attempts.|\ + The connection to the named provider at the indicated service URL cannot be opened. All \ + retries have been exhausted. The application controller is giving up on the connection and will \ + fail the request.|\ + Correct the cause of the connection failure as indicated by the reason(s) in previous APPC0054E \ + messages. + +STOPPING_SERVER=APPC0056I|\ + {0} IAAS Adapter stop server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the server to be stopped. The \ + properties that govern the request are echoed immediately following this message. + +REBUILD_SERVER_FAILED=APPC0057E|\ + Server {0} (id {1}) failed to rebuild, reason {2}|\ + The server rebuild failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to rebuild the indicated server but the rebuild request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +PARAMETER_IS_MISSING=APPC0058E|\ + Application {0} graph {1} response did not set the {2} parameter. This parameter is \ + required for synchronization with the controller. Absence of this parameter is assumed \ + to be a failure. Please correct the DG.|\ + The indicated directed graph was called from the application controller but when the \ + graph returned the indicated property was not defined in the return parameters. The \ + controller requires that property to be defined and set to a value that is used to \ + inform the controller of the outcome of operations in the graph. Failure to set \ + the required parameter is assumed to be a failure regardless if the graph actually \ + succeeded or not.|\ + Correct the DG to set the specified parameter to a value that is expected and understood \ + by the controller. + +PARAMETER_NOT_NUMERIC=APPC0059E|\ + Application {0} graph {1} did not set parameter {2} to a valid numeric value ({3}). \ + Please correct the DG.|\ + The indicated directed graph was called by the application controller and the graph \ + did set the specified property, however the property is not a valid numeric \ + value. The parameter is used to convey a numeric quantity and the controller \ + cannot convert the value specified to a number. |\ + Correct the DG. + +DG_FAILED_RESPONSE=APPC0060E|\ + Application {0} graph {1} completed with failure: error code = {2}, message = {3}|\ + The directed graph indicated was called by the application controller and when \ + the graph returned, an error code was set indicating that the graph failed. This \ + is a message that echoes the results of the graph, and shows the returned error \ + code and message.|\ + Correct the cause of the error. + +EXCEPTION_CALLING_DG=APPC0061E|\ + Application {0} received exception {1} attempting to call graph {2}, exception \ + message = {3}|\ + The application controller attempted to call the service logic interpreter (SLI) \ + to execute the indicated graph, but an exception was caught. The class of the \ + exception is shown, as is the message associated with the exception. An \ + abbreviated stack trace is also displayed to provide information as to the \ + state of the thread at the time of the exception.|\ + Correct the cause of the exception and rerun. + +GRAPH_NOT_FOUND=APPC0062E|\ + Application {0} was unable to locate graph {1}|\ + The application controller attempted to call the service logic interpreter (SLI) \ + to execute the specified graph but the graph does not exist in the SLI database.|\ + Correct the database and install the correct graph. + +DEBUG_GRAPH_RESPONSE_HEADER=APPC0063D|\ + Application {0} graph {1} responded with {2} properties|\ + This is a debugging message that is output immediately after the call to the \ + directed graph and before any processing is performed to determine the success \ + or failure of that call. The heading is output prior to dumping all the parameters \ + that were returned by the graph.|\ + No recovery action is required. + +DEBUG_GRAPH_RESPONSE_DETAIL=APPC0064D|\ + {0}:{1} - {2} = {3}|\ + This is a debugging message that is output immediately after the call to the \ + directed graph and before any processing is performed to determine the success \ + or failure of that call. This message is repeated for each parameter that \ + exists in the return context from the graph.|\ + No recovery action is required. + +INVALID_REQUIRED_PROPERTY=APPC0065E|\ + Application {0} request "{1}" was supplied a property "{2}" with the value "{3}" \ + that does not meet the required form(s):|\ + This message indicates that the specified requested operation was passed the \ + specific property named and the property value did not meet the expected \ + format requirements. For example, if the property is expected to be a \ + numeric quantity and it contains alphabetic characters, or if it is expected \ + to be a URL and it is not valid. The message also contains a list of one \ + or more regular expressions that were used to validate the input, and which \ + supply the syntax required for the property.|\ + Correct the property and retry. + +MIGRATING_SERVER=APPC066I|\ + {0} IAAS Adapter migrate of server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the migration of a server. The \ + properties that govern the request are echoed immediately following this message. + +EVACUATING_SERVER=APPC0067I|\ + {0} IAAS Adapter evacuate of server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the evacuation of a server. The \ + properties that govern the request are echoed immediately following this message. + +MIGRATE_SERVER_FAILED=APPC0068E|\ + Server {0} (id {1}) failed to migrate during {2} phase, reason {3}|\ + The server migration failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to migrate the indicated server but the migration request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +EVACUATE_SERVER_FAILED=APPC0069E|\ + Server {0} (id {1}) failed to evacuate, reason {2}|\ + The server evacuation failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to evacuate the indicated server but the evacuation request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +APPC_TOO_BUSY=APPC0080E|\ + APP-C instance is too busy|\ + The APP-C instance handles too many requests and cannot accept new ones as its internal \ + execution queue is full. The problem can appear when the APP-C instance gets more requests \ + than it can handle simultaneously.|\ + Check the server KPIs for possible performance issues (e.g. insufficient memory, \ + high network latency, slow responsiveness of southbound systems and so on) which can affect \ + the system throughput. + +VF_SERVER_BUSY=APPC0081E|\ + Concurrent access to server "{0}"|\ + APP-C currently executes a command on the specified server and cannot accept yet another request \ + for the same one.|\ + Try to resubmit the request at later time. + +VF_ILLEGAL_COMMAND=APPC0082E|\ + Server "{0}" does not support command "{1}" in the current state "{2}"|\ + APP-C cannot perform the requested command on the server in the current state as no state transition \ + is defined for that.|\ + Contact support for assistance. + +VF_UNDEFINED_STATE=APPC0083E|\ + Server "{0}" cannot handle command "{1}" because of its doubtful state|\ + The resource has undefined working state as result of abnormal termination of a previous command.|\ + Recover the resource in whatever means is appropriate. + +APPC_NO_RESOURCE_FOUND=APPC0084E|\ + No resource found with ID "{0}" in A&AI system.|\ + APP-C is unable to resolve the VF details given the instance ID.|\ + Check whether the resource has been deleted (terminated) before. + +APPC_EXPIRED_REQUEST=APPC0085E|\ + The request "{0}" for server "{1}" has exceeded its TTL limit of "{2}" seconds|\ + The received expired event won't be handled by APP-C instance. Normally the problem might be \ + related to asynchronous requests arriving to APP-C instance via DMaaP channel.|\ + Try to submit a new request if still relevant. + +APPC_WORKFLOW_NOT_FOUND=APPC0086E|\ + Workflow for vnfType = "{0}" and command = "{1}" not found.|\ + Unable to retrive Workflow related to mention VNF type and command.|\ + Check provided VNF and Command details are correct. + +APPC_INVALID_INPUT=APPC0087E|\ + Null vnfId and command provided|\ + Request contains Null vnfId and command|\ + Provided non-null VNF and Command details. + +APPC_AUDIT_MSG=APPC0090A|\ + Operation "{0}" for VNF type "{1}" from Source "{2}" with RequestID "{3}" \ + was started at "{4}" and ended at "{5}" with status code "{6}"|\ + Audit detailed msg|\ + Audit detailed msg. + +AAI_CONNECTION_FAILED=APPC0106E|\ + APP-C is unable to communicate with A&AI|\ + Connection to A&AI at service {0} failed after all retry attempts.|\ + The connection to the A&AI at the indicated service URL cannot be opened. \ + All retries have been exhausted. APP-C is giving up on the connection and will \ + reject the operation request.|\ + . + +AAI_UPDATE_FAILED=APPC0107E|\ + APP-C is unable to update COMPONENT_ID {0} to {1} for reason {2}|\ + The update at the end of the operation wasn't performed as a result of \ + A&AI communication failure or its internal error.|\ + . + +AAI_GET_DATA_FAILED=APPC0108E|\ + APP-C is unable to retrieve VF/VFC {0} data for Transaction ID {1} as a \ + result of A&AI communication failure or its internal error.|\ + Operation request will be rejected by APP-C|\ + . + +AAI_CONNECTION_FAILED_RETRY=APPC0105W|\ + A&AI at identity {0} using VNF_ID {1} failed, reason={2}, retrying in {3} seconds, attempt {4} of {5}.|\ + The connection to the A&AI could not be obtained for the indicated reason. APP-C will retry to connect \ + to the A&AI. The message contains the retry delay, the current attempt and the maximum number of attempts.|\ + Correct the cause of the connection failure as indicated by the reason. + +AAI_DELETE_FAILED=APPC0114E|\ + APP-C is unable to delete COMPONENT_ID {0} for reason {1}|\ + The deletion at the end of the operation wasn't performed as a result of \ + A&AI communication failure or its internal error.|\ + . + +AAI_QUERY_FAILED=APPC0115E|\ + Error Querying AAI with vnfID = {0}|\ + Querying AAI for the given vnf id returns failure to APPC|\ + . + +VNF_CONFIGURED=APPC0118I|\ + VNF {0} is configured|\ + No resolution is required, this is an informational message|\ + The VNF configuration has been completed. + +VNF_CONFIGURATION_STARTED=APPC0116I|\ + VNF {0} is being configured|\ + No resolution is required, this is an informational message|\ + The VNF configuration has been started + +VNF_CONFIGURATION_FAILED=APPC0119E|\ + VNF {0} configuration failed for reason {1}|\ + The configuration operation wasn't performed as a result of VNF communication failure or its internal error.|\ + . + +VNF_TEST_STARTED=APPC0120I|\ + VNF {0} is being tested|\ + No resolution is required, this is an informational message|\ + The VNF test has been started + +VNF_TESTED=APPC0121I|\ + VNF {0} was tested|\ + No resolution is required, this is an informational message|\ + The VNF test has been completed + +VNF_TEST_FAILED=APPC0122E|\ + VNF {0} test failed for reason {1}|\ + The test operation wasn't performed as a result of VNF communication failure or its internal error.|\ + . + +VNF_NOT_FOUND=APPC0123E|\ + VNF not found with vnf_id {0}|\ + The VNF wasn't found for the given vnf-id.|\ + . + +VNF_HEALTHCECK_FAILED=APPC0124E|\ + VNF {0} Healthcheck operation failed, reason {1}|\ + The health check operation wasn't performed as a result of VNF communication failure or its internal error.|\ + . + +VM_HEALTHCECK_FAILED=APPC0125E|\ + VM {0} Healthcheck operation failed, reason {1}|\ + The health check operation wasn't performed as a result of VNF communication failure or its internal error.|\ + . + +STOP_SERVER_FAILED=APPC0112E|\ + Server {0} (id {1}) failed to stop during {2} phase, reason {3}|\ + The server stop failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to stop the indicated server but the stop request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +TERMINATE_SERVER_FAILED=APPC0113E|\ + Server {0} (id {1}) failed to terminate during {2} phase, reason {3}|\ + The server termination failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to terminate the indicated server but the migration request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +TERMINATE_STACK_FAILED=APPC0113E|\ + Server {0} (id {1}) failed to terminate during {2} phase, reason {3}|\ + The server termination failed for the indicated reason. Correct the cause of the failure and \ + rerun, if applicable.|\ + The adapter has attempted to terminate the indicated server but the migration request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +TERMINATING_SERVER=APPC0114I|\ + {0} IAAS Adapter terminate server requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the server to be terminated. The \ + properties that govern the request are echoed immediately following this message. + + +TERMINATING_STACK=APPC0115I|\ + {0} IAAS Adapter terminate stack requested|\ + No resolution required|\ + A graph has invoked the IAAS adapter and has requested the server to be terminated. The \ + properties that govern the request are echoed immediately following this message. + +TERMINATE_SERVER=APPC0116I|\ + Server {0} is being terminated...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be terminated. + +TERMINATE_STACK=APPC0117I|\ + Stack {0} is being terminated...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be terminated. + +MIGRATE_COMPLETE=APPC0118I|\ + Migrate {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ + No resolution is required, this is an informational message|\ + APP-C Migrate Operation has completed. + +RESTART_COMPLETE=APPC0119I|\ + Restart {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ + No resolution is required, this is an informational message|\ + APP-C Restart Operation has completed. + +REBUILD_COMPLETE=APPC0120I|\ + Rebuild {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ + No resolution is required, this is an informational message|\ + APP-C Rebuild Operation has completed. + +CLOSE_CONTEXT_FAILED=APPC0121E|\ + Exception {0} was caught attempting to close provider context for {1}.|\ + Contact support for assistance|\ + An exception was caught while trying to close the provider context. The \ + exception may yield more information about the cause of the error. This may be because \ + of access security, or the server is in an invalid state, or any number of reasons. This \ + message should be referred to support for assistance. + +SNAPSHOTING_STACK=APPC0122I|\ + Stack {0} is being snapshoted...|\ + No resolution is required|\ + Stack snapshot. + +STACK_SNAPSHOTED==APPC0123I|\ + Stack {0} snapshoted, snapshot ID = [{1}].|\ + No resolution is required|\ + Stack snapshoted successfully. + + +RESTORING_STACK=APPC0124I|\ + Stack {0} is being restored to snapshot {1}...|\ + No resolution is required|\ + Stack restore. + +STACK_RESTORED=APPC0125I|\ + Stack {0} is restored to snapshot {1}.|\ + No resolution is required|\ + Stack restored successfully. + +MISSING_PARAMETER_IN_REQUEST=APPC0126E|\ + Parameter {0} is missing in svc request of {1}.|\ + Check DG node definition to pass missing parameter's value.|\ + Node definition in DG missing indicated parameter value or value is incorrect, \ + check the graph definition. + +CANNOT_ESTABLISH_CONNECTION=APPC0127E|\ + Cannot establish connection to server {0} port {1} with user {2}.|\ + Check server IP, port and user credentials.|\ + Wrong data sent in request's payload. + + +APPC_METRIC_MSG=APPC0128I|\ + Operation "{0}" for VNF type "{1}" from Source "{2}" with RequestID "{3}" on "{4}" with action "{5}" \ + ended in {6} ms with result "{7}"|\ + No resolution is required, this is an informational message|\ + This message indicates that the APPC logged some operation to metric + + SNAPSHOTING_SERVER=APPC0129I|\ +{0} IAAS Adapter create snapshot of server requested|\ +No resolution is required, this is an informational message|\ +This message indicates that a IAAS Adapter create snapshot of server was requested. + +INPUT_PAYLOAD_PARSING_FAILED = APPC0130E|\ + Failed to parsing the input payload: {0}|\ + Please provide correct input string for parsing.|\ + . + +APPC_EXCEPTION = APPC0132E|\ + Error occurred for VNF type : {0}, reason {1}|\ + Runtime exception thrown by APPC.|\ + . + +SSH_DATA_EXCEPTION = APPC0133E|\ + SSH Data Exception occurred, reason {0}|\ + SSH Data exception occurred.|\ + . + +JSON_PROCESSING_EXCEPTION = APPC0134E|\ + Json processing exception occurred, reason {0}|\ + Json processing Exception|\ + . + +SUCCESS_EVENT_MESSAGE = APPC0136I|\ + Operation {0} succeed for {1}|\ + Success message.|\ + . +DEPENDENCY_MODEL_NOT_FOUND = APPC0137E|\ + Dependency model not found for VNF type {0}, reason {1}|\ + Please provide dependency model|\ + . + +INVALID_DEPENDENCY_MODEL = APPC0138E|\ + Invalid Dependency model for VNF Type {0}, reason {1}|\ + Invalid dependency model found |\ + . + + +FAILURE_RETRIEVE_VNFC_DG = APPC0139E|\ + Failed to retrieve DG for VNFC Type: {0}|\ + Failed to retrieve VNFC DG |\ + . + + +SERVER_NETWORK_ERROR=APPC0140E|\ + Server {0} either has a port {1} that is NOT online, or the status of the network to which the port is connected to is not ACTIVE|\ + Please ensure they are UP and running before requested operation|\ + It is critical that the VM Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ + the requested operation on it. + . + +REBUILD_SERVER=APPC0140I|\ + Server {0} is being rebuilt...|\ + No recovery required|\ + The processing being performed by APPC requires that the indicated server be rebuilt. + +HYPERVISOR_DOWN_ERROR=APPC0141E|\ + Hypervisor {0} for the Server {1} is either NOT ENABLED, or its status is DOWN or UNKNOWN|\ + Please ensure the Hypervisor is UP and running before proceeding with the requested operation|\ + It is critical that the Hypervisor that manages the Virtual Machine for the Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ + the requested operation on it. + . + +HYPERVISOR_STATUS_UKNOWN=APPC0158E|\ + Unable to determine the status of the Hypervisor for the Server {0} |\ + Please ensure the userid has privileges enabled to query for the Hypervisor status. |\ + If you wish to proceed with the requested operation, either obtain the privileges from the Cloud provider, or skip the Hypervisor check and retry the request. + . + +HYPERVISOR_NETWORK_ERROR=APPC0142E|\ + Hypervisor {0} for the Server {1} is NOT Reachable by APPC for initiating the requested operation|\ + Please ensure the Hypervisor is connected to the network before proceeding with the requested operation|\ + It is critical that the Hypervisor that manages the Virtual Machine for the Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ + the requested operation on it. + +EVACUATE_SERVER_REBUILD_FAILED=APPC0143E|\ + Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3}|\ + The server rebuild after evacuation failed for the indicated reason. Correct the cause of the failure and \ + run a rebuild, if applicable.|\ + The adapter has attempted to rebuild after evacuating the indicated server but the rebuild request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +RESTART_APPLICATION=APPC0144I|\ + Application on server {0} is being restarted...|\ + No recovery required|\ + The processing being performed by APPC requires that the application on the indicated server be restarted. + +START_APPLICATION=APPC0145I|\ + Application on server {0} is being started...|\ + No recovery required|\ + The processing being performed by APPC requires that the application on the indicated server be started. + +APPLICATION_RESTART_FAILED=APPC0146E|\ + Restart application operation failed on server : {0}, reason {1}|\ + Restart application operation failure.|\ + Correct the cause of the failure as indicated by the reason. + +APPLICATION_START_FAILED=APPC0147E|\ + Start application operation failed on server : {0}, reason {1}|\ + Start application operation failure.|\ + Correct the cause of the failure as indicated by the reason. + +LOOKING_SERVER_UP=APPC0148I|\ +{0} IAAS Adapter looking up for the server requested|\ +No resolution is required, this is an informational message|\ +This message indicates that a IAAS Adapter lookup of server was requested. + +EVACUATE_SERVER_REBUILD_FAILED=APPC0149E|\ + Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3}|\ + The server rebuild after evacuation failed for the indicated reason. Correct the cause of the failure and \ + run a rebuild, if applicable.|\ + The adapter has attempted to rebuild after evacuating the indicated server but the rebuild request has \ + been failed by the provider for some reason. The reason returned by the provider is \ + included in the message. + +APPLICATION_STOP_FAILED=APPC0150E|\ + Stop application operation failed on server : {0}, reason {1}|\ + Stop application operation failure.|\ + Correct the cause of the failure as indicated by the reason. + +STOP_APPLICATION=APPC0151I|\ + Application on server {0} is being stopped...|\ + No recovery required|\ + The processing being performed by APPC requires that the application on the indicated server be stopped. + +LCM_OPERATIONS_DISABLED=APPC0152E|\ + APPC LCM operations have been administratively disabled|\ + No recovery required|\ + This is a indication that the APPC LCM operations are disabled. + +OAM_OPERATION_EXCEPTION=APPC0153E|\ + Application {0} received exception {1} while attempting to execute oam operation {2}, exception message = {3}|\ + The application controller attempted to perform an OAM operation \ + but an exception was caught. The class of the \ + exception is shown, as is the message associated with the exception. An \ + abbreviated stack trace is also displayed to provide information as to the \ + state of the thread at the time of the exception.|\ + Correct the cause of the exception and rerun. + +OAM_OPERATION_ENTERING_MAINTENANCE_MODE=APPC0154W|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC will no longer accept new LCM requests. Previously accepted LCM requests will be allowed to complete. + +OAM_OPERATION_MAINTENANCE_MODE=APPC0155W|\ + Application {0} is in {1}|\ + No recovery required|\ + The APPC is not accepting new LCM requests and all previously accepted LCM requests have completed. + +OAM_OPERATION_STARTING=APPC0156I|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC has initiated its startup procedure. Its internal components are coming online. Once completed it will start accepting LCM requests. + +OAM_OPERATION_STARTED=APPC0157I|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC will now accept new LCM requests for processing. + +INVALID_STATE_TRANSITION=APPC0158E|\ + A {1} API is not allowed when {0} in the {2} state|\ + No recovery required|\ + The Operation requested cannot be performed as per the current state of APPC. + +OAM_OPERATION_STOPPING=APPC0159W|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC has initiated its stop procedure. Its internal LCM bundles are stopping. + +OAM_OPERATION_STOPPED=APPC0160W|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC LCM bundles have now stopped. + +REQUEST_HANDLER_UNAVAILABLE=APPC0161E|\ + Application {0} was unable to find the Request Handler service |\ + The application controller attempted to get a handle on Request Handler service \ + but was unable to locate it in the OSGi Service Registry.|\ + Verify if the Request Handler bundle is running. + +OAM_OPERATION_RESTARTING=APPC0162W|\ + Application {0} is {1}|\ + No recovery required|\ + The APPC has initiated its restart procedure. Its internal LCM bundles are stopping and will then start again. + +OAM_OPERATION_RESTARTED=APPC0163W|\ + Application {0} is {1} for restart|\ + No recovery required|\ + The APPC LCM bundles have been restared (stopped and then started). + +OAM_OPERATION_INVALID_INPUT=APPC0162E|\ + {0}|\ + No recovery required|\ + Fix the input parameter and retry. + +IAAS_UNSUPPORTED_IDENTITY_SERVICE=APPC0163E|\ + Unsupported identity service version, unable to retrieve ServiceCatalog for identity service {0}|\ + Verify the identity url provided is correct. Currently supported version of the OpenStack identity servicer\ + are v2 and v3. If a support for a new version in required contact development.|\ + This message indicates that a request was made to connect to an unsupported version of \ + identity service. \ No newline at end of file diff --git a/appc-common/src/main/resources/org/onap/appc/i18n/auth.properties b/appc-common/src/main/resources/org/onap/appc/i18n/auth.properties new file mode 100644 index 000000000..d64e688e5 --- /dev/null +++ b/appc-common/src/main/resources/org/onap/appc/i18n/auth.properties @@ -0,0 +1,26 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +username=admin +password=admin diff --git a/appc-common/src/main/resources/org/onap/appc/org.ops4j.pax.logging.cfg b/appc-common/src/main/resources/org/onap/appc/org.ops4j.pax.logging.cfg new file mode 100644 index 000000000..a3a3f5837 --- /dev/null +++ b/appc-common/src/main/resources/org/onap/appc/org.ops4j.pax.logging.cfg @@ -0,0 +1,149 @@ + ################################################################################ + # + # Licensed to the Apache Software Foundation (ASF) under one or more + # contributor license agreements. See the NOTICE file distributed with + # this work for additional information regarding copyright ownership. + # The ASF licenses this file to You under the Apache License, Version 2.0 + # (the "License"); you may not use this file except in compliance with + # the License. You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITH WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # + ################################################################################ + + # Root + #log4j.rootLogger=TRACE, osgi:VmLogAppender + log4j.rootLogger=TRACE, out, sift, osgi:* + log4j.throwableRenderer=org.apache.log4j.OsgiThrowableRenderer + + # CONSOLE appender not used by default + log4j.appender.stdout=org.apache.log4j.ConsoleAppender + log4j.appender.stdout.layout=org.apache.log4j.PatternLayout + log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %X{bundle.id} - %X{bundle.name} - %X{bundle.version} | %m%n + + # Async appender forwarding to file appender + log4j.appender.async=org.apache.log4j.AsyncAppender + log4j.appender.async.appenders=out + + # Karaf appenders + # File appender + log4j.appender.out=org.apache.log4j.RollingFileAppender + log4j.appender.out.layout=org.apache.log4j.PatternLayout + log4j.appender.out.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %X{bundle.id} - %X{bundle.name} - %X{bundle.version} | %m%n + log4j.appender.out.file=${karaf.data}/log/karaf.log + log4j.appender.out.append=true + log4j.appender.out.maxFileSize=10MB + log4j.appender.out.maxBackupIndex=100 + + + # Sift appender + log4j.appender.sift=org.apache.log4j.sift.MDCSiftingAppender + log4j.appender.sift.key=bundle.name + log4j.appender.sift.default=karaf + log4j.appender.sift.appender=org.apache.log4j.RollingFileAppender + log4j.appender.sift.appender.layout=org.apache.log4j.PatternLayout + log4j.appender.sift.appender.layout.ConversionPattern=%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%-5.5p|%X{AlertSeverity}|%X{ServerFQDN}|%X{ServerIPAddress}|[%c{3}]|%m%n + log4j.appender.sift.appender.file=${karaf.data}/log/eelf/karaf.log + log4j.appender.sift.appender.append=true + + log4j.category.org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPusherImpl=DEBUG + log4j.category.org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator=DEBUG + + + #ECOMP Debug appender + log4j.appender.debug=org.apache.log4j.RollingFileAppender + log4j.appender.debug.key=bundle.name + log4j.appender.debug.default=karaf + + log4j.appender.debug.appName=EELFDebug + log4j.appender.debug.layout=org.apache.log4j.PatternLayout + log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd'T'hh:mm:ss.SSSXXX}|%X{RequestId}|%m%n + #log4j.appender.debug.filter.f1=org.apache.log4j.varia.LevelRangeFilter + #log4j.appender.debug.filter.f1.LevelMax=WARN + #log4j.appender.debug.filter.f1.LevelMin=TRACE + + + log4j.appender.debug.file=${karaf.data}/log/APPC/appc-debug.log + log4j.appender.debug.append=true + log4j.appender.debug.maxFileSize=100MB + log4j.appender.debug.maxBackupIndex=10 + + + #Error appender + log4j.appender.error=org.apache.log4j.RollingFileAppender + log4j.appender.error.appName=EELFError + log4j.appender.error.File=${karaf.data}/log/APPC/appc-error.log + log4j.appender.error.Threshold=ERROR + log4j.appender.error.MaxBackupIndex=1 + log4j.appender.error.MaxFileSize=100MB + log4j.appender.error.layout=org.apache.log4j.PatternLayout + log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd'T'hh:mm:ss.SSSXXX}|%X{RequestId}|%t|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%-5.5p|%X{ErrorCode}|%X{ErrorDescription}|%m%n + + #Metrics appender + log4j.appender.metric=org.apache.log4j.RollingFileAppender + log4j.appender.metric.appName=EELFMetrics + log4j.appender.metric.File=${karaf.data}/log/APPC/appc-metric.log + log4j.appender.metric.MaxBackupIndex=1 + log4j.appender.metric.MaxFileSize=100MB + log4j.appender.metric.layout=org.apache.log4j.PatternLayout + log4j.appender.metric.layout.ConversionPattern=%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%-5.5p|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%m%n + + #Audit appender + log4j.appender.audit=org.apache.log4j.RollingFileAppender + log4j.appender.audit.appName=EELFAudit + log4j.appender.audit.File=${karaf.data}/log/APPC/appc-audit.log + log4j.appender.audit.MaxBackupIndex=1 + log4j.appender.audit.MaxFileSize=100MB + log4j.appender.audit.layout=org.apache.log4j.PatternLayout + log4j.appender.audit.layout.ConversionPattern=%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%-5.5p|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%m%n + + #Loggers + + #Routing of all messages from root logger + log4j.logger.org.openecomp=TRACE, debug, error + #Store to the same log file messages from upper level appender or not + log4j.additivity.org.openecomp=false + + #org.openecomp logger + log4j.logger.org.openecomp=TRACE, debug, error + log4j.additivity.org.openecomp=false + + #EELFManager loggers + #EELF parent logger + log4j.logger.com.att.eelf=TRACE, debug + log4j.additivity.com.att.eelf=false + + #Audit logger routing + log4j.logger.com.att.eelf.audit=DEBUG, audit + log4j.additivity.com.att.eelf.audit=false + + #Metric logger routing + log4j.logger.com.att.eelf.metrics=DEBUG, metric + log4j.additivity.com.att.eelf.metrics=false + + #Performance logger routing + log4j.logger.com.att.eelf.perf=DEBUG, metric + log4j.additivity.com.att.eelf.perf=false + + #Server logger routing + log4j.logger.com.att.eelf.server=DEBUG, debug + log4j.additivity.com.att.eelf.server=false + + #Policy logger routing + log4j.logger.com.att.eelf.policy=DEBUG, debug + log4j.additivity.com.att.eelf.policy=false + + #Error logger routing + log4j.logger.com.att.eelf.error=DEBUG, error + log4j.additivity.com.att.eelf.error=false + + #Debug logger routing + log4j.logger.com.att.eelf.debug=DEBUG, debug + log4j.additivity.com.att.eelf.debug=false + diff --git a/appc-common/src/main/resources/org/openecomp/appc/i18n/MessageResources.properties b/appc-common/src/main/resources/org/openecomp/appc/i18n/MessageResources.properties deleted file mode 100644 index 7ffb220a1..000000000 --- a/appc-common/src/main/resources/org/openecomp/appc/i18n/MessageResources.properties +++ /dev/null @@ -1,1020 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# This property file contains all message definitions used by APPC -# -# Message resources are identified by a key, which is defined in the Msg enumeration. This key is -# assigned a value which consists of 4 parts separated by a pipe (|) symbol. These parts are: -# -# 1. The message identifier -# 2. The Message text to be formatted and issued to the user -# 3. The suggested resolution text, how to fix the problem. -# 4. The description text, what is the problem so the user can understand -# -CONFIGURATION_STARTED=APPC0001I|\ - ECOMP Application Controller (APP-C) initialization started at {0}|\ - No resolution is required, this is an informational message|\ - The APP-C component configuration has been started because the component is being \ - initialized or loaded for the first time, or a new instance of the component is \ - being created. This message indicates that the component is starting. - -CONFIGURATION_CLEARED=APPC0002I|\ - All prior configuration has been cleared|\ - No resolution is required, this is an informational message|\ - The APP-C component is being started or restarted and any prior configuration \ - (if present), is cleared. This is normal. - -LOADING_CONFIGURATION_OVERRIDES=APPC0003I|\ - Loading configuration properties from file "{0}"|\ - No resolution is required, this is an informational message|\ - This message indicates that the configuration of the APP-C component was located \ - and is being loaded from the specified file. - -LOADING_DEFAULTS=APPC0004I|\ - Configuration defaults loaded from resource file "{0}"|\ - No resolution is required, this is an informational message|\ - This is a normal indication that the default configuration settings were loaded \ - from the resource file. The APP-C components load a default configuration first \ - so that all configuration values have valid default settings. Any user configuation \ - that may be specified then overrides these defaults. - -NO_DEFAULTS_FOUND=APPC0005E|\ - No default property resource "{0}" was found!|\ - This is an internal error. Contact support.|\ - This is an internal error that indicates that the default resource property file \ - could not be located. This is likely a packaging error and is indicative of \ - a construction problem. Refer this to development or level 3 support for assistance. - -PROPERTY_VALUE=APPC0006I|\ - Property "{0}" ="{1}"|\ - No resolution is required, this is an informational message|\ - This message is issued to show the value of configuration properties and is used to \ - debug start up of the component. - -NO_OVERRIDE_PROPERTY_FILE_LOADED=APPC0007E|\ - No configuration file named [{0}] was found on the configuration search path [{1}]. \ - If a configuration file should have been loaded, check the file name and search \ - path specified. APPC will proceed using the default values and command-line \ - overrides (if any).|\ - If a configuration file was expected, verify the file name and that it exists on \ - the search path for the configuration properties. The search path defaults to \ - ${user.home},/opt/app/appc/etc,etc,../etc,/etc,. and can be overridden \ - by specification of the property org.onap.appc.bootstrap.path. The \ - property file name defaults to appc.properties and can also be \ - overridden by the org.onap.appc.bootstrap.file property.|\ - This message indicates that the bootstrap path was searched for the bootstrap \ - property file (a file that can be supplied to configure APPC) and that no file \ - with the specified name was found on any of the path elements of the path. - -SEARCHING_CONFIGURATION_OVERRIDES=APPC0008I|\ - Searching path "{0}" for configuration settings "{1}"|\ - No resolution is required|\ - This message indicates that the specified path is being examined for a configuration \ - file of the indicated name. The configuration file defaults to appc.properties \ - but can be overridden by specification of the org.onap.appc.bootstrap.file \ - property (using a command-line override, for example). This message is intended to \ - assist in the debugging and analysis of configuration issues where the indicated \ - file may not be processed or found. The path that is searched is a comma-delimited \ - list of directories and defaults to ${user.home},/opt/app/appc/etc,etc,../etc,/etc,. \ - but can also be overridden by specification of the org.onap.appc.bootstrap.path \ - property. - -LOADING_APPLICATION_OVERRIDES=APPC0009I|\ - Loading application-specific override properties|\ - No resolution required|\ - This message indicates that the APPC component was invoked as an embedded component \ - and that the caller has supplied an override property object. - -NO_APPLICATION_OVERRIDES=APPC0010I|\ - No application-specific override properties were provided!|\ - No resolution required|\ - This message indicates that the APPC component was invoked as an embedded component \ - and that the caller has supplied an override property object, but that object was \ - empty. - -MERGING_SYSTEM_PROPERTIES=APPC0011I|\ - Merging system properties into configuration|\ - No resolution is required|\ - This message indicates that the java virtual machine system properties are being \ - examined and merged into the APP-C component configuration. This allows for command \ - line specification of any APP-C configuration property as a standard java define \ - JVM option (ex: -Dproperty=value). - -SETTING_SPECIAL_PROPERTY=APPC0012I|\ - Setting property "{0}={1}" in system properties|\ - No resolution required.|\ - This message indicates that the specified property loaded from defaults, property \ - file overrides, application overrides, or command-line overrides is being placed \ - in the system (java virtual machine) properties object. Some libraries that may \ - be integrated with APP-C (for example, DME2 or AFT libraries) may only look for \ - their properties in the system properties object. This allows those components \ - to be configured from the APP-C configuration. - -LOADING_RESOURCE_BUNDLE=APPC0013I|\ - Loading resource bundle "{0}"|\ - No resolution required|\ - This message indicates that the specified resource bundle is being loaded. - -LOGGING_ALREADY_INITIALIZED=APPC0014W|\ - Logging has already been initialized, check the container logging definitions to ensure \ - they represent your desired logging configuration.|\ - If logging is configured incorrectly, move the definitions to the container or component \ - that first initialized logging. If they are ok, no resolution is required.|\ - This message indicates that the logging environment already exists and has been configured. - -SEARCHING_LOG_CONFIGURATION=APPC0015I|\ - Searching path "{0}" for log configuration file "{1}"|\ - No resolution is required|\ - This message indicates that the APP-C component configuration file specified a logging \ - configuration file and/or search path and the path is being searched. This is used to \ - assist in debugging the configuration process. - -LOADING_DEFAULT_LOG_CONFIGURATION=APPC0016I|\ - Loading default logging configuration from system resource file "{0}"|\ - No resolution is required|\ - A default logging configuration for the component is loaded from system resources to \ - ensure that a valid logging environment exists. This is a normal message, and will \ - be followed by APPC0019I if a user-specified logging configuration overrides the \ - defaults. - -NO_LOG_CONFIGURATION=APPC0017E|\ - No log configuration could be found or defaulted!|\ - A valid logging configuration cannot be found, and no default configuration resource \ - was loaded. This is likely a packaging issue and should be referred to development \ - or level 3 support for assistance.|\ - This is an internal error. - -UNSUPPORTED_LOGGING_FRAMEWORK=APPC0018E|\ - An unsupported logging framework is bound to SLF4J. Only Logback or Log4J are supported.|\ - This is a compatibility error with logging frameworks used in the application environment \ - and should be referred to development or level 3 support for assistance.|\ - This is an internal error. - -LOADING_LOG_CONFIGURATION=APPC0019I|\ - Loading logging configuration from file "{0}"|\ - No resolution is required|\ - The specified logging configuration is being loaded. - -UNKNOWN_PROVIDER=APPC0020E|\ - Provider {0} cannot be found or cannot be resolved to one of the known providers, [{1}].|\ - Specify the name of a valid provider. The IAAS adapter contains a set of providers \ - that are defined. Each of these providers is assigned a logical name. The call \ - to the IAAS adapter must specify the name of the provider that is desired. This \ - could be the result of an incorrect call, or the IAAS adapter configuration is \ - wrong.|\ - The APP-C IAAS adapter is being called to request a service on a specific provider, but \ - the name of the provider cannot be found in the list of defined providers. This may \ - be an error in the directed graph that contains the call to the IAAS adapter, or it \ - may be an error in the request, or the configuration of the IAAS adapter may need \ - to be updated. - -SERVER_STATE_CHANGE_TIMEOUT=APPC0021E|\ - Server name "{0}" with id "{1}" in tenant "{2}" and region "{3}" did not change state \ - within the alloted time. Current state is "{4}" and the desired state(s) are "{5}"|\ - This is likely a provider issue. If the provider is OpenStack, check the virtual \ - machine on the horizon dashboard. If the machine is in an invalid state, you may \ - need to contact Openstack support. The exact mechanisms for recovery of a machine \ - in an invalid state are varied and will be different from provider to provider.|\ - This message indicates that the IAAS adapter has performed some requested action \ - on the specified server (virtual machine) but the server did not enter a valid \ - state (running, stopped, etc) within the timeout period. The last state (current state) \ - is shown, as well as the state that was expected. The servers name, UUID, containing \ - tenant, and region are shown so that the correct provider can be examined. - -SERVER_DELETED=APPC0022E|\ - Server name "{0}" with id "{1}" in tenant "{2}" has a state of deleted and cannot be {3}.|\ - The specified server has been deleted on the provider. This is likely an incorrect \ - request. Make sure that you are specifying the correct server ID/name, provider, \ - and region. If the self-link URL is used, make sure that the correct server resource \ - is specified. If the machine was correct, recreate or rebuild the machine to make \ - it usable. Correct the request.|\ - This message indicates that the server specified was found to have been deleted in the \ - target provider and that the requested action cannot be performed. This may be caused \ - by several things:\ -
    \ -
  1. The UUID of the server is wrong and specifies a machine that no longer exists
  2. \ -
  3. The machine was deleted by a different process or request
  4. \ -
  5. The wrong provider was requested
  6. \ -
  7. The request was out-of-order
  8. \ -
- -UNKNOWN_SERVER_STATE=APPC0023E|\ - Server name "{0}" with id "{1}" in tenant "{2}" has an unknown state of "{3}".|\ - Check the machine to determine the state of the machine. Correct that state to a valid \ - state if possible. This may also be caused by an internal error in the PAL (Provider \ - Abstraction Layer) used by the IAAS if a new state definition has been added to the \ - provider (such as a new version or the installation of an unknown or unsupported \ - extension). If the machine's state is valid, refer this error to development or \ - level 3 support for assistance.|\ - This message indicates that a request was made to the IAAS adapter to take some action \ - on the specified virtual machine, but the machine was found to be in a state that \ - prevents that action from being performed. - -COMPONENT_INITIALIZING=APPC0024I|\ - {0} component {1} is being initialized...|\ - No resolution needed|\ - The IAAS adapter is being initialized - -COMPONENT_INITIALIZED=APPC0025I|\ - {0} component {1} has completed initialization|\ - No resolution needed|\ - The IAAS adapter has been initialized - -COMPONENT_TERMINATING=APPC0026I|\ - {0} component {1} is terminating...|\ - No resolution needed|\ - The IAAS adapter is being terminated - -COMPONENT_TERMINATED=APPC0027I|\ - {0} component {1} has terminated|\ - No resolution needed|\ - The IAAS adapter has been terminated - -IAAS_ADAPTER_UNSUPPORTED_OPERATION=APPC0028E|\ - Operation {0} is not supported or implemented at this time.|\ - Change the request to a supported operation|\ - The IAAS adapter has been requested to perform some operation that it cannot \ - perform at this time. - -IAAS_ADAPTER_RPC_CALLED=APPC0029I|\ - Operation [{0}] called. Input document:\n{1}|\ - No resolution required|\ - The IAAS adapter operation indicated was called with the requested input \ - parameters. - -NO_SERVICE_FOUND=APPC0030E|\ - Unable to locate the [{0}] service in the OSGi container|\ - Ensure that the feature containing that service is installed and running|\ - This indicates that the required feature could not be located - -CONTEXT_PARAMETERS_DISPLAY=APPC0031I|\ - Dump of context parameters for module [{0}], RPC [{1}], and version [{2}]|\ - No resolution required|\ - The specified RPC is being called and the context properties are being \ - displayed. This is a debugging message and preceeds the display of \ - each context property. - -RESPONSE_PARAMETERS_DISPLAY=APPC0032I|\ - Response properties from execution of module [{0}], RPC [{1}], and version [{2}] are:|\ - No resolution required|\ - The service logic directed graph has been executed and returned the response properties. \ - This message preceeds the dump of the response properties. It is used for debugging \ - of service logic and execution problems. - -NULL_OR_INVALID_ARGUMENT=APPC0033E|\ - Service {0}:{1} was provided a null (empty) or invalid argument, [{2}] = [{3}]|\ - This is likely an internal error, refer to support for assistance|\ - The indicated service was called, but the specified parameter or argument was either \ - null or empty, or it was invalid. If it has a value, the value is shown. If the \ - value is null, the value is shown as 'null'. - -PROCESSING_REQUEST=APPC0034I|\ - Service {0}:{1} is processing service [{2}] with request id [{3}]|\ - No resolution required|\ - The indicated application and RPC is processing the specified service request. - -INVALID_SERVICE_REQUEST=APPC0035E|\ - Service {0}:{1} received request for service [{2}] but that service is invalid or unknown.|\ - Correct the service request, likely a directed graph issue|\ - The RPC was invoked to process a service request, but the service is not valid. - -REGISTERING_SERVICE=APPC0036I|\ - {0} registering service {1} using class {2}|\ - No resolution required|\ - The indicated application service is registering itself with the OSGi container using the \ - indicated java class name. - -UNREGISTERING_SERVICE=APPC0037I|\ - {0} unregistering service {1}|\ - No resolution required|\ - The application service is being unregistered from the OSGi container services list. - -LOADING_PROVIDER_DEFINITIONS=APPC0038I|\ - {0} IAAS Adapter initializing provider {1} as {2}|\ - No resolution is required|\ - The IAAS adapter is loading the definition of the specified provider from its \ - configuration file. - -RESTARTING_SERVER=APPC0039I|\ - {0} IAAS Adapter restart of server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the restart of a server. The \ - properties that govern the request are echoed immediately following this message. - -REBUILDING_SERVER=APPC0040I|\ - {0} IAAS Adapter rebuild of server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the rebuilding of a server. The \ - properties that govern the request are echoed immediately following this message. - -INVALID_SELF_LINK_URL=APPC0041E|\ - {0} IAAS Adapter cannot perform requested service, VM url [{1}] is invalid|\ - Correct the call to the adapter with a valid self-link URL|\ - The IAAS adapter has been called to perform some operation on a virtual machine \ - but the vm_id of the virtual machine is not valid. - -SERVER_FOUND=APPC0042I|\ - Located server {0} on tenant [{1}] and in state [{2}]|\ - No resolution required|\ - This message indicates that a service request was made to perform some action on the server \ - and the indicated server was located on the specified tenant.\ - - -STACK_FOUND=APPC0042I|\ - Located stack {0} on tenant [{1}] and in state [{2}]|\ - No resolution required|\ - This message indicates that a service request was made to perform some action on the server \ - and the indicated server was located on the specified tenant. - - - -SERVER_NOT_FOUND=APPC0043E|\ - No server found in provider with self-link URL [{0}]|\ - Correct the server URL|\ - The requested server, identified by its self link URL, could not be found in the provider - -SERVER_OPERATION_EXCEPTION=APPC0044E|\ - Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}]|\ - Contact support for assistance|\ - An exception was caught while trying to perform the indicated operation on the server. The \ - exception may yield more information about the cause of the error. This may be because \ - of access security, or the server is in an invalid state, or any number of reasons. This \ - message should be referred to support for assistance. - - -STACK_NOT_FOUND=APPC0043E|\ - No stack found in provider with self-link URL [{0}]|\ - Correct the server URL|\ - The requested stack, identified by its self link URL, could not be found in the provider - -STACK_OPERATION_EXCEPTION=APPC0044E|\ - Exception {0} was caught attempting {1} of server [{2}] on tenant [{3}]|\ - Contact support for assistance|\ - An exception was caught while trying to perform the indicated operation on the stack. The \ - exception may yield more information about the cause of the error. This may be because \ - of access security, or the stack is in an invalid state, or any number of reasons. This \ - message should be referred to support for assistance. - -MISSING_REQUIRED_PROPERTIES=APPC0045E|\ - One or more properties for [{0}] are missing, null, or empty. They are:|\ - A request to execute the adapter indicated was made from a directed graph, but the properties \ - of the request that are required by the adapter are missing or do not have a value. Correct \ - the directed graph to supply the missing properties.|\ - The specified properties for the indicated adapter operation are invalid or missing. - -SERVER_ERROR_STATE=APPC0046E|\ - The server [{0}] (id={1}) in tenant {2} is in error state, {3} is not allowed|\ - Destroy and recreate the instance|\ - A request to restart or rebuild a server in an error state was received, but those operations \ - are not allowed on a server in this state. OpenStack only allows a deletion of a server \ - that is in the error state. - -IMAGE_NOT_FOUND=APPC0047E|\ - The image {0} could not be located for {1}.|\ - The image indicated could not be found. If the operation being requested is a rebuild of \ - a server, then there is no action that can be taken other than to destroy the server and \ - rebuild it using an image that exists.|\ - This is likely caused by an image being deleted after it was used to build a server. If the \ - request is for a server rebuild, then the image used to create the server was later deleted \ - and no longer exists. The server cannot be rebuilt, because the image doesnt exist. \ - The server must be deleted and reconstructed using a valid, existing image. - -STATE_CHANGE_TIMEOUT=APPC0048E|\ - Time out waiting for {0} with name {1} (and id {2}) to reach one of {3} states, current state is {4}|\ - Recover the resource in whatever means is appropriate|\ - The resource indicated (by name and id) was expected to change it's state (status) to one of the \ - indicated expected states within a specified timeout but the resource did not complete the \ - state change. It's current state is also shown. This can be caused by any number of factors \ - but is normally a problem or conflict within the IaaS provider (OpenStack). - -STATE_CHANGE_EXCEPTION=APPC0049E|\ - Exception {0} waiting for {1} with name {2} (and id {3}) to reach one of {4} states, current state is {5}\n\ - cause={6}|\ - Recover the resource in whatever means is appropriate|\ - The resource indicated (by name and id) was expected to change it's state (status) to one of the \ - indicated expected states within a specified timeout but the resource did not complete the \ - state change. It's current state is also shown. This can be caused by any number of factors \ - but is normally a problem or conflict within the IaaS provider (OpenStack). - -STOP_SERVER=APPC0050I|\ - Server {0} is being stopped...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be stopped. - -START_SERVER=APPC0051I|\ - Server {0} is being started...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be started. - -RESUME_SERVER=APPC0052I|\ - Server {0} is being resumed...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be resumed from a suspended state. - -UNPAUSE_SERVER=APPC0053I|\ - Server {0} is being unpaused...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be unpaused from a paused state. - -CONNECTION_FAILED_RETRY=APPC0054E|\ - Connection to provider {0} at identity {1} using tenant name {2} (id {3}) failed, reason={4}, \ - retrying in {5} seconds, attempt {6} of {7}.|\ - The connection to the provider could not be obtained for the indicated reason. The application \ - controller will retry the attempt to connect to the provider a maximum number of times. The \ - message contains the amount of time the system will wait to retry the connection, and the \ - current attempt and the maximum number of attempts.|\ - Correct the cause of the connection failure as indicated by the reason. - -CONNECTION_FAILED=APPC0055E|\ - Connection to provider {0} at service {1} failed after all retry attempts.|\ - The connection to the named provider at the indicated service URL cannot be opened. All \ - retries have been exhausted. The application controller is giving up on the connection and will \ - fail the request.|\ - Correct the cause of the connection failure as indicated by the reason(s) in previous APPC0054E \ - messages. - -STOPPING_SERVER=APPC0056I|\ - {0} IAAS Adapter stop server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the server to be stopped. The \ - properties that govern the request are echoed immediately following this message. - -REBUILD_SERVER_FAILED=APPC0057E|\ - Server {0} (id {1}) failed to rebuild, reason {2}|\ - The server rebuild failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to rebuild the indicated server but the rebuild request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -PARAMETER_IS_MISSING=APPC0058E|\ - Application {0} graph {1} response did not set the {2} parameter. This parameter is \ - required for synchronization with the controller. Absence of this parameter is assumed \ - to be a failure. Please correct the DG.|\ - The indicated directed graph was called from the application controller but when the \ - graph returned the indicated property was not defined in the return parameters. The \ - controller requires that property to be defined and set to a value that is used to \ - inform the controller of the outcome of operations in the graph. Failure to set \ - the required parameter is assumed to be a failure regardless if the graph actually \ - succeeded or not.|\ - Correct the DG to set the specified parameter to a value that is expected and understood \ - by the controller. - -PARAMETER_NOT_NUMERIC=APPC0059E|\ - Application {0} graph {1} did not set parameter {2} to a valid numeric value ({3}). \ - Please correct the DG.|\ - The indicated directed graph was called by the application controller and the graph \ - did set the specified property, however the property is not a valid numeric \ - value. The parameter is used to convey a numeric quantity and the controller \ - cannot convert the value specified to a number. |\ - Correct the DG. - -DG_FAILED_RESPONSE=APPC0060E|\ - Application {0} graph {1} completed with failure: error code = {2}, message = {3}|\ - The directed graph indicated was called by the application controller and when \ - the graph returned, an error code was set indicating that the graph failed. This \ - is a message that echoes the results of the graph, and shows the returned error \ - code and message.|\ - Correct the cause of the error. - -EXCEPTION_CALLING_DG=APPC0061E|\ - Application {0} received exception {1} attempting to call graph {2}, exception \ - message = {3}|\ - The application controller attempted to call the service logic interpreter (SLI) \ - to execute the indicated graph, but an exception was caught. The class of the \ - exception is shown, as is the message associated with the exception. An \ - abbreviated stack trace is also displayed to provide information as to the \ - state of the thread at the time of the exception.|\ - Correct the cause of the exception and rerun. - -GRAPH_NOT_FOUND=APPC0062E|\ - Application {0} was unable to locate graph {1}|\ - The application controller attempted to call the service logic interpreter (SLI) \ - to execute the specified graph but the graph does not exist in the SLI database.|\ - Correct the database and install the correct graph. - -DEBUG_GRAPH_RESPONSE_HEADER=APPC0063D|\ - Application {0} graph {1} responded with {2} properties|\ - This is a debugging message that is output immediately after the call to the \ - directed graph and before any processing is performed to determine the success \ - or failure of that call. The heading is output prior to dumping all the parameters \ - that were returned by the graph.|\ - No recovery action is required. - -DEBUG_GRAPH_RESPONSE_DETAIL=APPC0064D|\ - {0}:{1} - {2} = {3}|\ - This is a debugging message that is output immediately after the call to the \ - directed graph and before any processing is performed to determine the success \ - or failure of that call. This message is repeated for each parameter that \ - exists in the return context from the graph.|\ - No recovery action is required. - -INVALID_REQUIRED_PROPERTY=APPC0065E|\ - Application {0} request "{1}" was supplied a property "{2}" with the value "{3}" \ - that does not meet the required form(s):|\ - This message indicates that the specified requested operation was passed the \ - specific property named and the property value did not meet the expected \ - format requirements. For example, if the property is expected to be a \ - numeric quantity and it contains alphabetic characters, or if it is expected \ - to be a URL and it is not valid. The message also contains a list of one \ - or more regular expressions that were used to validate the input, and which \ - supply the syntax required for the property.|\ - Correct the property and retry. - -MIGRATING_SERVER=APPC066I|\ - {0} IAAS Adapter migrate of server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the migration of a server. The \ - properties that govern the request are echoed immediately following this message. - -EVACUATING_SERVER=APPC0067I|\ - {0} IAAS Adapter evacuate of server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the evacuation of a server. The \ - properties that govern the request are echoed immediately following this message. - -MIGRATE_SERVER_FAILED=APPC0068E|\ - Server {0} (id {1}) failed to migrate during {2} phase, reason {3}|\ - The server migration failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to migrate the indicated server but the migration request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -EVACUATE_SERVER_FAILED=APPC0069E|\ - Server {0} (id {1}) failed to evacuate, reason {2}|\ - The server evacuation failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to evacuate the indicated server but the evacuation request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -APPC_TOO_BUSY=APPC0080E|\ - APP-C instance is too busy|\ - The APP-C instance handles too many requests and cannot accept new ones as its internal \ - execution queue is full. The problem can appear when the APP-C instance gets more requests \ - than it can handle simultaneously.|\ - Check the server KPIs for possible performance issues (e.g. insufficient memory, \ - high network latency, slow responsiveness of southbound systems and so on) which can affect \ - the system throughput. - -VF_SERVER_BUSY=APPC0081E|\ - Concurrent access to server "{0}"|\ - APP-C currently executes a command on the specified server and cannot accept yet another request \ - for the same one.|\ - Try to resubmit the request at later time. - -VF_ILLEGAL_COMMAND=APPC0082E|\ - Server "{0}" does not support command "{1}" in the current state "{2}"|\ - APP-C cannot perform the requested command on the server in the current state as no state transition \ - is defined for that.|\ - Contact support for assistance. - -VF_UNDEFINED_STATE=APPC0083E|\ - Server "{0}" cannot handle command "{1}" because of its doubtful state|\ - The resource has undefined working state as result of abnormal termination of a previous command.|\ - Recover the resource in whatever means is appropriate. - -APPC_NO_RESOURCE_FOUND=APPC0084E|\ - No resource found with ID "{0}" in A&AI system.|\ - APP-C is unable to resolve the VF details given the instance ID.|\ - Check whether the resource has been deleted (terminated) before. - -APPC_EXPIRED_REQUEST=APPC0085E|\ - The request "{0}" for server "{1}" has exceeded its TTL limit of "{2}" seconds|\ - The received expired event won't be handled by APP-C instance. Normally the problem might be \ - related to asynchronous requests arriving to APP-C instance via DMaaP channel.|\ - Try to submit a new request if still relevant. - -APPC_WORKFLOW_NOT_FOUND=APPC0086E|\ - Workflow for vnfType = "{0}" and command = "{1}" not found.|\ - Unable to retrive Workflow related to mention VNF type and command.|\ - Check provided VNF and Command details are correct. - -APPC_INVALID_INPUT=APPC0087E|\ - Null vnfId and command provided|\ - Request contains Null vnfId and command|\ - Provided non-null VNF and Command details. - -APPC_AUDIT_MSG=APPC0090A|\ - Operation "{0}" for VNF type "{1}" from Source "{2}" with RequestID "{3}" \ - was started at "{4}" and ended at "{5}" with status code "{6}"|\ - Audit detailed msg|\ - Audit detailed msg. - -AAI_CONNECTION_FAILED=APPC0106E|\ - APP-C is unable to communicate with A&AI|\ - Connection to A&AI at service {0} failed after all retry attempts.|\ - The connection to the A&AI at the indicated service URL cannot be opened. \ - All retries have been exhausted. APP-C is giving up on the connection and will \ - reject the operation request.|\ - . - -AAI_UPDATE_FAILED=APPC0107E|\ - APP-C is unable to update COMPONENT_ID {0} to {1} for reason {2}|\ - The update at the end of the operation wasn't performed as a result of \ - A&AI communication failure or its internal error.|\ - . - -AAI_GET_DATA_FAILED=APPC0108E|\ - APP-C is unable to retrieve VF/VFC {0} data for Transaction ID {1} as a \ - result of A&AI communication failure or its internal error.|\ - Operation request will be rejected by APP-C|\ - . - -AAI_CONNECTION_FAILED_RETRY=APPC0105W|\ - A&AI at identity {0} using VNF_ID {1} failed, reason={2}, retrying in {3} seconds, attempt {4} of {5}.|\ - The connection to the A&AI could not be obtained for the indicated reason. APP-C will retry to connect \ - to the A&AI. The message contains the retry delay, the current attempt and the maximum number of attempts.|\ - Correct the cause of the connection failure as indicated by the reason. - -AAI_DELETE_FAILED=APPC0114E|\ - APP-C is unable to delete COMPONENT_ID {0} for reason {1}|\ - The deletion at the end of the operation wasn't performed as a result of \ - A&AI communication failure or its internal error.|\ - . - -AAI_QUERY_FAILED=APPC0115E|\ - Error Querying AAI with vnfID = {0}|\ - Querying AAI for the given vnf id returns failure to APPC|\ - . - -VNF_CONFIGURED=APPC0118I|\ - VNF {0} is configured|\ - No resolution is required, this is an informational message|\ - The VNF configuration has been completed. - -VNF_CONFIGURATION_STARTED=APPC0116I|\ - VNF {0} is being configured|\ - No resolution is required, this is an informational message|\ - The VNF configuration has been started - -VNF_CONFIGURATION_FAILED=APPC0119E|\ - VNF {0} configuration failed for reason {1}|\ - The configuration operation wasn't performed as a result of VNF communication failure or its internal error.|\ - . - -VNF_TEST_STARTED=APPC0120I|\ - VNF {0} is being tested|\ - No resolution is required, this is an informational message|\ - The VNF test has been started - -VNF_TESTED=APPC0121I|\ - VNF {0} was tested|\ - No resolution is required, this is an informational message|\ - The VNF test has been completed - -VNF_TEST_FAILED=APPC0122E|\ - VNF {0} test failed for reason {1}|\ - The test operation wasn't performed as a result of VNF communication failure or its internal error.|\ - . - -VNF_NOT_FOUND=APPC0123E|\ - VNF not found with vnf_id {0}|\ - The VNF wasn't found for the given vnf-id.|\ - . - -VNF_HEALTHCECK_FAILED=APPC0124E|\ - VNF {0} Healthcheck operation failed, reason {1}|\ - The health check operation wasn't performed as a result of VNF communication failure or its internal error.|\ - . - -VM_HEALTHCECK_FAILED=APPC0125E|\ - VM {0} Healthcheck operation failed, reason {1}|\ - The health check operation wasn't performed as a result of VNF communication failure or its internal error.|\ - . - -STOP_SERVER_FAILED=APPC0112E|\ - Server {0} (id {1}) failed to stop during {2} phase, reason {3}|\ - The server stop failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to stop the indicated server but the stop request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -TERMINATE_SERVER_FAILED=APPC0113E|\ - Server {0} (id {1}) failed to terminate during {2} phase, reason {3}|\ - The server termination failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to terminate the indicated server but the migration request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -TERMINATE_STACK_FAILED=APPC0113E|\ - Server {0} (id {1}) failed to terminate during {2} phase, reason {3}|\ - The server termination failed for the indicated reason. Correct the cause of the failure and \ - rerun, if applicable.|\ - The adapter has attempted to terminate the indicated server but the migration request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -TERMINATING_SERVER=APPC0114I|\ - {0} IAAS Adapter terminate server requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the server to be terminated. The \ - properties that govern the request are echoed immediately following this message. - - -TERMINATING_STACK=APPC0115I|\ - {0} IAAS Adapter terminate stack requested|\ - No resolution required|\ - A graph has invoked the IAAS adapter and has requested the server to be terminated. The \ - properties that govern the request are echoed immediately following this message. - -TERMINATE_SERVER=APPC0116I|\ - Server {0} is being terminated...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be terminated. - -TERMINATE_STACK=APPC0117I|\ - Stack {0} is being terminated...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be terminated. - -MIGRATE_COMPLETE=APPC0118I|\ - Migrate {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ - No resolution is required, this is an informational message|\ - APP-C Migrate Operation has completed. - -RESTART_COMPLETE=APPC0119I|\ - Restart {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ - No resolution is required, this is an informational message|\ - APP-C Restart Operation has completed. - -REBUILD_COMPLETE=APPC0120I|\ - Rebuild {0} finished with status {1}. Start Time: {2}. End Time: {3}. Request ID: {4}. Reason:{5}...|\ - No resolution is required, this is an informational message|\ - APP-C Rebuild Operation has completed. - -CLOSE_CONTEXT_FAILED=APPC0121E|\ - Exception {0} was caught attempting to close provider context for {1}.|\ - Contact support for assistance|\ - An exception was caught while trying to close the provider context. The \ - exception may yield more information about the cause of the error. This may be because \ - of access security, or the server is in an invalid state, or any number of reasons. This \ - message should be referred to support for assistance. - -SNAPSHOTING_STACK=APPC0122I|\ - Stack {0} is being snapshoted...|\ - No resolution is required|\ - Stack snapshot. - -STACK_SNAPSHOTED==APPC0123I|\ - Stack {0} snapshoted, snapshot ID = [{1}].|\ - No resolution is required|\ - Stack snapshoted successfully. - - -RESTORING_STACK=APPC0124I|\ - Stack {0} is being restored to snapshot {1}...|\ - No resolution is required|\ - Stack restore. - -STACK_RESTORED=APPC0125I|\ - Stack {0} is restored to snapshot {1}.|\ - No resolution is required|\ - Stack restored successfully. - -MISSING_PARAMETER_IN_REQUEST=APPC0126E|\ - Parameter {0} is missing in svc request of {1}.|\ - Check DG node definition to pass missing parameter's value.|\ - Node definition in DG missing indicated parameter value or value is incorrect, \ - check the graph definition. - -CANNOT_ESTABLISH_CONNECTION=APPC0127E|\ - Cannot establish connection to server {0} port {1} with user {2}.|\ - Check server IP, port and user credentials.|\ - Wrong data sent in request's payload. - - -APPC_METRIC_MSG=APPC0128I|\ - Operation "{0}" for VNF type "{1}" from Source "{2}" with RequestID "{3}" on "{4}" with action "{5}" \ - ended in {6} ms with result "{7}"|\ - No resolution is required, this is an informational message|\ - This message indicates that the APPC logged some operation to metric - - SNAPSHOTING_SERVER=APPC0129I|\ -{0} IAAS Adapter create snapshot of server requested|\ -No resolution is required, this is an informational message|\ -This message indicates that a IAAS Adapter create snapshot of server was requested. - -INPUT_PAYLOAD_PARSING_FAILED = APPC0130E|\ - Failed to parsing the input payload: {0}|\ - Please provide correct input string for parsing.|\ - . - -APPC_EXCEPTION = APPC0132E|\ - Error occurred for VNF type : {0}, reason {1}|\ - Runtime exception thrown by APPC.|\ - . - -SSH_DATA_EXCEPTION = APPC0133E|\ - SSH Data Exception occurred, reason {0}|\ - SSH Data exception occurred.|\ - . - -JSON_PROCESSING_EXCEPTION = APPC0134E|\ - Json processing exception occurred, reason {0}|\ - Json processing Exception|\ - . - -SUCCESS_EVENT_MESSAGE = APPC0136I|\ - Operation {0} succeed for {1}|\ - Success message.|\ - . -DEPENDENCY_MODEL_NOT_FOUND = APPC0137E|\ - Dependency model not found for VNF type {0}, reason {1}|\ - Please provide dependency model|\ - . - -INVALID_DEPENDENCY_MODEL = APPC0138E|\ - Invalid Dependency model for VNF Type {0}, reason {1}|\ - Invalid dependency model found |\ - . - - -FAILURE_RETRIEVE_VNFC_DG = APPC0139E|\ - Failed to retrieve DG for VNFC Type: {0}|\ - Failed to retrieve VNFC DG |\ - . - - -SERVER_NETWORK_ERROR=APPC0140E|\ - Server {0} either has a port {1} that is NOT online, or the status of the network to which the port is connected to is not ACTIVE|\ - Please ensure they are UP and running before requested operation|\ - It is critical that the VM Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ - the requested operation on it. - . - -REBUILD_SERVER=APPC0140I|\ - Server {0} is being rebuilt...|\ - No recovery required|\ - The processing being performed by APPC requires that the indicated server be rebuilt. - -HYPERVISOR_DOWN_ERROR=APPC0141E|\ - Hypervisor {0} for the Server {1} is either NOT ENABLED, or its status is DOWN or UNKNOWN|\ - Please ensure the Hypervisor is UP and running before proceeding with the requested operation|\ - It is critical that the Hypervisor that manages the Virtual Machine for the Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ - the requested operation on it. - . - -HYPERVISOR_STATUS_UKNOWN=APPC0158E|\ - Unable to determine the status of the Hypervisor for the Server {0} |\ - Please ensure the userid has privileges enabled to query for the Hypervisor status. |\ - If you wish to proceed with the requested operation, either obtain the privileges from the Cloud provider, or skip the Hypervisor check and retry the request. - . - -HYPERVISOR_NETWORK_ERROR=APPC0142E|\ - Hypervisor {0} for the Server {1} is NOT Reachable by APPC for initiating the requested operation|\ - Please ensure the Hypervisor is connected to the network before proceeding with the requested operation|\ - It is critical that the Hypervisor that manages the Virtual Machine for the Server is reachable by the Provider(ex: OpenStack) in order to be able to perform \ - the requested operation on it. - -EVACUATE_SERVER_REBUILD_FAILED=APPC0143E|\ - Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3}|\ - The server rebuild after evacuation failed for the indicated reason. Correct the cause of the failure and \ - run a rebuild, if applicable.|\ - The adapter has attempted to rebuild after evacuating the indicated server but the rebuild request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -RESTART_APPLICATION=APPC0144I|\ - Application on server {0} is being restarted...|\ - No recovery required|\ - The processing being performed by APPC requires that the application on the indicated server be restarted. - -START_APPLICATION=APPC0145I|\ - Application on server {0} is being started...|\ - No recovery required|\ - The processing being performed by APPC requires that the application on the indicated server be started. - -APPLICATION_RESTART_FAILED=APPC0146E|\ - Restart application operation failed on server : {0}, reason {1}|\ - Restart application operation failure.|\ - Correct the cause of the failure as indicated by the reason. - -APPLICATION_START_FAILED=APPC0147E|\ - Start application operation failed on server : {0}, reason {1}|\ - Start application operation failure.|\ - Correct the cause of the failure as indicated by the reason. - -LOOKING_SERVER_UP=APPC0148I|\ -{0} IAAS Adapter looking up for the server requested|\ -No resolution is required, this is an informational message|\ -This message indicates that a IAAS Adapter lookup of server was requested. - -EVACUATE_SERVER_REBUILD_FAILED=APPC0149E|\ - Server {0} evacuate from host {1} to host {2} failed during the rebuild on host {2}, reason {3}|\ - The server rebuild after evacuation failed for the indicated reason. Correct the cause of the failure and \ - run a rebuild, if applicable.|\ - The adapter has attempted to rebuild after evacuating the indicated server but the rebuild request has \ - been failed by the provider for some reason. The reason returned by the provider is \ - included in the message. - -APPLICATION_STOP_FAILED=APPC0150E|\ - Stop application operation failed on server : {0}, reason {1}|\ - Stop application operation failure.|\ - Correct the cause of the failure as indicated by the reason. - -STOP_APPLICATION=APPC0151I|\ - Application on server {0} is being stopped...|\ - No recovery required|\ - The processing being performed by APPC requires that the application on the indicated server be stopped. - -LCM_OPERATIONS_DISABLED=APPC0152E|\ - APPC LCM operations have been administratively disabled|\ - No recovery required|\ - This is a indication that the APPC LCM operations are disabled. - -OAM_OPERATION_EXCEPTION=APPC0153E|\ - Application {0} received exception {1} while attempting to execute oam operation {2}, exception message = {3}|\ - The application controller attempted to perform an OAM operation \ - but an exception was caught. The class of the \ - exception is shown, as is the message associated with the exception. An \ - abbreviated stack trace is also displayed to provide information as to the \ - state of the thread at the time of the exception.|\ - Correct the cause of the exception and rerun. - -OAM_OPERATION_ENTERING_MAINTENANCE_MODE=APPC0154W|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC will no longer accept new LCM requests. Previously accepted LCM requests will be allowed to complete. - -OAM_OPERATION_MAINTENANCE_MODE=APPC0155W|\ - Application {0} is in {1}|\ - No recovery required|\ - The APPC is not accepting new LCM requests and all previously accepted LCM requests have completed. - -OAM_OPERATION_STARTING=APPC0156I|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC has initiated its startup procedure. Its internal components are coming online. Once completed it will start accepting LCM requests. - -OAM_OPERATION_STARTED=APPC0157I|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC will now accept new LCM requests for processing. - -INVALID_STATE_TRANSITION=APPC0158E|\ - A {1} API is not allowed when {0} in the {2} state|\ - No recovery required|\ - The Operation requested cannot be performed as per the current state of APPC. - -OAM_OPERATION_STOPPING=APPC0159W|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC has initiated its stop procedure. Its internal LCM bundles are stopping. - -OAM_OPERATION_STOPPED=APPC0160W|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC LCM bundles have now stopped. - -REQUEST_HANDLER_UNAVAILABLE=APPC0161E|\ - Application {0} was unable to find the Request Handler service |\ - The application controller attempted to get a handle on Request Handler service \ - but was unable to locate it in the OSGi Service Registry.|\ - Verify if the Request Handler bundle is running. - -OAM_OPERATION_RESTARTING=APPC0162W|\ - Application {0} is {1}|\ - No recovery required|\ - The APPC has initiated its restart procedure. Its internal LCM bundles are stopping and will then start again. - -OAM_OPERATION_RESTARTED=APPC0163W|\ - Application {0} is {1} for restart|\ - No recovery required|\ - The APPC LCM bundles have been restared (stopped and then started). - -OAM_OPERATION_INVALID_INPUT=APPC0162E|\ - {0}|\ - No recovery required|\ - Fix the input parameter and retry. - -IAAS_UNSUPPORTED_IDENTITY_SERVICE=APPC0163E|\ - Unsupported identity service version, unable to retrieve ServiceCatalog for identity service {0}|\ - Verify the identity url provided is correct. Currently supported version of the OpenStack identity servicer\ - are v2 and v3. If a support for a new version in required contact development.|\ - This message indicates that a request was made to connect to an unsupported version of \ - identity service. \ No newline at end of file diff --git a/appc-common/src/main/resources/org/openecomp/appc/i18n/auth.properties b/appc-common/src/main/resources/org/openecomp/appc/i18n/auth.properties deleted file mode 100644 index d64e688e5..000000000 --- a/appc-common/src/main/resources/org/openecomp/appc/i18n/auth.properties +++ /dev/null @@ -1,26 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -username=admin -password=admin diff --git a/appc-common/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg b/appc-common/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg deleted file mode 100644 index a3a3f5837..000000000 --- a/appc-common/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg +++ /dev/null @@ -1,149 +0,0 @@ - ################################################################################ - # - # Licensed to the Apache Software Foundation (ASF) under one or more - # contributor license agreements. See the NOTICE file distributed with - # this work for additional information regarding copyright ownership. - # The ASF licenses this file to You under the Apache License, Version 2.0 - # (the "License"); you may not use this file except in compliance with - # the License. You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITH WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - ################################################################################ - - # Root - #log4j.rootLogger=TRACE, osgi:VmLogAppender - log4j.rootLogger=TRACE, out, sift, osgi:* - log4j.throwableRenderer=org.apache.log4j.OsgiThrowableRenderer - - # CONSOLE appender not used by default - log4j.appender.stdout=org.apache.log4j.ConsoleAppender - log4j.appender.stdout.layout=org.apache.log4j.PatternLayout - log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %X{bundle.id} - %X{bundle.name} - %X{bundle.version} | %m%n - - # Async appender forwarding to file appender - log4j.appender.async=org.apache.log4j.AsyncAppender - log4j.appender.async.appenders=out - - # Karaf appenders - # File appender - log4j.appender.out=org.apache.log4j.RollingFileAppender - log4j.appender.out.layout=org.apache.log4j.PatternLayout - log4j.appender.out.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %X{bundle.id} - %X{bundle.name} - %X{bundle.version} | %m%n - log4j.appender.out.file=${karaf.data}/log/karaf.log - log4j.appender.out.append=true - log4j.appender.out.maxFileSize=10MB - log4j.appender.out.maxBackupIndex=100 - - - # Sift appender - log4j.appender.sift=org.apache.log4j.sift.MDCSiftingAppender - log4j.appender.sift.key=bundle.name - log4j.appender.sift.default=karaf - log4j.appender.sift.appender=org.apache.log4j.RollingFileAppender - log4j.appender.sift.appender.layout=org.apache.log4j.PatternLayout - log4j.appender.sift.appender.layout.ConversionPattern=%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%-5.5p|%X{AlertSeverity}|%X{ServerFQDN}|%X{ServerIPAddress}|[%c{3}]|%m%n - log4j.appender.sift.appender.file=${karaf.data}/log/eelf/karaf.log - log4j.appender.sift.appender.append=true - - log4j.category.org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPusherImpl=DEBUG - log4j.category.org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator=DEBUG - - - #ECOMP Debug appender - log4j.appender.debug=org.apache.log4j.RollingFileAppender - log4j.appender.debug.key=bundle.name - log4j.appender.debug.default=karaf - - log4j.appender.debug.appName=EELFDebug - log4j.appender.debug.layout=org.apache.log4j.PatternLayout - log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd'T'hh:mm:ss.SSSXXX}|%X{RequestId}|%m%n - #log4j.appender.debug.filter.f1=org.apache.log4j.varia.LevelRangeFilter - #log4j.appender.debug.filter.f1.LevelMax=WARN - #log4j.appender.debug.filter.f1.LevelMin=TRACE - - - log4j.appender.debug.file=${karaf.data}/log/APPC/appc-debug.log - log4j.appender.debug.append=true - log4j.appender.debug.maxFileSize=100MB - log4j.appender.debug.maxBackupIndex=10 - - - #Error appender - log4j.appender.error=org.apache.log4j.RollingFileAppender - log4j.appender.error.appName=EELFError - log4j.appender.error.File=${karaf.data}/log/APPC/appc-error.log - log4j.appender.error.Threshold=ERROR - log4j.appender.error.MaxBackupIndex=1 - log4j.appender.error.MaxFileSize=100MB - log4j.appender.error.layout=org.apache.log4j.PatternLayout - log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd'T'hh:mm:ss.SSSXXX}|%X{RequestId}|%t|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%-5.5p|%X{ErrorCode}|%X{ErrorDescription}|%m%n - - #Metrics appender - log4j.appender.metric=org.apache.log4j.RollingFileAppender - log4j.appender.metric.appName=EELFMetrics - log4j.appender.metric.File=${karaf.data}/log/APPC/appc-metric.log - log4j.appender.metric.MaxBackupIndex=1 - log4j.appender.metric.MaxFileSize=100MB - log4j.appender.metric.layout=org.apache.log4j.PatternLayout - log4j.appender.metric.layout.ConversionPattern=%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%-5.5p|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%m%n - - #Audit appender - log4j.appender.audit=org.apache.log4j.RollingFileAppender - log4j.appender.audit.appName=EELFAudit - log4j.appender.audit.File=${karaf.data}/log/APPC/appc-audit.log - log4j.appender.audit.MaxBackupIndex=1 - log4j.appender.audit.MaxFileSize=100MB - log4j.appender.audit.layout=org.apache.log4j.PatternLayout - log4j.appender.audit.layout.ConversionPattern=%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%-5.5p|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%m%n - - #Loggers - - #Routing of all messages from root logger - log4j.logger.org.openecomp=TRACE, debug, error - #Store to the same log file messages from upper level appender or not - log4j.additivity.org.openecomp=false - - #org.openecomp logger - log4j.logger.org.openecomp=TRACE, debug, error - log4j.additivity.org.openecomp=false - - #EELFManager loggers - #EELF parent logger - log4j.logger.com.att.eelf=TRACE, debug - log4j.additivity.com.att.eelf=false - - #Audit logger routing - log4j.logger.com.att.eelf.audit=DEBUG, audit - log4j.additivity.com.att.eelf.audit=false - - #Metric logger routing - log4j.logger.com.att.eelf.metrics=DEBUG, metric - log4j.additivity.com.att.eelf.metrics=false - - #Performance logger routing - log4j.logger.com.att.eelf.perf=DEBUG, metric - log4j.additivity.com.att.eelf.perf=false - - #Server logger routing - log4j.logger.com.att.eelf.server=DEBUG, debug - log4j.additivity.com.att.eelf.server=false - - #Policy logger routing - log4j.logger.com.att.eelf.policy=DEBUG, debug - log4j.additivity.com.att.eelf.policy=false - - #Error logger routing - log4j.logger.com.att.eelf.error=DEBUG, error - log4j.additivity.com.att.eelf.error=false - - #Debug logger routing - log4j.logger.com.att.eelf.debug=DEBUG, debug - log4j.additivity.com.att.eelf.debug=false - diff --git a/appc-common/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java b/appc-common/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java new file mode 100644 index 000000000..41ceb4303 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache; + +import org.junit.Assert; +import org.junit.Test; + +public class CacheStrategiesTest { + private CacheStrategies cacheStrategies = CacheStrategies.LRU; + + @Test + public void testName() throws Exception { + Assert.assertEquals("Should have name LRU", "LRU", cacheStrategies.name()); + } + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Should return String LRU", "LRU", cacheStrategies.toString()); + } + + @Test + public void testEquals() throws Exception { + Assert.assertTrue(cacheStrategies.equals(CacheStrategies.LRU)); + Assert.assertFalse(cacheStrategies.equals(null)); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java b/appc-common/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java new file mode 100644 index 000000000..3f4233d86 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +import java.util.Map; + +public class LRUCacheTest { + + @Test + public void testConstructor() throws Exception { + LRUCache cache = new LRUCache(20); + Map internalMap = Whitebox.getInternalState(cache, "map"); + Assert.assertTrue(internalMap != null); + Assert.assertTrue(internalMap.size() == 0); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetAndPutObject() throws Exception { + LRUCache cache = new LRUCache(20); + + String key = "testing key"; + Assert.assertTrue(cache.getObject(key) == null); + + String value = "testing value"; + cache.putObject(key, value); + Map internalMap = Whitebox.getInternalState(cache, "map"); + Assert.assertTrue(internalMap.containsKey(key)); + Assert.assertTrue(internalMap.containsValue(value)); + Assert.assertTrue(internalMap.size() == 1); + + Assert.assertEquals(value, cache.getObject(key)); + } + +} diff --git a/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java b/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java new file mode 100644 index 000000000..386118025 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.appc.cache.CacheStrategies; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MetadataCacheFactory.class, MetadataCacheImpl.class}) +public class MetadataCacheFactoryTest { + @Test + public void testConstructor() throws Exception { + Whitebox.invokeConstructor(MetadataCacheFactory.class); + } + + @Test + public void testGetInstance() throws Exception { + Assert.assertTrue("Should not return null", MetadataCacheFactory.getInstance() != null); + Assert.assertEquals("Should always return the same object", + MetadataCacheFactory.getInstance(), MetadataCacheFactory.getInstance()); + } + + @Test + public void testGetMetadataCacheWithNoArgument() throws Exception { + MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); + PowerMockito.whenNew(MetadataCacheImpl.class).withNoArguments().thenReturn(mockImpl); + Assert.assertEquals(mockImpl, MetadataCacheFactory.getInstance().getMetadataCache()); + } + + @Test + public void testGetMetadataCacheWithArgument() throws Exception { + CacheStrategies cacheStrategies = CacheStrategies.LRU; + MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); + PowerMockito.whenNew(MetadataCacheImpl.class).withArguments(cacheStrategies).thenReturn(mockImpl); + Assert.assertEquals(mockImpl, MetadataCacheFactory.getInstance().getMetadataCache(cacheStrategies)); + } + +} diff --git a/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java b/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java new file mode 100644 index 000000000..c68fb48dc --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.cache.CacheStrategies; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.spy; + +public class MetadataCacheImplTest { + @Test + public void testConstructor() throws Exception { + // test without parameter + MetadataCacheImpl impl = new MetadataCacheImpl<>(); + Assert.assertTrue("Should have initialized strategy", + Whitebox.getInternalState(impl, "strategy") != null); + + // test with parameter + impl = new MetadataCacheImpl<>(CacheStrategies.LRU); + Assert.assertTrue("Should have initialized strategy", + Whitebox.getInternalState(impl, "strategy") != null); + + impl = new MetadataCacheImpl<>(null); + Assert.assertTrue("Should not initialized strategy", + Whitebox.getInternalState(impl, "strategy") == null); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetAndPutObject() throws Exception { + MetadataCacheImpl impl = spy(new MetadataCacheImpl<>()); + + String key = "testing key"; + Assert.assertTrue(impl.getObject(key) == null); + + String value = "testing value"; + impl.putObject(key, value); + Assert.assertEquals(value, impl.getObject(key)); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/concurrent/TestSignal.java b/appc-common/src/test/java/org/onap/appc/concurrent/TestSignal.java new file mode 100644 index 000000000..e86fe54a1 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/concurrent/TestSignal.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.concurrent; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.TimeoutException; + +import org.junit.Test; +import org.onap.appc.concurrent.Signal; + +public class TestSignal { + + private static final DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS"); + public static final String SIGNAL_READY = "READY"; + public static final String SIGNAL_SHUTDOWN = "SHUTDOWN"; + + @Test + public void TestSimpleSignal() throws TimeoutException { + + Signal mySignal = new Signal(Thread.currentThread()); + mySignal.setTimeout(5000L); + Fred fred = new Fred(mySignal); + Thread t1 = new Thread(fred); + + /* + * Verify that fred is dead, then start him and wait for him to signal us he is ready to proceed + */ + assertFalse(t1.isAlive()); + t1.start(); + System.out.println(formatter.format(new Date()) + " MAIN: Waiting for Ready..."); + mySignal.waitFor(SIGNAL_READY); + System.out.println(formatter.format(new Date()) + " MAIN: Signal Ready received"); + + /* + * Verify that fred is still alive and we will sleep for a while (simulate doing things) + */ + assertTrue(t1.isAlive()); + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // ignored + } + + /* + * Verify that fred is still alive and signal him to shutdown + */ + assertTrue(t1.isAlive()); + System.out.println(formatter.format(new Date()) + " MAIN: Signaling shutdown"); + fred.getSignal().signal(SIGNAL_SHUTDOWN); + + /* + * Wait a little bit + */ + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // ignored + } + + /* + * Verify that fred is dead now and that he completed normally + */ + System.out.println(formatter.format(new Date()) + " MAIN: Shutting down..."); + assertFalse(t1.isAlive()); + assertTrue(fred.isCompleted()); + } + + public class Fred implements Runnable { + private Signal signal; + private Signal parentSignal; + private boolean completed = false; + + public Fred(Signal parentSignal) { + this.parentSignal = parentSignal; + } + + @Override + public void run() { + signal = new Signal(Thread.currentThread()); + signal.setTimeout(5000L); + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // Ignore + } + + System.out.println(formatter.format(new Date()) + " FRED: Signaling ready..."); + parentSignal.signal(SIGNAL_READY); + + try { + System.out.println(formatter.format(new Date()) + " FRED: Waiting for shutdown..."); + signal.waitFor(SIGNAL_SHUTDOWN); + System.out.println(formatter.format(new Date()) + " FRED: Received shutdown"); + completed = true; + } catch (TimeoutException e) { + e.printStackTrace(); + } + } + + public boolean isCompleted() { + return completed; + } + + public Signal getSignal() { + return signal; + } + } +} diff --git a/appc-common/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java b/appc-common/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java new file mode 100644 index 000000000..a423eae81 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java @@ -0,0 +1,337 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.configuration; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.powermock.reflect.Whitebox; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import static org.mockito.Mockito.mock; + +public class DefaultConfigurationTest { + private static final String propKey1 = "testKey1"; + private static final String propKey2 = "testKey2"; + private static final String propValue1 = "testValue1"; + private static final String propValue2 = "testValue2"; + + private Properties prop = new Properties(); + private DefaultConfiguration defaultConfiguration; + + @Before + public void setUp() throws Exception { + prop.setProperty(propKey1, propValue1); + prop.setProperty(propKey2, propValue2); + + defaultConfiguration = new DefaultConfiguration(); + } + + @Test + public void testClear() throws Exception { + Whitebox.setInternalState(defaultConfiguration, "properties", prop); + defaultConfiguration.clear(); + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertTrue("internal properties should be cleared", internalProp.isEmpty()); + } + + @Test + public void testClone() throws Exception { + Object clonedObject = defaultConfiguration.clone(); + Assert.assertTrue("Should be DefaultConfiguration", clonedObject instanceof DefaultConfiguration); + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Properties clonedInternalProp = Whitebox.getInternalState(clonedObject, "properties"); + Assert.assertEquals(internalProp, clonedInternalProp); + } + + @Test + public void testEquals() throws Exception { + // test compare with null + Assert.assertFalse(defaultConfiguration.equals(null)); + // test with non-DefaultConfiguration object + Assert.assertFalse(defaultConfiguration.equals("abc")); + + // test with not match DefaultConfiguration object + defaultConfiguration.setProperties(prop); + DefaultConfiguration newConfig = new DefaultConfiguration(); + Assert.assertFalse(defaultConfiguration.equals(newConfig)); + + // test with matching DefaultConfiguration object + newConfig.setProperties(prop); + Assert.assertTrue(defaultConfiguration.equals(newConfig)); + } + + @Test + public void testSetPropAndGetBooleanProperty() throws Exception { + String booleanKey = "booleanKey"; + // test default value + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + // test match value true + defaultConfiguration.setProperty(booleanKey, "true"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "True"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "TrUe"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + // test not matching true values + defaultConfiguration.setProperty(booleanKey, "false"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "abc"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + } + + @Test + public void testSetPropAndGetBooleanPropertyWithDefaultValue() throws Exception { + String booleanKey = "booleanKey"; + // test default value + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, false)); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, true)); + // test match value true + defaultConfiguration.setProperty(booleanKey, "true"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + defaultConfiguration.setProperty(booleanKey, "True"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + defaultConfiguration.setProperty(booleanKey, "TrUe"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + // test not matching true values + defaultConfiguration.setProperty(booleanKey, "false"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); + defaultConfiguration.setProperty(booleanKey, "abc"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); + } + + @Test + public void testSetPropAndGetDoubleProperty() throws Exception { + String doubleKey = "doubleKey"; + // test default value + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); + // test NumberFormatException + defaultConfiguration.setProperty(doubleKey, "abc"); + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); + // test normal + defaultConfiguration.setProperty(doubleKey, "1.1"); + Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey)); + } + + @Test + public void testSetPropAndGetDoublePropertyWithDefaultValue() throws Exception { + String doubleKey = "doubleKey"; + // test default value + Assert.assertTrue(2.2 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + // test NumberFormatException + defaultConfiguration.setProperty(doubleKey, "abc"); + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + // test normal + defaultConfiguration.setProperty(doubleKey, "1.1"); + Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + } + + @Test + public void testSetPropAndGetIntegerProperty() throws Exception { + String integerKey = "integerKey"; + // test default value + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); + // test NumberFormatException + defaultConfiguration.setProperty(integerKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); + // test normal + defaultConfiguration.setProperty(integerKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey)); + } + + @Test + public void testSetPropAndGetIntegerPropertyWithDefaultValue() throws Exception { + String integerKey = "integerKey"; + // test default value + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 100)); + // test NumberFormatException + defaultConfiguration.setProperty(integerKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey, 100)); + // test normal + defaultConfiguration.setProperty(integerKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 10)); + } + + @Test + public void testSetPropAndGetLongProperty() throws Exception { + String longKey = "longKey"; + // test default value + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); + // test NumberFormatException + defaultConfiguration.setProperty(longKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); + // test normal + defaultConfiguration.setProperty(longKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey)); + } + + @Test + public void testSetPropAndGetLongPropertyWithDefaultVaue() throws Exception { + String longKey = "longKey"; + // test default value + Assert.assertTrue(10 == defaultConfiguration.getLongProperty(longKey, 10)); + // test NumberFormatException + defaultConfiguration.setProperty(longKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey, 10)); + // test normal + defaultConfiguration.setProperty(longKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey, 10)); + } + + @Test + public void testSetAndGetProperties() throws Exception { + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); + + defaultConfiguration.setProperties(prop); + internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); + } + + @Test + public void testSetAndGetProperty() throws Exception { + String key = "key"; + // test default value + Assert.assertTrue(null == defaultConfiguration.getProperty(key)); + // test normal + defaultConfiguration.setProperty(key, "abc"); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key)); + } + + @Test + public void testSetPropAndGetPropertyWithDefaultValue() throws Exception { + String key = "key"; + // test default value + Assert.assertTrue(null == defaultConfiguration.getProperty(key, null)); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abc")); + // test normal + defaultConfiguration.setProperty(key, "abc"); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abcd")); + } + + @Test + public void testHashCode() throws Exception { + Properties properties = null; + Whitebox.setInternalState(defaultConfiguration, "properties", properties); + Assert.assertEquals(0, defaultConfiguration.hashCode()); + + + Whitebox.setInternalState(defaultConfiguration, "properties", prop); + Assert.assertEquals(prop.hashCode(), defaultConfiguration.hashCode()); + } + + @Test + public void testIsPropertyDefined() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isPropertyDefined(key)); + // test exist + defaultConfiguration.setProperty(key, "abc"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + } + + @Test + public void testIsValidBoolean() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "True"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + defaultConfiguration.setProperty(key, "FaLse"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + } + + @Test + public void testIsValidDouble() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidDouble(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidDouble(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidDouble(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertTrue(defaultConfiguration.isValidDouble(key)); + } + + @Test + public void testIsValidInteger() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidInteger(key)); + } + + @Test + public void testIsValidLong() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidLong(key)); + } + + @Test + public void testSetPropertiesWithInputStream() throws Exception { + InputStream mockIS = mock(InputStream.class); + defaultConfiguration.setProperties(mockIS); + + Properties mockProp = mock(Properties.class); + Mockito.doThrow(new IOException("testing exception")).when(mockProp).load(mockIS); + Whitebox.setInternalState(defaultConfiguration, "properties", mockProp); + defaultConfiguration.setProperties(mockIS); + // Should come here without exception + } + + @Test + public void testToString() throws Exception { + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(String.format("Configuration: %d properties, keys:[%s]", + internalProp.size(), internalProp.keySet().toString()), defaultConfiguration.toString()); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/encryption/TestEncryption.java b/appc-common/src/test/java/org/onap/appc/encryption/TestEncryption.java new file mode 100644 index 000000000..aa9664d2e --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/encryption/TestEncryption.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryption; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import org.junit.Test; +import org.onap.appc.encryption.EncryptionTool; + +public class TestEncryption { + + @Test + public void testEncryptionDecryption() { + String plain = "AppC"; + String enc = EncryptionTool.getInstance().encrypt(plain); + assertNotEquals(plain, enc); + String dec = EncryptionTool.getInstance().decrypt(enc); + assertNotEquals(enc, dec); + assertEquals(plain, dec); + System.out.println(String.format("%s = [%s]", plain, enc)); + } + +} diff --git a/appc-common/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java b/appc-common/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java new file mode 100644 index 000000000..a9611a2df --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + + +public class APPCExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + APPCException appcException = new APPCException(); + Assert.assertTrue(appcException.getCause() == null); + Assert.assertTrue(appcException.getLocalizedMessage() == null); + Assert.assertTrue(appcException.getMessage() == null); + } + + @Test + public void testConstructorWithMessaqge() throws Exception { + String message = "testing message"; + APPCException appcException = new APPCException(message); + Assert.assertTrue(appcException.getCause() == null); + Assert.assertEquals(message, appcException.getLocalizedMessage()); + Assert.assertEquals(message, appcException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + APPCException appcException = new APPCException(throwable); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + APPCException appcException = new APPCException(message, throwable); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithFourArguments() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + APPCException appcException = new APPCException(message, throwable, true, true); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + + Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") != null); + Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") != null); + + appcException = new APPCException(message, throwable, false, false); + Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") == null); + Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") == null); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java b/appc-common/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java new file mode 100644 index 000000000..9822ff7ee --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; + +public class InvalidInputExceptionTest { + @Test + public void testConstructor() throws Exception { + String message = "testing message"; + InvalidInputException invalidInputException = new InvalidInputException(message); + Assert.assertTrue(invalidInputException.getCause() == null); + Assert.assertEquals(message, invalidInputException.getLocalizedMessage()); + Assert.assertEquals(message, invalidInputException.getMessage()); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java b/appc-common/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java new file mode 100644 index 000000000..c008131f1 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; + +public class InvalidStateExceptionTest { + @Test + public void testConstructor() throws Exception { + String message = "testing message"; + InvalidStateException invalidStateException = new InvalidStateException(message); + Assert.assertTrue(invalidStateException.getCause() == null); + Assert.assertEquals(message, invalidStateException.getLocalizedMessage()); + Assert.assertEquals(message, invalidStateException.getMessage()); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java b/appc-common/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java new file mode 100644 index 000000000..d3c7ab5ef --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class UnknownProviderExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + UnknownProviderException unknownProviderException = new UnknownProviderException(); + Assert.assertTrue(unknownProviderException.getCause() == null); + Assert.assertTrue(unknownProviderException.getLocalizedMessage() == null); + Assert.assertTrue(unknownProviderException.getMessage() == null); + } + + @Test + public void testConstructorWithMessaqge() throws Exception { + String message = "testing message"; + UnknownProviderException unknownProviderException = new UnknownProviderException(message); + Assert.assertTrue(unknownProviderException.getCause() == null); + Assert.assertEquals(message, unknownProviderException.getLocalizedMessage()); + Assert.assertEquals(message, unknownProviderException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + UnknownProviderException unknownProviderException = new UnknownProviderException(throwable); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + UnknownProviderException unknownProviderException = new UnknownProviderException(message, throwable); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithFourArguements() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + UnknownProviderException unknownProviderException = + new UnknownProviderException(message, throwable, true, true); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, "stackTrace") != null); + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, + "suppressedExceptions") != null); + + unknownProviderException = new UnknownProviderException(message, throwable, false, false); + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, + "stackTrace") == null); + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, + "suppressedExceptions") == null); + } + +} diff --git a/appc-common/src/test/java/org/onap/appc/i18n/MsgTest.java b/appc-common/src/test/java/org/onap/appc/i18n/MsgTest.java new file mode 100644 index 000000000..1a541a5d4 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/i18n/MsgTest.java @@ -0,0 +1,771 @@ +package org.onap.appc.i18n; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Assert; +import org.junit.Test; + +public class MsgTest { + + @Test + public void testNameAndToString() throws Exception { + for (Msg msg : Msg.values()) { + Assert.assertEquals(msg.name(), msg.toString()); + } + } + + @Test + public void testCONFIGURATION_STARTED() { + assertNotNull(Msg.valueOf("CONFIGURATION_STARTED")); + } + + @Test + public void testCONFIGURATION_CLEARED() { + assertNotNull(Msg.valueOf("CONFIGURATION_CLEARED")); + } + + @Test + public void testLOADING_CONFIGURATION_OVERRIDES() { + assertNotNull(Msg.valueOf("LOADING_CONFIGURATION_OVERRIDES")); + } + + + @Test + public void testLOADING_DEFAULTS() { + assertNotNull(Msg.valueOf("LOADING_DEFAULTS")); + } + + + @Test + public void testNO_DEFAULTS_FOUND() { + assertNotNull(Msg.valueOf("NO_DEFAULTS_FOUND")); + } + + @Test + public void testPROPERTY_VALUE() { + assertNotNull(Msg.valueOf("PROPERTY_VALUE")); + } + + @Test + public void testNO_OVERRIDE_PROPERTY_FILE_LOADED() { + assertNotNull(Msg.valueOf("NO_OVERRIDE_PROPERTY_FILE_LOADED")); + } + + @Test + public void testSEARCHING_CONFIGURATION_OVERRIDES() { + assertNotNull(Msg.valueOf("SEARCHING_CONFIGURATION_OVERRIDES")); + } + + @Test + public void testLOADING_APPLICATION_OVERRIDES() { + assertNotNull(Msg.valueOf("LOADING_APPLICATION_OVERRIDES")); + } + + @Test + public void testNO_APPLICATION_OVERRIDES() { + assertNotNull(Msg.valueOf("NO_APPLICATION_OVERRIDES")); + } + + @Test + public void testMERGING_SYSTEM_PROPERTIES() { + assertNotNull(Msg.valueOf("MERGING_SYSTEM_PROPERTIES")); + } + + @Test + public void testSETTING_SPECIAL_PROPERTY() { + assertNotNull(Msg.valueOf("SETTING_SPECIAL_PROPERTY")); + } + + @Test + public void testLOADING_RESOURCE_BUNDLE() { + assertNotNull(Msg.valueOf("LOADING_RESOURCE_BUNDLE")); + } + + @Test + public void testLOGGING_ALREADY_INITIALIZED() { assertNotNull(Msg.valueOf("LOGGING_ALREADY_INITIALIZED")); } + + @Test + public void testSEARCHING_LOG_CONFIGURATION() { + assertNotNull(Msg.valueOf("SEARCHING_LOG_CONFIGURATION")); + } + + @Test + public void testLOADING_DEFAULT_LOG_CONFIGURATION() { + assertNotNull(Msg.valueOf("LOADING_DEFAULT_LOG_CONFIGURATION")); + } + + @Test + public void testNO_LOG_CONFIGURATION() { + assertNotNull(Msg.valueOf("NO_LOG_CONFIGURATION")); + } + + @Test + public void testUNSUPPORTED_LOGGING_FRAMEWORK() { + assertNotNull(Msg.valueOf("UNSUPPORTED_LOGGING_FRAMEWORK")); + } + + @Test + public void testLOADING_LOG_CONFIGURATION() { + assertNotNull(Msg.valueOf("LOADING_LOG_CONFIGURATION")); + } + + @Test + public void testUNKNOWN_PROVIDER() { + assertNotNull(Msg.valueOf("UNKNOWN_PROVIDER")); + } + + @Test + public void testSERVER_STATE_CHANGE_TIMEOUT() { + assertNotNull(Msg.valueOf("SERVER_STATE_CHANGE_TIMEOUT")); + } + + @Test + public void testSERVER_DELETED() { + assertNotNull(Msg.valueOf("SERVER_DELETED")); + } + + @Test + public void testUNKNOWN_SERVER_STATE() { + assertNotNull(Msg.valueOf("UNKNOWN_SERVER_STATE")); + } + + @Test + public void testCOMPONENT_INITIALIZING() { + assertNotNull(Msg.valueOf("COMPONENT_INITIALIZING")); + } + + @Test + public void testCOMPONENT_INITIALIZED() { + assertNotNull(Msg.valueOf("COMPONENT_INITIALIZED")); + } + + @Test + public void testCOMPONENT_TERMINATING() { + assertNotNull(Msg.valueOf("COMPONENT_TERMINATING")); + } + + @Test + public void testCOMPONENT_TERMINATED() { + assertNotNull(Msg.valueOf("COMPONENT_TERMINATED")); + } + + @Test + public void testIAAS_ADAPTER_UNSUPPORTED_OPERATION() { + assertNotNull(Msg.valueOf("IAAS_ADAPTER_UNSUPPORTED_OPERATION")); + } + + @Test + public void testIAAS_ADAPTER_RPC_CALLED() { + assertNotNull(Msg.valueOf("IAAS_ADAPTER_RPC_CALLED")); + } + + @Test + public void testNO_SERVICE_FOUND() { + assertNotNull(Msg.valueOf("NO_SERVICE_FOUND")); + } + + @Test + public void testCONTEXT_PARAMETERS_DISPLAY() { + assertNotNull(Msg.valueOf("CONTEXT_PARAMETERS_DISPLAY")); + } + + @Test + public void testRESPONSE_PARAMETERS_DISPLAY() { + assertNotNull(Msg.valueOf("RESPONSE_PARAMETERS_DISPLAY")); + } + + @Test + public void testNULL_OR_INVALID_ARGUMENT() { + assertNotNull(Msg.valueOf("NULL_OR_INVALID_ARGUMENT")); + } + + @Test + public void testPROCESSING_REQUEST() { + assertNotNull(Msg.valueOf("PROCESSING_REQUEST")); + } + + @Test + public void testINVALID_SERVICE_REQUEST() { + assertNotNull(Msg.valueOf("INVALID_SERVICE_REQUEST")); + } + + @Test + public void testREGISTERING_SERVICE() { + assertNotNull(Msg.valueOf("REGISTERING_SERVICE")); + } + + @Test + public void testUNREGISTERING_SERVICE() { + assertNotNull(Msg.valueOf("UNREGISTERING_SERVICE")); + } + + @Test + public void testLOADING_PROVIDER_DEFINITIONS() { + assertNotNull(Msg.valueOf("LOADING_PROVIDER_DEFINITIONS")); + } + + @Test + public void testRESTARTING_SERVER() { + assertNotNull(Msg.valueOf("RESTARTING_SERVER")); + } + + @Test + public void testREBUILDING_SERVER() { + assertNotNull(Msg.valueOf("REBUILDING_SERVER")); + } + + @Test + public void testMIGRATING_SERVER() { + assertNotNull(Msg.valueOf("MIGRATING_SERVER")); + } + + @Test + public void testEVACUATING_SERVER() { + assertNotNull(Msg.valueOf("EVACUATING_SERVER")); + } + + @Test + public void testSNAPSHOTING_SERVER() { + assertNotNull(Msg.valueOf("SNAPSHOTING_SERVER")); + } + + @Test + public void testLOOKING_SERVER_UP() { + assertNotNull(Msg.valueOf("LOOKING_SERVER_UP")); + } + + @Test + public void testINVALID_SELF_LINK_URL() { + assertNotNull(Msg.valueOf("INVALID_SELF_LINK_URL")); + } + + @Test + public void testSERVER_FOUND() { + assertNotNull(Msg.valueOf("SERVER_FOUND")); + } + + @Test + public void testSERVER_NOT_FOUND() { + assertNotNull(Msg.valueOf("SERVER_NOT_FOUND")); + } + + @Test + public void testSERVER_OPERATION_EXCEPTION() { + assertNotNull(Msg.valueOf("SERVER_OPERATION_EXCEPTION")); + } + + @Test + public void testMISSING_REQUIRED_PROPERTIES() { + assertNotNull(Msg.valueOf("MISSING_REQUIRED_PROPERTIES")); + } + + @Test + public void testSERVER_ERROR_STATE() { + assertNotNull(Msg.valueOf("SERVER_ERROR_STATE")); + } + + @Test + public void testIMAGE_NOT_FOUND() { + assertNotNull(Msg.valueOf("IMAGE_NOT_FOUND")); + } + + @Test + public void testSTATE_CHANGE_TIMEOUT() { + assertNotNull(Msg.valueOf("STATE_CHANGE_TIMEOUT")); + } + + @Test + public void testSTATE_CHANGE_EXCEPTION() { + assertNotNull(Msg.valueOf("STATE_CHANGE_EXCEPTION")); + } + + @Test + public void testSTOP_SERVER() { + assertNotNull(Msg.valueOf("STOP_SERVER")); + } + + @Test + public void testSTART_SERVER() { + assertNotNull(Msg.valueOf("START_SERVER")); + } + + @Test + public void testRESUME_SERVER() { + assertNotNull(Msg.valueOf("RESUME_SERVER")); + } + + @Test + public void testUNPAUSE_SERVER() { + assertNotNull(Msg.valueOf("UNPAUSE_SERVER")); + } + + @Test + public void testREBUILD_SERVER() { + assertNotNull(Msg.valueOf("REBUILD_SERVER")); + } + + @Test + public void testCONNECTION_FAILED_RETRY() { + assertNotNull(Msg.valueOf("CONNECTION_FAILED_RETRY")); + } + + @Test + public void testCONNECTION_FAILED() { + assertNotNull(Msg.valueOf("CONNECTION_FAILED")); + } + + @Test + public void testSTOPPING_SERVER() { + assertNotNull(Msg.valueOf("STOPPING_SERVER")); + } + + @Test + public void testSTARTING_SERVER() { + assertNotNull(Msg.valueOf("STARTING_SERVER")); + } + + @Test + public void testREBUILD_SERVER_FAILED() { + assertNotNull(Msg.valueOf("REBUILD_SERVER_FAILED")); + } + + @Test + public void testPARAMETER_IS_MISSING() { + assertNotNull(Msg.valueOf("PARAMETER_IS_MISSING")); + } + + @Test + public void testPARAMETER_NOT_NUMERIC() { + assertNotNull(Msg.valueOf("PARAMETER_NOT_NUMERIC")); + } + + @Test + public void testDG_FAILED_RESPONSE() { + assertNotNull(Msg.valueOf("DG_FAILED_RESPONSE")); + } + + @Test + public void testEXCEPTION_CALLING_DG() { + assertNotNull(Msg.valueOf("EXCEPTION_CALLING_DG")); + } + + @Test + public void testGRAPH_NOT_FOUND() { + assertNotNull(Msg.valueOf("GRAPH_NOT_FOUND")); + } + + @Test + public void testDEBUG_GRAPH_RESPONSE_HEADER() { + assertNotNull(Msg.valueOf("DEBUG_GRAPH_RESPONSE_HEADER")); + } + + @Test + public void testDEBUG_GRAPH_RESPONSE_DETAIL() { + assertNotNull(Msg.valueOf("DEBUG_GRAPH_RESPONSE_DETAIL")); + } + + @Test + public void testINVALID_REQUIRED_PROPERTY() { + assertNotNull(Msg.valueOf("INVALID_REQUIRED_PROPERTY")); + } + + @Test + public void testMIGRATE_SERVER_FAILED() { + assertNotNull(Msg.valueOf("MIGRATE_SERVER_FAILED")); + } + + @Test + public void testEVACUATE_SERVER_FAILED() { + assertNotNull(Msg.valueOf("EVACUATE_SERVER_FAILED")); + } + + @Test + public void testEVACUATE_SERVER_REBUILD_FAILED() { + assertNotNull(Msg.valueOf("EVACUATE_SERVER_REBUILD_FAILED")); + } + + @Test + public void testAPPC_TOO_BUSY() { + assertNotNull(Msg.valueOf("APPC_TOO_BUSY")); + } + + @Test + public void testVF_SERVER_BUSY() { + assertNotNull(Msg.valueOf("VF_SERVER_BUSY")); + } + + @Test + public void testVF_ILLEGAL_COMMAND() { + assertNotNull(Msg.valueOf("VF_ILLEGAL_COMMAND")); + } + + @Test + public void testVF_UNDEFINED_STATE() { + assertNotNull(Msg.valueOf("VF_UNDEFINED_STATE")); + } + + @Test + public void testAPPC_NO_RESOURCE_FOUND() { + assertNotNull(Msg.valueOf("APPC_NO_RESOURCE_FOUND")); + } + + @Test + public void testAPPC_EXPIRED_REQUEST() { + assertNotNull(Msg.valueOf("APPC_EXPIRED_REQUEST")); + } + + @Test + public void testAPPC_WORKFLOW_NOT_FOUND() { + assertNotNull(Msg.valueOf("APPC_WORKFLOW_NOT_FOUND")); + } + + @Test + public void testAPPC_INVALID_INPUT() { + assertNotNull(Msg.valueOf("APPC_INVALID_INPUT")); + } + + @Test + public void testAPPC_AUDIT_MSG() { + assertNotNull(Msg.valueOf("APPC_AUDIT_MSG")); + } + + @Test + public void testAAI_CONNECTION_FAILED() { + assertNotNull(Msg.valueOf("AAI_CONNECTION_FAILED")); + } + + @Test + public void testAAI_UPDATE_FAILED() { + assertNotNull(Msg.valueOf("AAI_UPDATE_FAILED")); + } + + @Test + public void testAAI_GET_DATA_FAILED() { + assertNotNull(Msg.valueOf("AAI_GET_DATA_FAILED")); + } + + @Test + public void testAAI_CONNECTION_FAILED_RETRY() { + assertNotNull(Msg.valueOf("AAI_CONNECTION_FAILED_RETRY")); + } + + @Test + public void testAAI_DELETE_FAILED() { + assertNotNull(Msg.valueOf("AAI_DELETE_FAILED")); + } + + @Test + public void testAAI_QUERY_FAILED() { + assertNotNull(Msg.valueOf("AAI_QUERY_FAILED")); + } + + @Test + public void testVNF_CONFIGURED() { + assertNotNull(Msg.valueOf("VNF_CONFIGURED")); + } + + @Test + public void testVNF_CONFIGURATION_STARTED() { + assertNotNull(Msg.valueOf("VNF_CONFIGURATION_STARTED")); + } + + @Test + public void testVNF_CONFIGURATION_FAILED() { + assertNotNull(Msg.valueOf("VNF_CONFIGURATION_FAILED")); + } + + @Test + public void testVNF_TEST_STARTED() { + assertNotNull(Msg.valueOf("VNF_TEST_STARTED")); + } + + @Test + public void testVNF_TESTED() { + assertNotNull(Msg.valueOf("VNF_TESTED")); + } + + @Test + public void testVNF_TEST_FAILED() { + assertNotNull(Msg.valueOf("VNF_TEST_FAILED")); + } + + @Test + public void testVNF_NOT_FOUND() { + assertNotNull(Msg.valueOf("VNF_NOT_FOUND")); + } + + @Test + public void testVNF_HEALTHCECK_FAILED() { + assertNotNull(Msg.valueOf("VNF_HEALTHCECK_FAILED")); + } + + @Test + public void testVM_HEALTHCECK_FAILED() { + assertNotNull(Msg.valueOf("VM_HEALTHCECK_FAILED")); + } + + @Test + public void testSTOP_SERVER_FAILED() { + assertNotNull(Msg.valueOf("STOP_SERVER_FAILED")); + } + + @Test + public void testTERMINATE_SERVER_FAILED() { + assertNotNull(Msg.valueOf("TERMINATE_SERVER_FAILED")); + } + + @Test + public void testTERMINATING_SERVER() { + assertNotNull(Msg.valueOf("TERMINATING_SERVER")); + } + + @Test + public void testTERMINATE_SERVER() { + assertNotNull(Msg.valueOf("TERMINATE_SERVER")); + } + + @Test + public void testMIGRATE_COMPLETE() { + assertNotNull(Msg.valueOf("MIGRATE_COMPLETE")); + } + + @Test + public void testRESTART_COMPLETE() { + assertNotNull(Msg.valueOf("RESTART_COMPLETE")); + } + + @Test + public void testREBUILD_COMPLETE() { + assertNotNull(Msg.valueOf("REBUILD_COMPLETE")); + } + + @Test + public void testSTACK_FOUND() { + assertNotNull(Msg.valueOf("STACK_FOUND")); + } + + @Test + public void testTERMINATING_STACK() { + assertNotNull(Msg.valueOf("TERMINATING_STACK")); + } + + @Test + public void testTERMINATE_STACK() { + assertNotNull(Msg.valueOf("TERMINATE_STACK")); + } + + @Test + public void testSTACK_NOT_FOUND() { + assertNotNull(Msg.valueOf("STACK_NOT_FOUND")); + } + + @Test + public void testSTACK_OPERATION_EXCEPTION() { + assertNotNull(Msg.valueOf("STACK_OPERATION_EXCEPTION")); + } + + @Test + public void testTERMINATE_STACK_FAILED() { + assertNotNull(Msg.valueOf("TERMINATE_STACK_FAILED")); + } + + @Test + public void testCLOSE_CONTEXT_FAILED() { + assertNotNull(Msg.valueOf("CLOSE_CONTEXT_FAILED")); + } + + @Test + public void testSNAPSHOTING_STACK() { + assertNotNull(Msg.valueOf("SNAPSHOTING_STACK")); + } + + @Test + public void testSTACK_SNAPSHOTED() { + assertNotNull(Msg.valueOf("STACK_SNAPSHOTED")); + } + + @Test + public void testRESTORING_STACK() { + assertNotNull(Msg.valueOf("RESTORING_STACK")); + } + + @Test + public void testSTACK_RESTORED() { + assertNotNull(Msg.valueOf("STACK_RESTORED")); + } + + @Test + public void testCHECKING_SERVER() { + assertNotNull(Msg.valueOf("CHECKING_SERVER")); + } + + @Test + public void testMISSING_PARAMETER_IN_REQUEST() { + assertNotNull(Msg.valueOf("MISSING_PARAMETER_IN_REQUEST")); + } + + @Test + public void testCANNOT_ESTABLISH_CONNECTION() { + assertNotNull(Msg.valueOf("CANNOT_ESTABLISH_CONNECTION")); + } + + @Test + public void testAPPC_METRIC_MSG() { + assertNotNull(Msg.valueOf("APPC_METRIC_MSG")); + } + + @Test + public void testINPUT_PAYLOAD_PARSING_FAILED() { + assertNotNull(Msg.valueOf("INPUT_PAYLOAD_PARSING_FAILED")); + } + + @Test + public void testAPPC_EXCEPTION() { + assertNotNull(Msg.valueOf("APPC_EXCEPTION")); + } + + @Test + public void testSSH_DATA_EXCEPTION() { + assertNotNull(Msg.valueOf("SSH_DATA_EXCEPTION")); + } + + @Test + public void testJSON_PROCESSING_EXCEPTION() { + assertNotNull(Msg.valueOf("JSON_PROCESSING_EXCEPTION")); + } + + @Test + public void testSUCCESS_EVENT_MESSAGE() { + assertNotNull(Msg.valueOf("SUCCESS_EVENT_MESSAGE")); + } + + @Test + public void testDEPENDENCY_MODEL_NOT_FOUND() { + assertNotNull(Msg.valueOf("DEPENDENCY_MODEL_NOT_FOUND")); + } + + @Test + public void testINVALID_DEPENDENCY_MODEL() { + assertNotNull(Msg.valueOf("INVALID_DEPENDENCY_MODEL")); + } + + @Test + public void testFAILURE_RETRIEVE_VNFC_DG() { + assertNotNull(Msg.valueOf("FAILURE_RETRIEVE_VNFC_DG")); + } + + @Test + public void testSERVER_NETWORK_ERROR() { + assertNotNull(Msg.valueOf("SERVER_NETWORK_ERROR")); + } + + @Test + public void testHYPERVISOR_DOWN_ERROR() { + assertNotNull(Msg.valueOf("HYPERVISOR_DOWN_ERROR")); + } + + @Test + public void testHYPERVISOR_STATUS_UKNOWN() { + assertNotNull(Msg.valueOf("HYPERVISOR_STATUS_UKNOWN")); + } + + @Test + public void testHYPERVISOR_NETWORK_ERROR() { + assertNotNull(Msg.valueOf("HYPERVISOR_NETWORK_ERROR")); + } + + @Test + public void testAPPLICATION_RESTART_FAILED() { + assertNotNull(Msg.valueOf("APPLICATION_RESTART_FAILED")); + } + + @Test + public void testAPPLICATION_START_FAILED() { + assertNotNull(Msg.valueOf("APPLICATION_START_FAILED")); + } + + @Test + public void testAPPLICATION_STOP_FAILED() { + assertNotNull(Msg.valueOf("APPLICATION_STOP_FAILED")); + } + + @Test + public void testRESTART_APPLICATION() { + assertNotNull(Msg.valueOf("RESTART_APPLICATION")); + } + + @Test + public void testSTART_APPLICATION() { + assertNotNull(Msg.valueOf("START_APPLICATION")); + } + + @Test + public void testSTOP_APPLICATION() { + assertNotNull(Msg.valueOf("STOP_APPLICATION")); + } + + @Test + public void testLCM_OPERATIONS_DISABLED() { + assertNotNull(Msg.valueOf("LCM_OPERATIONS_DISABLED")); + } + + @Test + public void testOAM_OPERATION_EXCEPTION() { + assertNotNull(Msg.valueOf("OAM_OPERATION_EXCEPTION")); + } + + @Test + public void testOAM_OPERATION_ENTERING_MAINTENANCE_MODE() { + assertNotNull(Msg.valueOf("OAM_OPERATION_ENTERING_MAINTENANCE_MODE")); + } + + @Test + public void testOAM_OPERATION_MAINTENANCE_MODE() { + assertNotNull(Msg.valueOf("OAM_OPERATION_MAINTENANCE_MODE")); + } + + @Test + public void testOAM_OPERATION_STARTING() { + assertNotNull(Msg.valueOf("OAM_OPERATION_STARTING")); + } + + @Test + public void testOAM_OPERATION_STARTED() { + assertNotNull(Msg.valueOf("OAM_OPERATION_STARTED")); + } + + @Test + public void testOAM_OPERATION_STOPPING() { + assertNotNull(Msg.valueOf("OAM_OPERATION_STOPPING")); + } + + @Test + public void testOAM_OPERATION_STOPPED() { + assertNotNull(Msg.valueOf("OAM_OPERATION_STOPPED")); + } + + @Test + public void testINVALID_STATE_TRANSITION() { + assertNotNull(Msg.valueOf("INVALID_STATE_TRANSITION")); + } + + @Test + public void testREQUEST_HANDLER_UNAVAILABLE() { + assertNotNull(Msg.valueOf("REQUEST_HANDLER_UNAVAILABLE")); + } + + @Test + public void testOAM_OPERATION_RESTARTING() { + assertNotNull(Msg.valueOf("OAM_OPERATION_RESTARTING")); + } + + @Test + public void testOAM_OPERATION_RESTARTED() { + assertNotNull(Msg.valueOf("OAM_OPERATION_RESTARTED")); + } + + @Test + public void testOAM_OPERATION_INVALID_INPUT() { + assertNotNull(Msg.valueOf("OAM_OPERATION_INVALID_INPUT")); + } +} diff --git a/appc-common/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java b/appc-common/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java new file mode 100644 index 000000000..1238b494b --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.logging; + +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class LoggingConstantsTest { + @Test (expected = IllegalAccessError.class) + public void testConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.class); + } + + @Test (expected = IllegalAccessError.class) + public void testMdcKeysConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.MDCKeys.class); + } + + @Test (expected = IllegalAccessError.class) + public void testStatusCodesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.StatusCodes.class); + } + + @Test (expected = IllegalAccessError.class) + public void testTargetNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetNames.class); + } + + @Test (expected = IllegalAccessError.class) + public void testTargetServiceNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.class); + } + + @Test (expected = IllegalAccessError.class) + public void testAAIServiceNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.AAIServiceNames.class); + } +} \ No newline at end of file diff --git a/appc-common/src/test/java/org/onap/appc/metadata/TestMetadataService.java b/appc-common/src/test/java/org/onap/appc/metadata/TestMetadataService.java new file mode 100644 index 000000000..7316fe8a6 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/metadata/TestMetadataService.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata; + +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import com.sun.rowset.CachedRowSetImpl; +import org.mockito.Mockito; +import org.onap.appc.metadata.impl.MetadataServiceImpl; + +import javax.sql.rowset.CachedRowSet; +import java.sql.SQLException; +import java.util.ArrayList; + +import static org.mockito.Matchers.anyCollection; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; + + + +public class TestMetadataService { + + MetadataServiceImpl metadataService = new MetadataServiceImpl(); + + TestMetadataService() throws SQLException { + DbLibService dbLibService = mock(DbLibService.class); + metadataService.setDbLibService(dbLibService); + CachedRowSet mockRS = new CachedRowSetImpl(); + Mockito.when(dbLibService.getData(anyString(), (ArrayList)anyCollection(), anyString())).thenReturn(mockRS); + } + + +} diff --git a/appc-common/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java b/appc-common/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java new file mode 100644 index 000000000..95f3312cb --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata.objects; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +import static org.onap.appc.metadata.objects.DependencyModelIdentifier.prime; + +public class DependencyModelIdentifierTest { + private static final String vnfType = "vnfType"; + private static final String vnfType2 = "vnfType2"; + private static final String cVersion = "catalogVersion"; + private DependencyModelIdentifier identifier; + private DependencyModelIdentifier identifier1; + private DependencyModelIdentifier identifier2; + private DependencyModelIdentifier identifier3; + + @Before + public void setUp() throws Exception { + identifier = new DependencyModelIdentifier(vnfType, cVersion); + identifier1 = new DependencyModelIdentifier(null, null); + identifier2 = new DependencyModelIdentifier(vnfType, null); + identifier3 = new DependencyModelIdentifier(null, cVersion); + } + + @Test + public void testConstructorAndGetterAndToString() throws Exception { + Assert.assertEquals(vnfType, Whitebox.getInternalState(identifier, "vnfType")); + Assert.assertEquals(cVersion, Whitebox.getInternalState(identifier, "catalogVersion")); + + Assert.assertEquals(vnfType, identifier.getVnfType()); + Assert.assertEquals(cVersion, identifier.getCatalogVersion()); + + Assert.assertEquals(String.format(DependencyModelIdentifier.TO_STRING_FORMAT, vnfType, cVersion), + identifier.toString()); + } + + @Test + public void testHashCode() throws Exception { + Assert.assertEquals((prime + vnfType.hashCode()) * prime + cVersion.hashCode(), identifier.hashCode()); + Assert.assertEquals(prime * prime, identifier1.hashCode()); + Assert.assertEquals((prime + vnfType.hashCode()) * prime , identifier2.hashCode()); + Assert.assertEquals(prime* prime + cVersion.hashCode(), identifier3.hashCode()); + } + + @Test + public void testEquals() throws Exception { + // other object is null + Assert.assertFalse(identifier.equals(null)); + // other object is wrong data type + Assert.assertFalse(identifier.equals("abc")); + + // my vnfType is null + Assert.assertFalse(identifier1.equals(identifier)); + // different vnfType + DependencyModelIdentifier identifier4 = new DependencyModelIdentifier(vnfType2, cVersion); + Assert.assertFalse(identifier.equals(identifier4)); + // same vnfType, my catalogVerson is null + Assert.assertFalse(identifier2.equals(identifier)); + // same vnfType and both catalogVersion are null + identifier4 = new DependencyModelIdentifier(vnfType, null); + Assert.assertTrue(identifier2.equals(identifier4)); + + Assert.assertFalse(identifier.equals(identifier1)); + Assert.assertFalse(identifier.equals(identifier2)); + Assert.assertFalse(identifier.equals(identifier3)); + + Assert.assertFalse(identifier2.equals(identifier1)); + Assert.assertFalse(identifier2.equals(identifier3)); + + + Assert.assertFalse(identifier3.equals(identifier)); + Assert.assertFalse(identifier3.equals(identifier1)); + Assert.assertFalse(identifier3.equals(identifier2)); + + identifier4 = new DependencyModelIdentifier(vnfType, cVersion); + Assert.assertTrue(identifier.equals(identifier4)); + } + +} diff --git a/appc-common/src/test/java/org/onap/appc/pool/CachedElementTest.java b/appc-common/src/test/java/org/onap/appc/pool/CachedElementTest.java new file mode 100644 index 000000000..30e592430 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/pool/CachedElementTest.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.pool.Allocator; +import org.onap.appc.pool.CachedElement; +import org.onap.appc.pool.Destructor; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolDrainedException; +import org.onap.appc.pool.PoolExtensionException; +import org.onap.appc.pool.PoolSpecificationException; +import org.onap.appc.pool.*; + + +public class CachedElementTest implements Allocator, Destructor { + private static final int MIN = 10; + private static final int MAX = 100; + private Pool pool; + private int index = 0; + private int destroyCount = 0; + + /** + * setup + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Before + public void setup() throws PoolSpecificationException { + pool = new Pool<>(MIN, MAX); + } + + /** + * Test state + */ + @Test + public void testAllocator() { + assertNull(pool.getAllocator()); + pool.setAllocator(this); + assertNotNull(pool.getAllocator()); + } + + /** + * Test state + */ + @Test + public void testDestructor() { + assertNull(pool.getDestructor()); + pool.setDestructor(this); + assertNotNull(pool.getDestructor()); + } + + /** + * Test that we can allocate and release elements and that the pool maintains them in MRU order + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { + pool.setAllocator(this); + + assertFalse(pool.isDrained()); + + /* + * Allocate three elements + */ + Testable value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value1.getId())); + assertEquals(1, pool.getAllocatedSize()); + assertEquals(MIN - 1, pool.getFreeSize()); + assertEquals(1, pool.getAllocatedSize()); + + Testable value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); + assertEquals(2, pool.getAllocatedSize()); + assertEquals(MIN - 2, pool.getFreeSize()); + assertEquals(2, pool.getAllocatedSize()); + + Testable value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value3.getId())); + assertEquals(3, pool.getAllocatedSize()); + assertEquals(MIN - 3, pool.getFreeSize()); + assertEquals(3, pool.getAllocatedSize()); + + /* + * Now, release them in the order obtained + */ + pool.release(value1); + pool.release(value2); + pool.release(value3); + + assertEquals(0, pool.getAllocatedSize()); + assertEquals(MIN, pool.getFreeSize()); + + /* + * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used + * to the least recently used. + */ + value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value1.getId())); + + value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); + + value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value3.getId())); + } + + /** + * Test that we can trim the pool to a desired size + * + * @throws PoolDrainedException + * If the caller is trying to release or reserve an element from a drained pool + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws IllegalAccessException + * if this Method object is enforcing Java language access control and the underlying method is + * inaccessible. + * @throws IllegalArgumentException + * if the method is an instance method and the specified object argument is not an instance of the class + * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number + * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or + * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @throws InvocationTargetException + * if the underlying method throws an exception. + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared method
  • + *
  • the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class
  • + *
+ * @throws NoSuchMethodException + * if a matching method is not found. + */ + @SuppressWarnings("nls") + @Test + public void testTrim() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, + PoolDrainedException, PoolExtensionException, NoSuchMethodException, SecurityException { + + pool.setAllocator(this); + int SIZE = 50; + Testable[] array = new Testable[SIZE]; + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < SIZE; i++) { + pool.release(array[i]); + } + assertEquals(0, pool.getAllocatedSize()); + + assertEquals(SIZE, pool.getFreeSize()); + + Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { + Integer.TYPE + }); + trimMethod.setAccessible(true); + trimMethod.invoke(pool, new Object[] { + SIZE - MIN + }); + + assertEquals(MIN, pool.getFreeSize()); + } + + /** + * Test that we can drain a pool containing a mix of free and allocated elements + * + * @throws PoolDrainedException + * If the caller is trying to release or reserve an element from a drained pool + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws IOException + * if an I/O error occurs + */ + @Test + public void testDrain() throws PoolExtensionException, PoolDrainedException, IOException { + int SIZE = 50; + int FREE = 20; + int ALLOC = SIZE - FREE; + + Testable[] array = new Testable[SIZE]; + pool.setAllocator(this); + pool.setDestructor(this); + + assertFalse(pool.isDrained()); + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < FREE; i++) { + array[i].close(); + } + assertEquals(ALLOC, pool.getAllocatedSize()); + assertEquals(FREE, pool.getFreeSize()); + + pool.drain(); + assertEquals(0, pool.getFreeSize()); + assertEquals(0, pool.getAllocatedSize()); + assertTrue(pool.isDrained()); + + assertEquals(SIZE, destroyCount); + } + + /** + * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) + */ + @Override + public Testable allocate(Pool pool) { + Testable element = new Element(index++); + Testable ce = CachedElement.newInstance(pool, element, new Class[] { + Testable.class + }); + return ce; + } + + /** + * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) + */ + @Override + public void destroy(Testable obj, Pool pool) { + destroyCount++; + } +} diff --git a/appc-common/src/test/java/org/onap/appc/pool/Element.java b/appc-common/src/test/java/org/onap/appc/pool/Element.java new file mode 100644 index 000000000..877fab2aa --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/pool/Element.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.IOException; + +public class Element implements Testable { + private boolean closed; + private Integer id; + + public Element(int id) { + this.id = Integer.valueOf(id); + closed = false; + } + + @Override + public boolean equals(Object obj) { + boolean result = false; + if (obj instanceof Element) { + Element other = (Element) obj; + result = this.id.equals(other.id); + } + + return result; + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + /** + * @see java.io.Closeable#close() + */ + @Override + public void close() throws IOException { + closed = true; + } + + @Override + public Boolean isClosed() { + return Boolean.valueOf(closed); + } + + @Override + public String toString() { + return Integer.toString(id); + } + + @Override + public Integer getId() { + return id; + } +} diff --git a/appc-common/src/test/java/org/onap/appc/pool/PoolTest.java b/appc-common/src/test/java/org/onap/appc/pool/PoolTest.java new file mode 100644 index 000000000..db9a2e615 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/pool/PoolTest.java @@ -0,0 +1,323 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.pool.Allocator; +import org.onap.appc.pool.Destructor; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolDrainedException; +import org.onap.appc.pool.PoolExtensionException; +import org.onap.appc.pool.PoolSpecificationException; +import org.onap.appc.pool.*; + + +public class PoolTest implements Allocator, Destructor { + + private Pool pool; + private static final int MIN = 10; + private static final int MAX = 100; + private int index = 0; + private int destroyCount = 0; + + /** + * Set up the test by allocating a pool with MIN-MAX size (bounded pool) + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Before + public void setup() throws PoolSpecificationException { + pool = new Pool<>(MIN, MAX); + index = 0; + destroyCount = 0; + } + + /** + * Test that trying to construct a pool with a bad minimum throws an exception + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidMinSize() throws PoolSpecificationException { + pool = new Pool<>(-1, MAX); + } + + /** + * Test that trying to construct a pool with a bad maximum throws an exception + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidMaxSize() throws PoolSpecificationException { + pool = new Pool<>(MIN, -1); + } + + /** + * Test creation of a pool where max is less than min fails + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidSizeRange() throws PoolSpecificationException { + pool = new Pool<>(MAX, MIN); + } + + /** + * Test state + */ + @Test + public void testMinPool() { + assertEquals(MIN, pool.getMinPool()); + } + + /** + * Test state + */ + @Test + public void testMaxPool() { + assertEquals(MAX, pool.getMaxPool()); + } + + /** + * Test state + */ + @Test + public void testAllocator() { + assertNull(pool.getAllocator()); + pool.setAllocator(this); + assertNotNull(pool.getAllocator()); + } + + /** + * Test state + */ + @Test + public void testDestructor() { + assertNull(pool.getDestructor()); + pool.setDestructor(this); + assertNotNull(pool.getDestructor()); + } + + /** + * Test that we can allocate and release elements and that the pool maintains them in MRU order + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { + pool.setAllocator(this); + + assertFalse(pool.isDrained()); + + /* + * Allocate three elements + */ + Testable value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 1), value1.getId()); + assertEquals(1, pool.getAllocatedSize()); + assertEquals(MIN - 1, pool.getFreeSize()); + assertEquals(1, pool.getAllocatedSize()); + + Testable value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), value2.getId()); + assertEquals(2, pool.getAllocatedSize()); + assertEquals(MIN - 2, pool.getFreeSize()); + assertEquals(2, pool.getAllocatedSize()); + + Testable value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 3), value3.getId()); + assertEquals(3, pool.getAllocatedSize()); + assertEquals(MIN - 3, pool.getFreeSize()); + assertEquals(3, pool.getAllocatedSize()); + + /* + * Now, release them in the order obtained + */ + pool.release(value1); + pool.release(value2); + pool.release(value3); + + assertEquals(0, pool.getAllocatedSize()); + assertEquals(MIN, pool.getFreeSize()); + + /* + * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used + * to the least recently used. + */ + value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 3), value1.getId()); + + value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), value2.getId()); + + value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 1), value3.getId()); + } + + /** + * Test that we can trim the pool to a desired size + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws NoSuchMethodException + * if a matching method is not found. + * @throws SecurityException + * if the request is denied. + * @throws IllegalAccessException + * if this Method object is enforcing Java language access control and the underlying method is + * inaccessible. + * @throws IllegalArgumentException + * if the method is an instance method and the specified object argument is not an instance of the class + * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number + * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or + * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @throws InvocationTargetException + * if the underlying method throws an exception. + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @SuppressWarnings("nls") + @Test + public void testTrim() throws PoolExtensionException, NoSuchMethodException, SecurityException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, PoolDrainedException { + pool.setAllocator(this); + int SIZE = 50; + Proxy[] array = new Proxy[SIZE]; + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = (Proxy) pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < SIZE; i++) { + pool.release((Testable) array[i]); + } + assertEquals(0, pool.getAllocatedSize()); + + assertEquals(SIZE, pool.getFreeSize()); + + Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { + Integer.TYPE + }); + trimMethod.setAccessible(true); + trimMethod.invoke(pool, new Object[] { + SIZE - MIN + }); + + assertEquals(MIN, pool.getFreeSize()); + } + + /** + * Test that we can drain a pool containing a mix of free and allocated elements + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testDrain() throws PoolExtensionException, PoolDrainedException { + int SIZE = 50; + int FREE = 20; + int ALLOC = SIZE - FREE; + + Proxy[] array = new Proxy[SIZE]; + pool.setAllocator(this); + pool.setDestructor(this); + + assertFalse(pool.isDrained()); + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = (Proxy) pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < FREE; i++) { + pool.release((Testable) array[i]); + } + assertEquals(ALLOC, pool.getAllocatedSize()); + assertEquals(FREE, pool.getFreeSize()); + + pool.drain(); + assertEquals(0, pool.getFreeSize()); + assertEquals(0, pool.getAllocatedSize()); + assertTrue(pool.isDrained()); + + assertEquals(SIZE, destroyCount); + } + + /** + * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) + */ + @Override + public void destroy(Testable obj, Pool pool) { + destroyCount++; + try { + obj.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) + */ + @Override + public Testable allocate(Pool pool) { + Testable e = new Element(index++); + + return e; + } +} diff --git a/appc-common/src/test/java/org/onap/appc/pool/Testable.java b/appc-common/src/test/java/org/onap/appc/pool/Testable.java new file mode 100644 index 000000000..fb2fa75ef --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/pool/Testable.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.pool; + +import java.io.Closeable; + +public interface Testable extends Closeable { + + Integer getId(); + + Boolean isClosed(); +} + diff --git a/appc-common/src/test/java/org/onap/appc/util/TestJsonUtil.java b/appc-common/src/test/java/org/onap/appc/util/TestJsonUtil.java new file mode 100644 index 000000000..270f90f05 --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/util/TestJsonUtil.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.util.JsonUtil; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import static org.junit.Assert.*; + + + +public class TestJsonUtil { + + @Test + public void testConvertJsonStringToFlatMap() { + try { + String jsonString = "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; + Map flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); + assertNotNull(flatMap); + Map expectedMap = new HashMap<>(); + expectedMap.put("A","A-value"); + expectedMap.put("B.C","B.C-value"); + expectedMap.put("B.D","B.D-value"); + assertEquals(expectedMap,flatMap); + } catch (IOException e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + @Test + public void testConvertJsonStringToFlatMapWithInnerJson() { + try { + String jsonString = "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}"; + Map flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); + assertNotNull(flatMap); + Map expectedMap = new HashMap<>(); + expectedMap.put("A","A-value"); + expectedMap.put("B","{\"C\":\"C-value\",\"D\":\"D-value\"}"); + assertEquals(expectedMap,flatMap); + } catch (IOException e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } +} diff --git a/appc-common/src/test/java/org/onap/appc/util/TestStringHelper.java b/appc-common/src/test/java/org/onap/appc/util/TestStringHelper.java new file mode 100644 index 000000000..06957cf2d --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/util/TestStringHelper.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.junit.Test; +import org.onap.appc.util.StringHelper; + + +public class TestStringHelper { + + @Test + public void testAsListWithNullList() { + String value = StringHelper.asList((String[]) null); + assertNotNull(value); + assertEquals("[]", value); + } + + @Test + public void testAsListWithEmptyList() { + String value = StringHelper.asList(new String[] {}); + assertNotNull(value); + assertEquals("[]", value); + } + + @Test + public void testAsListWithSingleValue() { + String value = StringHelper.asList("one"); + assertNotNull(value); + assertEquals("[one]", value); + } + + @Test + public void testAsListWithTwoValues() { + String value = StringHelper.asList("one", "two"); + assertNotNull(value); + assertEquals("[one,two]", value); + } + + @Test + public void testAsListWithFiveValues() { + String value = StringHelper.asList("one", "two", "three", "four", "five"); + assertNotNull(value); + assertEquals("[one,two,three,four,five]", value); + } + + @Test + public void testPropertiesToString() { + String key1 = "key1"; + String val1 = "val1"; + String key2 = "key2"; + String val2 = "val2"; + + assertEquals(null, StringHelper.propertiesToString(null)); + + Properties props = new Properties(); + + String result = StringHelper.propertiesToString(props); + assertNotNull(result); + assertEquals("[ ]", result); + + props.setProperty(key1, val1); + result = StringHelper.propertiesToString(props); + assertNotNull(result); + assertTrue(result.contains(key1)); + assertTrue(result.contains(val1)); + assertTrue(result.lastIndexOf(",") < result.length() - 3); // No trailing comma + + props.setProperty(key2, val2); + result = StringHelper.propertiesToString(props); + assertNotNull(result); + assertTrue(result.contains(key1)); + assertTrue(result.contains(val1)); + assertTrue(result.contains(key2)); + assertTrue(result.contains(val2)); + assertTrue(result.lastIndexOf(",") < result.length() - 3); // No trailing comma + } +} diff --git a/appc-common/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java b/appc-common/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java new file mode 100644 index 000000000..06c27d0dd --- /dev/null +++ b/appc-common/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.util.StructuredPropertyHelper; +import org.onap.appc.util.StructuredPropertyHelper.Node; + +/** + * This class is used to test the structured property helper class. + *

+ * A structured property is one where the name is constructed from a compound set of elements, concatenated by a period, + * and optionally being enumerated using a sequence number suffix. A java package name is an example of a structured + * name, where each element of the name represents a directory or name in the namespace hierarchy. Property names may + * also be structured. This class constructs a graph of the structured properties and this test case is used to verify + * its operation. + *

+ * + */ +public class TestStructuredPropertyHelper { + + /** + * The properties to be parsed + */ + private Properties properties; + + /** + * The result of parsing the properties + */ + private List nodes = new ArrayList<>(); + + /** + * Initialize the test environment + */ + @SuppressWarnings("nls") + @Before + public void setup() { + nodes.clear(); + + properties = new Properties(); + + properties.setProperty("provider1.name", "provider1Name"); + properties.setProperty("provider1.type", "provider1type"); + properties.setProperty("provider1.URL", "provider1URL"); + properties.setProperty("provider2.name", "provider2Name"); + properties.setProperty("provider2.type", "provider2type"); + properties.setProperty("provider2.URL", "provider2URL"); + properties.setProperty("provider003.name", "provider3Name"); + properties.setProperty("provider003.type", "provider3type"); + properties.setProperty("provider003.URL", "provider3URL"); + + properties.setProperty("node1.level1.value1.key", "1.1.1"); + properties.setProperty("node1.level1.value2.key", "1.1.2"); + properties.setProperty("node1.level1.value3.key", "1.1.3"); + properties.setProperty("node1.level2.value1.key", "1.2.1"); + properties.setProperty("node1.level2.value2.key", "1.2.2"); + properties.setProperty("node1.level2.value3.key", "1.2.3"); + properties.setProperty("node1.level3.value1.key", "1.3.1"); + properties.setProperty("node1.level3.value2.key", "1.3.2"); + properties.setProperty("node1.level3.value3.key", "1.3.3"); + properties.setProperty("node2.level1.value1.key", "2.1.1"); + properties.setProperty("node2.level1.value2.key", "2.1.2"); + properties.setProperty("node2.level1.value3.key", "2.1.3"); + properties.setProperty("node2.level2.value1.key", "2.2.1"); + properties.setProperty("node2.level2.value2.key", "2.2.2"); + properties.setProperty("node2.level2.value3.key", "2.2.3"); + properties.setProperty("node2.level3.value1.key", "2.3.1"); + properties.setProperty("node2.level3.value2.key", "2.3.2"); + properties.setProperty("node2.level3.value3.key", "2.3.3"); + properties.setProperty("node3.level1.value1.key", "3.1.1"); + properties.setProperty("node3.level1.value2.key", "3.1.2"); + properties.setProperty("node3.level1.value3.key", "3.1.3"); + properties.setProperty("node3.level2.value1.key", "3.2.1"); + properties.setProperty("node3.level2.value2.key", "3.2.2"); + properties.setProperty("node3.level2.value3.key", "3.2.3"); + properties.setProperty("node3.level3.value1.key", "3.3.1"); + properties.setProperty("node3.level3.value2.key", "3.3.2"); + properties.setProperty("node3.level3.value3.key", "3.3.3"); + + properties.setProperty("other.property", "bogus"); + properties.setProperty("yet.another.property", "bogus"); + properties.setProperty("simpleProperty", "bogus"); + + } + + /** + * Test that a simple namespace works + */ + @SuppressWarnings("nls") + @Test + public void testSimpleNamespace() { + nodes = StructuredPropertyHelper.getStructuredProperties(properties, "provider"); + + assertNotNull(nodes); + assertFalse(nodes.isEmpty()); + + assertEquals(3, nodes.size()); + + List children; + for (Node node : nodes) { + switch (node.getName()) { + case "provider1": + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider1URL", child.getValue()); + break; + case "type": + assertEquals("provider1type", child.getValue()); + break; + case "name": + assertEquals("provider1Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + case "provider2": + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider2URL", child.getValue()); + break; + case "type": + assertEquals("provider2type", child.getValue()); + break; + case "name": + assertEquals("provider2Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + case "provider3": + /* + * Note that the helper normalizes any ordinal suffixes (003 became 3) + */ + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider3URL", child.getValue()); + break; + case "type": + assertEquals("provider3type", child.getValue()); + break; + case "name": + assertEquals("provider3Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + default: + fail("Unknown provider " + node.toString()); + } + } + // System.out.println(nodes); + } + + /** + * Test a multi-dimensional namespace (3X3X3) + */ + @SuppressWarnings("nls") + @Test + public void testMultiLevelNamespace() { + nodes = StructuredPropertyHelper.getStructuredProperties(properties, "node"); + + assertNotNull(nodes); + assertFalse(nodes.isEmpty()); + + assertEquals(3, nodes.size()); + for (Node node : nodes) { + assertNull(node.getValue()); + List children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + assertNull(child.getValue()); + List grandChildren = child.getChildren(); + assertNotNull(grandChildren); + assertEquals(3, grandChildren.size()); + for (Node greatGrandChild : grandChildren) { + assertNull(greatGrandChild.getValue()); + List greatGrandChildren = greatGrandChild.getChildren(); + assertNotNull(greatGrandChildren); + assertEquals(1, greatGrandChildren.size()); + } + } + } + // System.out.println(nodes); + } +} diff --git a/appc-common/src/test/java/org/openecomp/appc/cache/CacheStrategiesTest.java b/appc-common/src/test/java/org/openecomp/appc/cache/CacheStrategiesTest.java deleted file mode 100644 index 41ceb4303..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/cache/CacheStrategiesTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache; - -import org.junit.Assert; -import org.junit.Test; - -public class CacheStrategiesTest { - private CacheStrategies cacheStrategies = CacheStrategies.LRU; - - @Test - public void testName() throws Exception { - Assert.assertEquals("Should have name LRU", "LRU", cacheStrategies.name()); - } - - @Test - public void testToString() throws Exception { - Assert.assertEquals("Should return String LRU", "LRU", cacheStrategies.toString()); - } - - @Test - public void testEquals() throws Exception { - Assert.assertTrue(cacheStrategies.equals(CacheStrategies.LRU)); - Assert.assertFalse(cacheStrategies.equals(null)); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/cache/impl/LRUCacheTest.java b/appc-common/src/test/java/org/openecomp/appc/cache/impl/LRUCacheTest.java deleted file mode 100644 index 3f4233d86..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/cache/impl/LRUCacheTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import org.junit.Assert; -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -import java.util.Map; - -public class LRUCacheTest { - - @Test - public void testConstructor() throws Exception { - LRUCache cache = new LRUCache(20); - Map internalMap = Whitebox.getInternalState(cache, "map"); - Assert.assertTrue(internalMap != null); - Assert.assertTrue(internalMap.size() == 0); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAndPutObject() throws Exception { - LRUCache cache = new LRUCache(20); - - String key = "testing key"; - Assert.assertTrue(cache.getObject(key) == null); - - String value = "testing value"; - cache.putObject(key, value); - Map internalMap = Whitebox.getInternalState(cache, "map"); - Assert.assertTrue(internalMap.containsKey(key)); - Assert.assertTrue(internalMap.containsValue(value)); - Assert.assertTrue(internalMap.size() == 1); - - Assert.assertEquals(value, cache.getObject(key)); - } - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheFactoryTest.java b/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheFactoryTest.java deleted file mode 100644 index 386118025..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheFactoryTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.appc.cache.CacheStrategies; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import static org.mockito.Mockito.mock; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MetadataCacheFactory.class, MetadataCacheImpl.class}) -public class MetadataCacheFactoryTest { - @Test - public void testConstructor() throws Exception { - Whitebox.invokeConstructor(MetadataCacheFactory.class); - } - - @Test - public void testGetInstance() throws Exception { - Assert.assertTrue("Should not return null", MetadataCacheFactory.getInstance() != null); - Assert.assertEquals("Should always return the same object", - MetadataCacheFactory.getInstance(), MetadataCacheFactory.getInstance()); - } - - @Test - public void testGetMetadataCacheWithNoArgument() throws Exception { - MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); - PowerMockito.whenNew(MetadataCacheImpl.class).withNoArguments().thenReturn(mockImpl); - Assert.assertEquals(mockImpl, MetadataCacheFactory.getInstance().getMetadataCache()); - } - - @Test - public void testGetMetadataCacheWithArgument() throws Exception { - CacheStrategies cacheStrategies = CacheStrategies.LRU; - MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); - PowerMockito.whenNew(MetadataCacheImpl.class).withArguments(cacheStrategies).thenReturn(mockImpl); - Assert.assertEquals(mockImpl, MetadataCacheFactory.getInstance().getMetadataCache(cacheStrategies)); - } - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheImplTest.java b/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheImplTest.java deleted file mode 100644 index c68fb48dc..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/cache/impl/MetadataCacheImplTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.cache.impl; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.cache.CacheStrategies; -import org.powermock.reflect.Whitebox; - -import static org.mockito.Mockito.spy; - -public class MetadataCacheImplTest { - @Test - public void testConstructor() throws Exception { - // test without parameter - MetadataCacheImpl impl = new MetadataCacheImpl<>(); - Assert.assertTrue("Should have initialized strategy", - Whitebox.getInternalState(impl, "strategy") != null); - - // test with parameter - impl = new MetadataCacheImpl<>(CacheStrategies.LRU); - Assert.assertTrue("Should have initialized strategy", - Whitebox.getInternalState(impl, "strategy") != null); - - impl = new MetadataCacheImpl<>(null); - Assert.assertTrue("Should not initialized strategy", - Whitebox.getInternalState(impl, "strategy") == null); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAndPutObject() throws Exception { - MetadataCacheImpl impl = spy(new MetadataCacheImpl<>()); - - String key = "testing key"; - Assert.assertTrue(impl.getObject(key) == null); - - String value = "testing value"; - impl.putObject(key, value); - Assert.assertEquals(value, impl.getObject(key)); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/concurrent/TestSignal.java b/appc-common/src/test/java/org/openecomp/appc/concurrent/TestSignal.java deleted file mode 100644 index e86fe54a1..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/concurrent/TestSignal.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.concurrent; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.TimeoutException; - -import org.junit.Test; -import org.onap.appc.concurrent.Signal; - -public class TestSignal { - - private static final DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS"); - public static final String SIGNAL_READY = "READY"; - public static final String SIGNAL_SHUTDOWN = "SHUTDOWN"; - - @Test - public void TestSimpleSignal() throws TimeoutException { - - Signal mySignal = new Signal(Thread.currentThread()); - mySignal.setTimeout(5000L); - Fred fred = new Fred(mySignal); - Thread t1 = new Thread(fred); - - /* - * Verify that fred is dead, then start him and wait for him to signal us he is ready to proceed - */ - assertFalse(t1.isAlive()); - t1.start(); - System.out.println(formatter.format(new Date()) + " MAIN: Waiting for Ready..."); - mySignal.waitFor(SIGNAL_READY); - System.out.println(formatter.format(new Date()) + " MAIN: Signal Ready received"); - - /* - * Verify that fred is still alive and we will sleep for a while (simulate doing things) - */ - assertTrue(t1.isAlive()); - try { - Thread.sleep(250L); - } catch (InterruptedException e) { - // ignored - } - - /* - * Verify that fred is still alive and signal him to shutdown - */ - assertTrue(t1.isAlive()); - System.out.println(formatter.format(new Date()) + " MAIN: Signaling shutdown"); - fred.getSignal().signal(SIGNAL_SHUTDOWN); - - /* - * Wait a little bit - */ - try { - Thread.sleep(250L); - } catch (InterruptedException e) { - // ignored - } - - /* - * Verify that fred is dead now and that he completed normally - */ - System.out.println(formatter.format(new Date()) + " MAIN: Shutting down..."); - assertFalse(t1.isAlive()); - assertTrue(fred.isCompleted()); - } - - public class Fred implements Runnable { - private Signal signal; - private Signal parentSignal; - private boolean completed = false; - - public Fred(Signal parentSignal) { - this.parentSignal = parentSignal; - } - - @Override - public void run() { - signal = new Signal(Thread.currentThread()); - signal.setTimeout(5000L); - try { - Thread.sleep(250L); - } catch (InterruptedException e) { - // Ignore - } - - System.out.println(formatter.format(new Date()) + " FRED: Signaling ready..."); - parentSignal.signal(SIGNAL_READY); - - try { - System.out.println(formatter.format(new Date()) + " FRED: Waiting for shutdown..."); - signal.waitFor(SIGNAL_SHUTDOWN); - System.out.println(formatter.format(new Date()) + " FRED: Received shutdown"); - completed = true; - } catch (TimeoutException e) { - e.printStackTrace(); - } - } - - public boolean isCompleted() { - return completed; - } - - public Signal getSignal() { - return signal; - } - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/configuration/DefaultConfigurationTest.java b/appc-common/src/test/java/org/openecomp/appc/configuration/DefaultConfigurationTest.java deleted file mode 100644 index a423eae81..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/configuration/DefaultConfigurationTest.java +++ /dev/null @@ -1,337 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.configuration; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.powermock.reflect.Whitebox; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.mockito.Mockito.mock; - -public class DefaultConfigurationTest { - private static final String propKey1 = "testKey1"; - private static final String propKey2 = "testKey2"; - private static final String propValue1 = "testValue1"; - private static final String propValue2 = "testValue2"; - - private Properties prop = new Properties(); - private DefaultConfiguration defaultConfiguration; - - @Before - public void setUp() throws Exception { - prop.setProperty(propKey1, propValue1); - prop.setProperty(propKey2, propValue2); - - defaultConfiguration = new DefaultConfiguration(); - } - - @Test - public void testClear() throws Exception { - Whitebox.setInternalState(defaultConfiguration, "properties", prop); - defaultConfiguration.clear(); - Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); - Assert.assertTrue("internal properties should be cleared", internalProp.isEmpty()); - } - - @Test - public void testClone() throws Exception { - Object clonedObject = defaultConfiguration.clone(); - Assert.assertTrue("Should be DefaultConfiguration", clonedObject instanceof DefaultConfiguration); - Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); - Properties clonedInternalProp = Whitebox.getInternalState(clonedObject, "properties"); - Assert.assertEquals(internalProp, clonedInternalProp); - } - - @Test - public void testEquals() throws Exception { - // test compare with null - Assert.assertFalse(defaultConfiguration.equals(null)); - // test with non-DefaultConfiguration object - Assert.assertFalse(defaultConfiguration.equals("abc")); - - // test with not match DefaultConfiguration object - defaultConfiguration.setProperties(prop); - DefaultConfiguration newConfig = new DefaultConfiguration(); - Assert.assertFalse(defaultConfiguration.equals(newConfig)); - - // test with matching DefaultConfiguration object - newConfig.setProperties(prop); - Assert.assertTrue(defaultConfiguration.equals(newConfig)); - } - - @Test - public void testSetPropAndGetBooleanProperty() throws Exception { - String booleanKey = "booleanKey"; - // test default value - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); - // test match value true - defaultConfiguration.setProperty(booleanKey, "true"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); - defaultConfiguration.setProperty(booleanKey, "True"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); - defaultConfiguration.setProperty(booleanKey, "TrUe"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); - // test not matching true values - defaultConfiguration.setProperty(booleanKey, "false"); - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); - defaultConfiguration.setProperty(booleanKey, "abc"); - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); - } - - @Test - public void testSetPropAndGetBooleanPropertyWithDefaultValue() throws Exception { - String booleanKey = "booleanKey"; - // test default value - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, false)); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, true)); - // test match value true - defaultConfiguration.setProperty(booleanKey, "true"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); - defaultConfiguration.setProperty(booleanKey, "True"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); - defaultConfiguration.setProperty(booleanKey, "TrUe"); - Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); - // test not matching true values - defaultConfiguration.setProperty(booleanKey, "false"); - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); - defaultConfiguration.setProperty(booleanKey, "abc"); - Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); - } - - @Test - public void testSetPropAndGetDoubleProperty() throws Exception { - String doubleKey = "doubleKey"; - // test default value - Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); - // test NumberFormatException - defaultConfiguration.setProperty(doubleKey, "abc"); - Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); - // test normal - defaultConfiguration.setProperty(doubleKey, "1.1"); - Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey)); - } - - @Test - public void testSetPropAndGetDoublePropertyWithDefaultValue() throws Exception { - String doubleKey = "doubleKey"; - // test default value - Assert.assertTrue(2.2 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); - // test NumberFormatException - defaultConfiguration.setProperty(doubleKey, "abc"); - Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); - // test normal - defaultConfiguration.setProperty(doubleKey, "1.1"); - Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); - } - - @Test - public void testSetPropAndGetIntegerProperty() throws Exception { - String integerKey = "integerKey"; - // test default value - Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); - // test NumberFormatException - defaultConfiguration.setProperty(integerKey, "abc"); - Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); - // test normal - defaultConfiguration.setProperty(integerKey, "100"); - Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey)); - } - - @Test - public void testSetPropAndGetIntegerPropertyWithDefaultValue() throws Exception { - String integerKey = "integerKey"; - // test default value - Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 100)); - // test NumberFormatException - defaultConfiguration.setProperty(integerKey, "abc"); - Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey, 100)); - // test normal - defaultConfiguration.setProperty(integerKey, "100"); - Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 10)); - } - - @Test - public void testSetPropAndGetLongProperty() throws Exception { - String longKey = "longKey"; - // test default value - Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); - // test NumberFormatException - defaultConfiguration.setProperty(longKey, "abc"); - Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); - // test normal - defaultConfiguration.setProperty(longKey, "100"); - Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey)); - } - - @Test - public void testSetPropAndGetLongPropertyWithDefaultVaue() throws Exception { - String longKey = "longKey"; - // test default value - Assert.assertTrue(10 == defaultConfiguration.getLongProperty(longKey, 10)); - // test NumberFormatException - defaultConfiguration.setProperty(longKey, "abc"); - Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey, 10)); - // test normal - defaultConfiguration.setProperty(longKey, "100"); - Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey, 10)); - } - - @Test - public void testSetAndGetProperties() throws Exception { - Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); - Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); - - defaultConfiguration.setProperties(prop); - internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); - Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); - } - - @Test - public void testSetAndGetProperty() throws Exception { - String key = "key"; - // test default value - Assert.assertTrue(null == defaultConfiguration.getProperty(key)); - // test normal - defaultConfiguration.setProperty(key, "abc"); - Assert.assertEquals("abc", defaultConfiguration.getProperty(key)); - } - - @Test - public void testSetPropAndGetPropertyWithDefaultValue() throws Exception { - String key = "key"; - // test default value - Assert.assertTrue(null == defaultConfiguration.getProperty(key, null)); - Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abc")); - // test normal - defaultConfiguration.setProperty(key, "abc"); - Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abcd")); - } - - @Test - public void testHashCode() throws Exception { - Properties properties = null; - Whitebox.setInternalState(defaultConfiguration, "properties", properties); - Assert.assertEquals(0, defaultConfiguration.hashCode()); - - - Whitebox.setInternalState(defaultConfiguration, "properties", prop); - Assert.assertEquals(prop.hashCode(), defaultConfiguration.hashCode()); - } - - @Test - public void testIsPropertyDefined() throws Exception { - String key = "key"; - // test not exist - Assert.assertFalse(defaultConfiguration.isPropertyDefined(key)); - // test exist - defaultConfiguration.setProperty(key, "abc"); - Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); - } - - @Test - public void testIsValidBoolean() throws Exception { - String key = "key"; - // test not exist - Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); - // test exist with invalid - defaultConfiguration.setProperty(key, "abc"); - Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); - // test exist with valid - defaultConfiguration.setProperty(key, "True"); - Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); - defaultConfiguration.setProperty(key, "FaLse"); - Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); - } - - @Test - public void testIsValidDouble() throws Exception { - String key = "key"; - // test not exist - Assert.assertFalse(defaultConfiguration.isValidDouble(key)); - // test exist with invalid - defaultConfiguration.setProperty(key, "abc"); - Assert.assertFalse(defaultConfiguration.isValidDouble(key)); - // test exist with valid - defaultConfiguration.setProperty(key, "2"); - Assert.assertTrue(defaultConfiguration.isValidDouble(key)); - defaultConfiguration.setProperty(key, "3.45"); - Assert.assertTrue(defaultConfiguration.isValidDouble(key)); - } - - @Test - public void testIsValidInteger() throws Exception { - String key = "key"; - // test not exist - Assert.assertFalse(defaultConfiguration.isValidInteger(key)); - // test exist with invalid - defaultConfiguration.setProperty(key, "abc"); - Assert.assertFalse(defaultConfiguration.isValidInteger(key)); - defaultConfiguration.setProperty(key, "3.45"); - Assert.assertFalse(defaultConfiguration.isValidInteger(key)); - // test exist with valid - defaultConfiguration.setProperty(key, "2"); - Assert.assertTrue(defaultConfiguration.isValidInteger(key)); - } - - @Test - public void testIsValidLong() throws Exception { - String key = "key"; - // test not exist - Assert.assertFalse(defaultConfiguration.isValidLong(key)); - // test exist with invalid - defaultConfiguration.setProperty(key, "abc"); - Assert.assertFalse(defaultConfiguration.isValidLong(key)); - defaultConfiguration.setProperty(key, "3.45"); - Assert.assertFalse(defaultConfiguration.isValidLong(key)); - // test exist with valid - defaultConfiguration.setProperty(key, "2"); - Assert.assertTrue(defaultConfiguration.isValidLong(key)); - } - - @Test - public void testSetPropertiesWithInputStream() throws Exception { - InputStream mockIS = mock(InputStream.class); - defaultConfiguration.setProperties(mockIS); - - Properties mockProp = mock(Properties.class); - Mockito.doThrow(new IOException("testing exception")).when(mockProp).load(mockIS); - Whitebox.setInternalState(defaultConfiguration, "properties", mockProp); - defaultConfiguration.setProperties(mockIS); - // Should come here without exception - } - - @Test - public void testToString() throws Exception { - Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); - Assert.assertEquals(String.format("Configuration: %d properties, keys:[%s]", - internalProp.size(), internalProp.keySet().toString()), defaultConfiguration.toString()); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/encryption/TestEncryption.java b/appc-common/src/test/java/org/openecomp/appc/encryption/TestEncryption.java deleted file mode 100644 index aa9664d2e..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/encryption/TestEncryption.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.encryption; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import org.junit.Test; -import org.onap.appc.encryption.EncryptionTool; - -public class TestEncryption { - - @Test - public void testEncryptionDecryption() { - String plain = "AppC"; - String enc = EncryptionTool.getInstance().encrypt(plain); - assertNotEquals(plain, enc); - String dec = EncryptionTool.getInstance().decrypt(enc); - assertNotEquals(enc, dec); - assertEquals(plain, dec); - System.out.println(String.format("%s = [%s]", plain, enc)); - } - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/exceptions/APPCExceptionTest.java b/appc-common/src/test/java/org/openecomp/appc/exceptions/APPCExceptionTest.java deleted file mode 100644 index a9611a2df..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/exceptions/APPCExceptionTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -import org.junit.Assert; -import org.junit.Test; -import org.powermock.reflect.Whitebox; - - -public class APPCExceptionTest { - - @Test - public void testConstructorNoArgument() throws Exception { - APPCException appcException = new APPCException(); - Assert.assertTrue(appcException.getCause() == null); - Assert.assertTrue(appcException.getLocalizedMessage() == null); - Assert.assertTrue(appcException.getMessage() == null); - } - - @Test - public void testConstructorWithMessaqge() throws Exception { - String message = "testing message"; - APPCException appcException = new APPCException(message); - Assert.assertTrue(appcException.getCause() == null); - Assert.assertEquals(message, appcException.getLocalizedMessage()); - Assert.assertEquals(message, appcException.getMessage()); - } - - @Test - public void testConstructorWithThrowable() throws Exception { - String message = "testing message"; - Throwable throwable = new Throwable(message); - APPCException appcException = new APPCException(throwable); - Assert.assertEquals(throwable, appcException.getCause()); - Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); - Assert.assertTrue(appcException.getMessage().contains(message)); - } - - @Test - public void testConstructorWithMessageAndThrowable() throws Exception { - String message = "testing message"; - String tMessage = "throwable message"; - Throwable throwable = new Throwable(tMessage); - APPCException appcException = new APPCException(message, throwable); - Assert.assertEquals(throwable, appcException.getCause()); - Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); - Assert.assertTrue(appcException.getMessage().contains(message)); - } - - @Test - public void testConstructorWithFourArguments() throws Exception { - String message = "testing message"; - String tMessage = "throwable message"; - Throwable throwable = new Throwable(tMessage); - APPCException appcException = new APPCException(message, throwable, true, true); - Assert.assertEquals(throwable, appcException.getCause()); - Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); - Assert.assertTrue(appcException.getMessage().contains(message)); - - Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") != null); - Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") != null); - - appcException = new APPCException(message, throwable, false, false); - Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") == null); - Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") == null); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidInputExceptionTest.java b/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidInputExceptionTest.java deleted file mode 100644 index 9822ff7ee..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidInputExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -import org.junit.Assert; -import org.junit.Test; - -public class InvalidInputExceptionTest { - @Test - public void testConstructor() throws Exception { - String message = "testing message"; - InvalidInputException invalidInputException = new InvalidInputException(message); - Assert.assertTrue(invalidInputException.getCause() == null); - Assert.assertEquals(message, invalidInputException.getLocalizedMessage()); - Assert.assertEquals(message, invalidInputException.getMessage()); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidStateExceptionTest.java b/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidStateExceptionTest.java deleted file mode 100644 index c008131f1..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/exceptions/InvalidStateExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -import org.junit.Assert; -import org.junit.Test; - -public class InvalidStateExceptionTest { - @Test - public void testConstructor() throws Exception { - String message = "testing message"; - InvalidStateException invalidStateException = new InvalidStateException(message); - Assert.assertTrue(invalidStateException.getCause() == null); - Assert.assertEquals(message, invalidStateException.getLocalizedMessage()); - Assert.assertEquals(message, invalidStateException.getMessage()); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/exceptions/UnknownProviderExceptionTest.java b/appc-common/src/test/java/org/openecomp/appc/exceptions/UnknownProviderExceptionTest.java deleted file mode 100644 index d3c7ab5ef..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/exceptions/UnknownProviderExceptionTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.exceptions; - -import org.junit.Assert; -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -public class UnknownProviderExceptionTest { - - @Test - public void testConstructorNoArgument() throws Exception { - UnknownProviderException unknownProviderException = new UnknownProviderException(); - Assert.assertTrue(unknownProviderException.getCause() == null); - Assert.assertTrue(unknownProviderException.getLocalizedMessage() == null); - Assert.assertTrue(unknownProviderException.getMessage() == null); - } - - @Test - public void testConstructorWithMessaqge() throws Exception { - String message = "testing message"; - UnknownProviderException unknownProviderException = new UnknownProviderException(message); - Assert.assertTrue(unknownProviderException.getCause() == null); - Assert.assertEquals(message, unknownProviderException.getLocalizedMessage()); - Assert.assertEquals(message, unknownProviderException.getMessage()); - } - - @Test - public void testConstructorWithThrowable() throws Exception { - String message = "testing message"; - Throwable throwable = new Throwable(message); - UnknownProviderException unknownProviderException = new UnknownProviderException(throwable); - Assert.assertEquals(throwable, unknownProviderException.getCause()); - Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); - Assert.assertTrue(unknownProviderException.getMessage().contains(message)); - } - - @Test - public void testConstructorWithMessageAndThrowable() throws Exception { - String message = "testing message"; - String tMessage = "throwable message"; - Throwable throwable = new Throwable(tMessage); - UnknownProviderException unknownProviderException = new UnknownProviderException(message, throwable); - Assert.assertEquals(throwable, unknownProviderException.getCause()); - Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); - Assert.assertTrue(unknownProviderException.getMessage().contains(message)); - } - - @Test - public void testConstructorWithFourArguements() throws Exception { - String message = "testing message"; - String tMessage = "throwable message"; - Throwable throwable = new Throwable(tMessage); - UnknownProviderException unknownProviderException = - new UnknownProviderException(message, throwable, true, true); - Assert.assertEquals(throwable, unknownProviderException.getCause()); - Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); - Assert.assertTrue(unknownProviderException.getMessage().contains(message)); - - Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, "stackTrace") != null); - Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, - "suppressedExceptions") != null); - - unknownProviderException = new UnknownProviderException(message, throwable, false, false); - Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, - "stackTrace") == null); - Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, - "suppressedExceptions") == null); - } - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/i18n/MsgTest.java b/appc-common/src/test/java/org/openecomp/appc/i18n/MsgTest.java deleted file mode 100644 index 1a541a5d4..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/i18n/MsgTest.java +++ /dev/null @@ -1,771 +0,0 @@ -package org.onap.appc.i18n; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Assert; -import org.junit.Test; - -public class MsgTest { - - @Test - public void testNameAndToString() throws Exception { - for (Msg msg : Msg.values()) { - Assert.assertEquals(msg.name(), msg.toString()); - } - } - - @Test - public void testCONFIGURATION_STARTED() { - assertNotNull(Msg.valueOf("CONFIGURATION_STARTED")); - } - - @Test - public void testCONFIGURATION_CLEARED() { - assertNotNull(Msg.valueOf("CONFIGURATION_CLEARED")); - } - - @Test - public void testLOADING_CONFIGURATION_OVERRIDES() { - assertNotNull(Msg.valueOf("LOADING_CONFIGURATION_OVERRIDES")); - } - - - @Test - public void testLOADING_DEFAULTS() { - assertNotNull(Msg.valueOf("LOADING_DEFAULTS")); - } - - - @Test - public void testNO_DEFAULTS_FOUND() { - assertNotNull(Msg.valueOf("NO_DEFAULTS_FOUND")); - } - - @Test - public void testPROPERTY_VALUE() { - assertNotNull(Msg.valueOf("PROPERTY_VALUE")); - } - - @Test - public void testNO_OVERRIDE_PROPERTY_FILE_LOADED() { - assertNotNull(Msg.valueOf("NO_OVERRIDE_PROPERTY_FILE_LOADED")); - } - - @Test - public void testSEARCHING_CONFIGURATION_OVERRIDES() { - assertNotNull(Msg.valueOf("SEARCHING_CONFIGURATION_OVERRIDES")); - } - - @Test - public void testLOADING_APPLICATION_OVERRIDES() { - assertNotNull(Msg.valueOf("LOADING_APPLICATION_OVERRIDES")); - } - - @Test - public void testNO_APPLICATION_OVERRIDES() { - assertNotNull(Msg.valueOf("NO_APPLICATION_OVERRIDES")); - } - - @Test - public void testMERGING_SYSTEM_PROPERTIES() { - assertNotNull(Msg.valueOf("MERGING_SYSTEM_PROPERTIES")); - } - - @Test - public void testSETTING_SPECIAL_PROPERTY() { - assertNotNull(Msg.valueOf("SETTING_SPECIAL_PROPERTY")); - } - - @Test - public void testLOADING_RESOURCE_BUNDLE() { - assertNotNull(Msg.valueOf("LOADING_RESOURCE_BUNDLE")); - } - - @Test - public void testLOGGING_ALREADY_INITIALIZED() { assertNotNull(Msg.valueOf("LOGGING_ALREADY_INITIALIZED")); } - - @Test - public void testSEARCHING_LOG_CONFIGURATION() { - assertNotNull(Msg.valueOf("SEARCHING_LOG_CONFIGURATION")); - } - - @Test - public void testLOADING_DEFAULT_LOG_CONFIGURATION() { - assertNotNull(Msg.valueOf("LOADING_DEFAULT_LOG_CONFIGURATION")); - } - - @Test - public void testNO_LOG_CONFIGURATION() { - assertNotNull(Msg.valueOf("NO_LOG_CONFIGURATION")); - } - - @Test - public void testUNSUPPORTED_LOGGING_FRAMEWORK() { - assertNotNull(Msg.valueOf("UNSUPPORTED_LOGGING_FRAMEWORK")); - } - - @Test - public void testLOADING_LOG_CONFIGURATION() { - assertNotNull(Msg.valueOf("LOADING_LOG_CONFIGURATION")); - } - - @Test - public void testUNKNOWN_PROVIDER() { - assertNotNull(Msg.valueOf("UNKNOWN_PROVIDER")); - } - - @Test - public void testSERVER_STATE_CHANGE_TIMEOUT() { - assertNotNull(Msg.valueOf("SERVER_STATE_CHANGE_TIMEOUT")); - } - - @Test - public void testSERVER_DELETED() { - assertNotNull(Msg.valueOf("SERVER_DELETED")); - } - - @Test - public void testUNKNOWN_SERVER_STATE() { - assertNotNull(Msg.valueOf("UNKNOWN_SERVER_STATE")); - } - - @Test - public void testCOMPONENT_INITIALIZING() { - assertNotNull(Msg.valueOf("COMPONENT_INITIALIZING")); - } - - @Test - public void testCOMPONENT_INITIALIZED() { - assertNotNull(Msg.valueOf("COMPONENT_INITIALIZED")); - } - - @Test - public void testCOMPONENT_TERMINATING() { - assertNotNull(Msg.valueOf("COMPONENT_TERMINATING")); - } - - @Test - public void testCOMPONENT_TERMINATED() { - assertNotNull(Msg.valueOf("COMPONENT_TERMINATED")); - } - - @Test - public void testIAAS_ADAPTER_UNSUPPORTED_OPERATION() { - assertNotNull(Msg.valueOf("IAAS_ADAPTER_UNSUPPORTED_OPERATION")); - } - - @Test - public void testIAAS_ADAPTER_RPC_CALLED() { - assertNotNull(Msg.valueOf("IAAS_ADAPTER_RPC_CALLED")); - } - - @Test - public void testNO_SERVICE_FOUND() { - assertNotNull(Msg.valueOf("NO_SERVICE_FOUND")); - } - - @Test - public void testCONTEXT_PARAMETERS_DISPLAY() { - assertNotNull(Msg.valueOf("CONTEXT_PARAMETERS_DISPLAY")); - } - - @Test - public void testRESPONSE_PARAMETERS_DISPLAY() { - assertNotNull(Msg.valueOf("RESPONSE_PARAMETERS_DISPLAY")); - } - - @Test - public void testNULL_OR_INVALID_ARGUMENT() { - assertNotNull(Msg.valueOf("NULL_OR_INVALID_ARGUMENT")); - } - - @Test - public void testPROCESSING_REQUEST() { - assertNotNull(Msg.valueOf("PROCESSING_REQUEST")); - } - - @Test - public void testINVALID_SERVICE_REQUEST() { - assertNotNull(Msg.valueOf("INVALID_SERVICE_REQUEST")); - } - - @Test - public void testREGISTERING_SERVICE() { - assertNotNull(Msg.valueOf("REGISTERING_SERVICE")); - } - - @Test - public void testUNREGISTERING_SERVICE() { - assertNotNull(Msg.valueOf("UNREGISTERING_SERVICE")); - } - - @Test - public void testLOADING_PROVIDER_DEFINITIONS() { - assertNotNull(Msg.valueOf("LOADING_PROVIDER_DEFINITIONS")); - } - - @Test - public void testRESTARTING_SERVER() { - assertNotNull(Msg.valueOf("RESTARTING_SERVER")); - } - - @Test - public void testREBUILDING_SERVER() { - assertNotNull(Msg.valueOf("REBUILDING_SERVER")); - } - - @Test - public void testMIGRATING_SERVER() { - assertNotNull(Msg.valueOf("MIGRATING_SERVER")); - } - - @Test - public void testEVACUATING_SERVER() { - assertNotNull(Msg.valueOf("EVACUATING_SERVER")); - } - - @Test - public void testSNAPSHOTING_SERVER() { - assertNotNull(Msg.valueOf("SNAPSHOTING_SERVER")); - } - - @Test - public void testLOOKING_SERVER_UP() { - assertNotNull(Msg.valueOf("LOOKING_SERVER_UP")); - } - - @Test - public void testINVALID_SELF_LINK_URL() { - assertNotNull(Msg.valueOf("INVALID_SELF_LINK_URL")); - } - - @Test - public void testSERVER_FOUND() { - assertNotNull(Msg.valueOf("SERVER_FOUND")); - } - - @Test - public void testSERVER_NOT_FOUND() { - assertNotNull(Msg.valueOf("SERVER_NOT_FOUND")); - } - - @Test - public void testSERVER_OPERATION_EXCEPTION() { - assertNotNull(Msg.valueOf("SERVER_OPERATION_EXCEPTION")); - } - - @Test - public void testMISSING_REQUIRED_PROPERTIES() { - assertNotNull(Msg.valueOf("MISSING_REQUIRED_PROPERTIES")); - } - - @Test - public void testSERVER_ERROR_STATE() { - assertNotNull(Msg.valueOf("SERVER_ERROR_STATE")); - } - - @Test - public void testIMAGE_NOT_FOUND() { - assertNotNull(Msg.valueOf("IMAGE_NOT_FOUND")); - } - - @Test - public void testSTATE_CHANGE_TIMEOUT() { - assertNotNull(Msg.valueOf("STATE_CHANGE_TIMEOUT")); - } - - @Test - public void testSTATE_CHANGE_EXCEPTION() { - assertNotNull(Msg.valueOf("STATE_CHANGE_EXCEPTION")); - } - - @Test - public void testSTOP_SERVER() { - assertNotNull(Msg.valueOf("STOP_SERVER")); - } - - @Test - public void testSTART_SERVER() { - assertNotNull(Msg.valueOf("START_SERVER")); - } - - @Test - public void testRESUME_SERVER() { - assertNotNull(Msg.valueOf("RESUME_SERVER")); - } - - @Test - public void testUNPAUSE_SERVER() { - assertNotNull(Msg.valueOf("UNPAUSE_SERVER")); - } - - @Test - public void testREBUILD_SERVER() { - assertNotNull(Msg.valueOf("REBUILD_SERVER")); - } - - @Test - public void testCONNECTION_FAILED_RETRY() { - assertNotNull(Msg.valueOf("CONNECTION_FAILED_RETRY")); - } - - @Test - public void testCONNECTION_FAILED() { - assertNotNull(Msg.valueOf("CONNECTION_FAILED")); - } - - @Test - public void testSTOPPING_SERVER() { - assertNotNull(Msg.valueOf("STOPPING_SERVER")); - } - - @Test - public void testSTARTING_SERVER() { - assertNotNull(Msg.valueOf("STARTING_SERVER")); - } - - @Test - public void testREBUILD_SERVER_FAILED() { - assertNotNull(Msg.valueOf("REBUILD_SERVER_FAILED")); - } - - @Test - public void testPARAMETER_IS_MISSING() { - assertNotNull(Msg.valueOf("PARAMETER_IS_MISSING")); - } - - @Test - public void testPARAMETER_NOT_NUMERIC() { - assertNotNull(Msg.valueOf("PARAMETER_NOT_NUMERIC")); - } - - @Test - public void testDG_FAILED_RESPONSE() { - assertNotNull(Msg.valueOf("DG_FAILED_RESPONSE")); - } - - @Test - public void testEXCEPTION_CALLING_DG() { - assertNotNull(Msg.valueOf("EXCEPTION_CALLING_DG")); - } - - @Test - public void testGRAPH_NOT_FOUND() { - assertNotNull(Msg.valueOf("GRAPH_NOT_FOUND")); - } - - @Test - public void testDEBUG_GRAPH_RESPONSE_HEADER() { - assertNotNull(Msg.valueOf("DEBUG_GRAPH_RESPONSE_HEADER")); - } - - @Test - public void testDEBUG_GRAPH_RESPONSE_DETAIL() { - assertNotNull(Msg.valueOf("DEBUG_GRAPH_RESPONSE_DETAIL")); - } - - @Test - public void testINVALID_REQUIRED_PROPERTY() { - assertNotNull(Msg.valueOf("INVALID_REQUIRED_PROPERTY")); - } - - @Test - public void testMIGRATE_SERVER_FAILED() { - assertNotNull(Msg.valueOf("MIGRATE_SERVER_FAILED")); - } - - @Test - public void testEVACUATE_SERVER_FAILED() { - assertNotNull(Msg.valueOf("EVACUATE_SERVER_FAILED")); - } - - @Test - public void testEVACUATE_SERVER_REBUILD_FAILED() { - assertNotNull(Msg.valueOf("EVACUATE_SERVER_REBUILD_FAILED")); - } - - @Test - public void testAPPC_TOO_BUSY() { - assertNotNull(Msg.valueOf("APPC_TOO_BUSY")); - } - - @Test - public void testVF_SERVER_BUSY() { - assertNotNull(Msg.valueOf("VF_SERVER_BUSY")); - } - - @Test - public void testVF_ILLEGAL_COMMAND() { - assertNotNull(Msg.valueOf("VF_ILLEGAL_COMMAND")); - } - - @Test - public void testVF_UNDEFINED_STATE() { - assertNotNull(Msg.valueOf("VF_UNDEFINED_STATE")); - } - - @Test - public void testAPPC_NO_RESOURCE_FOUND() { - assertNotNull(Msg.valueOf("APPC_NO_RESOURCE_FOUND")); - } - - @Test - public void testAPPC_EXPIRED_REQUEST() { - assertNotNull(Msg.valueOf("APPC_EXPIRED_REQUEST")); - } - - @Test - public void testAPPC_WORKFLOW_NOT_FOUND() { - assertNotNull(Msg.valueOf("APPC_WORKFLOW_NOT_FOUND")); - } - - @Test - public void testAPPC_INVALID_INPUT() { - assertNotNull(Msg.valueOf("APPC_INVALID_INPUT")); - } - - @Test - public void testAPPC_AUDIT_MSG() { - assertNotNull(Msg.valueOf("APPC_AUDIT_MSG")); - } - - @Test - public void testAAI_CONNECTION_FAILED() { - assertNotNull(Msg.valueOf("AAI_CONNECTION_FAILED")); - } - - @Test - public void testAAI_UPDATE_FAILED() { - assertNotNull(Msg.valueOf("AAI_UPDATE_FAILED")); - } - - @Test - public void testAAI_GET_DATA_FAILED() { - assertNotNull(Msg.valueOf("AAI_GET_DATA_FAILED")); - } - - @Test - public void testAAI_CONNECTION_FAILED_RETRY() { - assertNotNull(Msg.valueOf("AAI_CONNECTION_FAILED_RETRY")); - } - - @Test - public void testAAI_DELETE_FAILED() { - assertNotNull(Msg.valueOf("AAI_DELETE_FAILED")); - } - - @Test - public void testAAI_QUERY_FAILED() { - assertNotNull(Msg.valueOf("AAI_QUERY_FAILED")); - } - - @Test - public void testVNF_CONFIGURED() { - assertNotNull(Msg.valueOf("VNF_CONFIGURED")); - } - - @Test - public void testVNF_CONFIGURATION_STARTED() { - assertNotNull(Msg.valueOf("VNF_CONFIGURATION_STARTED")); - } - - @Test - public void testVNF_CONFIGURATION_FAILED() { - assertNotNull(Msg.valueOf("VNF_CONFIGURATION_FAILED")); - } - - @Test - public void testVNF_TEST_STARTED() { - assertNotNull(Msg.valueOf("VNF_TEST_STARTED")); - } - - @Test - public void testVNF_TESTED() { - assertNotNull(Msg.valueOf("VNF_TESTED")); - } - - @Test - public void testVNF_TEST_FAILED() { - assertNotNull(Msg.valueOf("VNF_TEST_FAILED")); - } - - @Test - public void testVNF_NOT_FOUND() { - assertNotNull(Msg.valueOf("VNF_NOT_FOUND")); - } - - @Test - public void testVNF_HEALTHCECK_FAILED() { - assertNotNull(Msg.valueOf("VNF_HEALTHCECK_FAILED")); - } - - @Test - public void testVM_HEALTHCECK_FAILED() { - assertNotNull(Msg.valueOf("VM_HEALTHCECK_FAILED")); - } - - @Test - public void testSTOP_SERVER_FAILED() { - assertNotNull(Msg.valueOf("STOP_SERVER_FAILED")); - } - - @Test - public void testTERMINATE_SERVER_FAILED() { - assertNotNull(Msg.valueOf("TERMINATE_SERVER_FAILED")); - } - - @Test - public void testTERMINATING_SERVER() { - assertNotNull(Msg.valueOf("TERMINATING_SERVER")); - } - - @Test - public void testTERMINATE_SERVER() { - assertNotNull(Msg.valueOf("TERMINATE_SERVER")); - } - - @Test - public void testMIGRATE_COMPLETE() { - assertNotNull(Msg.valueOf("MIGRATE_COMPLETE")); - } - - @Test - public void testRESTART_COMPLETE() { - assertNotNull(Msg.valueOf("RESTART_COMPLETE")); - } - - @Test - public void testREBUILD_COMPLETE() { - assertNotNull(Msg.valueOf("REBUILD_COMPLETE")); - } - - @Test - public void testSTACK_FOUND() { - assertNotNull(Msg.valueOf("STACK_FOUND")); - } - - @Test - public void testTERMINATING_STACK() { - assertNotNull(Msg.valueOf("TERMINATING_STACK")); - } - - @Test - public void testTERMINATE_STACK() { - assertNotNull(Msg.valueOf("TERMINATE_STACK")); - } - - @Test - public void testSTACK_NOT_FOUND() { - assertNotNull(Msg.valueOf("STACK_NOT_FOUND")); - } - - @Test - public void testSTACK_OPERATION_EXCEPTION() { - assertNotNull(Msg.valueOf("STACK_OPERATION_EXCEPTION")); - } - - @Test - public void testTERMINATE_STACK_FAILED() { - assertNotNull(Msg.valueOf("TERMINATE_STACK_FAILED")); - } - - @Test - public void testCLOSE_CONTEXT_FAILED() { - assertNotNull(Msg.valueOf("CLOSE_CONTEXT_FAILED")); - } - - @Test - public void testSNAPSHOTING_STACK() { - assertNotNull(Msg.valueOf("SNAPSHOTING_STACK")); - } - - @Test - public void testSTACK_SNAPSHOTED() { - assertNotNull(Msg.valueOf("STACK_SNAPSHOTED")); - } - - @Test - public void testRESTORING_STACK() { - assertNotNull(Msg.valueOf("RESTORING_STACK")); - } - - @Test - public void testSTACK_RESTORED() { - assertNotNull(Msg.valueOf("STACK_RESTORED")); - } - - @Test - public void testCHECKING_SERVER() { - assertNotNull(Msg.valueOf("CHECKING_SERVER")); - } - - @Test - public void testMISSING_PARAMETER_IN_REQUEST() { - assertNotNull(Msg.valueOf("MISSING_PARAMETER_IN_REQUEST")); - } - - @Test - public void testCANNOT_ESTABLISH_CONNECTION() { - assertNotNull(Msg.valueOf("CANNOT_ESTABLISH_CONNECTION")); - } - - @Test - public void testAPPC_METRIC_MSG() { - assertNotNull(Msg.valueOf("APPC_METRIC_MSG")); - } - - @Test - public void testINPUT_PAYLOAD_PARSING_FAILED() { - assertNotNull(Msg.valueOf("INPUT_PAYLOAD_PARSING_FAILED")); - } - - @Test - public void testAPPC_EXCEPTION() { - assertNotNull(Msg.valueOf("APPC_EXCEPTION")); - } - - @Test - public void testSSH_DATA_EXCEPTION() { - assertNotNull(Msg.valueOf("SSH_DATA_EXCEPTION")); - } - - @Test - public void testJSON_PROCESSING_EXCEPTION() { - assertNotNull(Msg.valueOf("JSON_PROCESSING_EXCEPTION")); - } - - @Test - public void testSUCCESS_EVENT_MESSAGE() { - assertNotNull(Msg.valueOf("SUCCESS_EVENT_MESSAGE")); - } - - @Test - public void testDEPENDENCY_MODEL_NOT_FOUND() { - assertNotNull(Msg.valueOf("DEPENDENCY_MODEL_NOT_FOUND")); - } - - @Test - public void testINVALID_DEPENDENCY_MODEL() { - assertNotNull(Msg.valueOf("INVALID_DEPENDENCY_MODEL")); - } - - @Test - public void testFAILURE_RETRIEVE_VNFC_DG() { - assertNotNull(Msg.valueOf("FAILURE_RETRIEVE_VNFC_DG")); - } - - @Test - public void testSERVER_NETWORK_ERROR() { - assertNotNull(Msg.valueOf("SERVER_NETWORK_ERROR")); - } - - @Test - public void testHYPERVISOR_DOWN_ERROR() { - assertNotNull(Msg.valueOf("HYPERVISOR_DOWN_ERROR")); - } - - @Test - public void testHYPERVISOR_STATUS_UKNOWN() { - assertNotNull(Msg.valueOf("HYPERVISOR_STATUS_UKNOWN")); - } - - @Test - public void testHYPERVISOR_NETWORK_ERROR() { - assertNotNull(Msg.valueOf("HYPERVISOR_NETWORK_ERROR")); - } - - @Test - public void testAPPLICATION_RESTART_FAILED() { - assertNotNull(Msg.valueOf("APPLICATION_RESTART_FAILED")); - } - - @Test - public void testAPPLICATION_START_FAILED() { - assertNotNull(Msg.valueOf("APPLICATION_START_FAILED")); - } - - @Test - public void testAPPLICATION_STOP_FAILED() { - assertNotNull(Msg.valueOf("APPLICATION_STOP_FAILED")); - } - - @Test - public void testRESTART_APPLICATION() { - assertNotNull(Msg.valueOf("RESTART_APPLICATION")); - } - - @Test - public void testSTART_APPLICATION() { - assertNotNull(Msg.valueOf("START_APPLICATION")); - } - - @Test - public void testSTOP_APPLICATION() { - assertNotNull(Msg.valueOf("STOP_APPLICATION")); - } - - @Test - public void testLCM_OPERATIONS_DISABLED() { - assertNotNull(Msg.valueOf("LCM_OPERATIONS_DISABLED")); - } - - @Test - public void testOAM_OPERATION_EXCEPTION() { - assertNotNull(Msg.valueOf("OAM_OPERATION_EXCEPTION")); - } - - @Test - public void testOAM_OPERATION_ENTERING_MAINTENANCE_MODE() { - assertNotNull(Msg.valueOf("OAM_OPERATION_ENTERING_MAINTENANCE_MODE")); - } - - @Test - public void testOAM_OPERATION_MAINTENANCE_MODE() { - assertNotNull(Msg.valueOf("OAM_OPERATION_MAINTENANCE_MODE")); - } - - @Test - public void testOAM_OPERATION_STARTING() { - assertNotNull(Msg.valueOf("OAM_OPERATION_STARTING")); - } - - @Test - public void testOAM_OPERATION_STARTED() { - assertNotNull(Msg.valueOf("OAM_OPERATION_STARTED")); - } - - @Test - public void testOAM_OPERATION_STOPPING() { - assertNotNull(Msg.valueOf("OAM_OPERATION_STOPPING")); - } - - @Test - public void testOAM_OPERATION_STOPPED() { - assertNotNull(Msg.valueOf("OAM_OPERATION_STOPPED")); - } - - @Test - public void testINVALID_STATE_TRANSITION() { - assertNotNull(Msg.valueOf("INVALID_STATE_TRANSITION")); - } - - @Test - public void testREQUEST_HANDLER_UNAVAILABLE() { - assertNotNull(Msg.valueOf("REQUEST_HANDLER_UNAVAILABLE")); - } - - @Test - public void testOAM_OPERATION_RESTARTING() { - assertNotNull(Msg.valueOf("OAM_OPERATION_RESTARTING")); - } - - @Test - public void testOAM_OPERATION_RESTARTED() { - assertNotNull(Msg.valueOf("OAM_OPERATION_RESTARTED")); - } - - @Test - public void testOAM_OPERATION_INVALID_INPUT() { - assertNotNull(Msg.valueOf("OAM_OPERATION_INVALID_INPUT")); - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/logging/LoggingConstantsTest.java b/appc-common/src/test/java/org/openecomp/appc/logging/LoggingConstantsTest.java deleted file mode 100644 index 1238b494b..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/logging/LoggingConstantsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.logging; - -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -public class LoggingConstantsTest { - @Test (expected = IllegalAccessError.class) - public void testConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.class); - } - - @Test (expected = IllegalAccessError.class) - public void testMdcKeysConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.MDCKeys.class); - } - - @Test (expected = IllegalAccessError.class) - public void testStatusCodesConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.StatusCodes.class); - } - - @Test (expected = IllegalAccessError.class) - public void testTargetNamesConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.TargetNames.class); - } - - @Test (expected = IllegalAccessError.class) - public void testTargetServiceNamesConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.class); - } - - @Test (expected = IllegalAccessError.class) - public void testAAIServiceNamesConstructor() throws Exception { - Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.AAIServiceNames.class); - } -} \ No newline at end of file diff --git a/appc-common/src/test/java/org/openecomp/appc/metadata/TestMetadataService.java b/appc-common/src/test/java/org/openecomp/appc/metadata/TestMetadataService.java deleted file mode 100644 index 7316fe8a6..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/metadata/TestMetadataService.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metadata; - -import org.onap.ccsdk.sli.core.dblib.DbLibService; -import com.sun.rowset.CachedRowSetImpl; -import org.mockito.Mockito; -import org.onap.appc.metadata.impl.MetadataServiceImpl; - -import javax.sql.rowset.CachedRowSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import static org.mockito.Matchers.anyCollection; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; - - - -public class TestMetadataService { - - MetadataServiceImpl metadataService = new MetadataServiceImpl(); - - TestMetadataService() throws SQLException { - DbLibService dbLibService = mock(DbLibService.class); - metadataService.setDbLibService(dbLibService); - CachedRowSet mockRS = new CachedRowSetImpl(); - Mockito.when(dbLibService.getData(anyString(), (ArrayList)anyCollection(), anyString())).thenReturn(mockRS); - } - - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifierTest.java b/appc-common/src/test/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifierTest.java deleted file mode 100644 index 95f3312cb..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/metadata/objects/DependencyModelIdentifierTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metadata.objects; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -import static org.onap.appc.metadata.objects.DependencyModelIdentifier.prime; - -public class DependencyModelIdentifierTest { - private static final String vnfType = "vnfType"; - private static final String vnfType2 = "vnfType2"; - private static final String cVersion = "catalogVersion"; - private DependencyModelIdentifier identifier; - private DependencyModelIdentifier identifier1; - private DependencyModelIdentifier identifier2; - private DependencyModelIdentifier identifier3; - - @Before - public void setUp() throws Exception { - identifier = new DependencyModelIdentifier(vnfType, cVersion); - identifier1 = new DependencyModelIdentifier(null, null); - identifier2 = new DependencyModelIdentifier(vnfType, null); - identifier3 = new DependencyModelIdentifier(null, cVersion); - } - - @Test - public void testConstructorAndGetterAndToString() throws Exception { - Assert.assertEquals(vnfType, Whitebox.getInternalState(identifier, "vnfType")); - Assert.assertEquals(cVersion, Whitebox.getInternalState(identifier, "catalogVersion")); - - Assert.assertEquals(vnfType, identifier.getVnfType()); - Assert.assertEquals(cVersion, identifier.getCatalogVersion()); - - Assert.assertEquals(String.format(DependencyModelIdentifier.TO_STRING_FORMAT, vnfType, cVersion), - identifier.toString()); - } - - @Test - public void testHashCode() throws Exception { - Assert.assertEquals((prime + vnfType.hashCode()) * prime + cVersion.hashCode(), identifier.hashCode()); - Assert.assertEquals(prime * prime, identifier1.hashCode()); - Assert.assertEquals((prime + vnfType.hashCode()) * prime , identifier2.hashCode()); - Assert.assertEquals(prime* prime + cVersion.hashCode(), identifier3.hashCode()); - } - - @Test - public void testEquals() throws Exception { - // other object is null - Assert.assertFalse(identifier.equals(null)); - // other object is wrong data type - Assert.assertFalse(identifier.equals("abc")); - - // my vnfType is null - Assert.assertFalse(identifier1.equals(identifier)); - // different vnfType - DependencyModelIdentifier identifier4 = new DependencyModelIdentifier(vnfType2, cVersion); - Assert.assertFalse(identifier.equals(identifier4)); - // same vnfType, my catalogVerson is null - Assert.assertFalse(identifier2.equals(identifier)); - // same vnfType and both catalogVersion are null - identifier4 = new DependencyModelIdentifier(vnfType, null); - Assert.assertTrue(identifier2.equals(identifier4)); - - Assert.assertFalse(identifier.equals(identifier1)); - Assert.assertFalse(identifier.equals(identifier2)); - Assert.assertFalse(identifier.equals(identifier3)); - - Assert.assertFalse(identifier2.equals(identifier1)); - Assert.assertFalse(identifier2.equals(identifier3)); - - - Assert.assertFalse(identifier3.equals(identifier)); - Assert.assertFalse(identifier3.equals(identifier1)); - Assert.assertFalse(identifier3.equals(identifier2)); - - identifier4 = new DependencyModelIdentifier(vnfType, cVersion); - Assert.assertTrue(identifier.equals(identifier4)); - } - -} diff --git a/appc-common/src/test/java/org/openecomp/appc/pool/CachedElementTest.java b/appc-common/src/test/java/org/openecomp/appc/pool/CachedElementTest.java deleted file mode 100644 index 30e592430..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/pool/CachedElementTest.java +++ /dev/null @@ -1,276 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.pool.Allocator; -import org.onap.appc.pool.CachedElement; -import org.onap.appc.pool.Destructor; -import org.onap.appc.pool.Pool; -import org.onap.appc.pool.PoolDrainedException; -import org.onap.appc.pool.PoolExtensionException; -import org.onap.appc.pool.PoolSpecificationException; -import org.onap.appc.pool.*; - - -public class CachedElementTest implements Allocator, Destructor { - private static final int MIN = 10; - private static final int MAX = 100; - private Pool pool; - private int index = 0; - private int destroyCount = 0; - - /** - * setup - * - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - @Before - public void setup() throws PoolSpecificationException { - pool = new Pool<>(MIN, MAX); - } - - /** - * Test state - */ - @Test - public void testAllocator() { - assertNull(pool.getAllocator()); - pool.setAllocator(this); - assertNotNull(pool.getAllocator()); - } - - /** - * Test state - */ - @Test - public void testDestructor() { - assertNull(pool.getDestructor()); - pool.setDestructor(this); - assertNotNull(pool.getDestructor()); - } - - /** - * Test that we can allocate and release elements and that the pool maintains them in MRU order - * - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws PoolDrainedException - * If the caller is trying to reserve an element from a drained pool - */ - @Test - public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { - pool.setAllocator(this); - - assertFalse(pool.isDrained()); - - /* - * Allocate three elements - */ - Testable value1 = pool.reserve(); - assertNotNull(value1); - assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value1.getId())); - assertEquals(1, pool.getAllocatedSize()); - assertEquals(MIN - 1, pool.getFreeSize()); - assertEquals(1, pool.getAllocatedSize()); - - Testable value2 = pool.reserve(); - assertNotNull(value2); - assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); - assertEquals(2, pool.getAllocatedSize()); - assertEquals(MIN - 2, pool.getFreeSize()); - assertEquals(2, pool.getAllocatedSize()); - - Testable value3 = pool.reserve(); - assertNotNull(value3); - assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value3.getId())); - assertEquals(3, pool.getAllocatedSize()); - assertEquals(MIN - 3, pool.getFreeSize()); - assertEquals(3, pool.getAllocatedSize()); - - /* - * Now, release them in the order obtained - */ - pool.release(value1); - pool.release(value2); - pool.release(value3); - - assertEquals(0, pool.getAllocatedSize()); - assertEquals(MIN, pool.getFreeSize()); - - /* - * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used - * to the least recently used. - */ - value1 = pool.reserve(); - assertNotNull(value1); - assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value1.getId())); - - value2 = pool.reserve(); - assertNotNull(value2); - assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); - - value3 = pool.reserve(); - assertNotNull(value3); - assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value3.getId())); - } - - /** - * Test that we can trim the pool to a desired size - * - * @throws PoolDrainedException - * If the caller is trying to release or reserve an element from a drained pool - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws IllegalAccessException - * if this Method object is enforcing Java language access control and the underlying method is - * inaccessible. - * @throws IllegalArgumentException - * if the method is an instance method and the specified object argument is not an instance of the class - * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number - * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or - * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal - * parameter type by a method invocation conversion. - * @throws InvocationTargetException - * if the underlying method throws an exception. - * @throws SecurityException - * If a security manager, s, is present and any of the following conditions is met: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared method
  • - *
  • the caller's class loader is not the same as or an ancestor of the class loader for the current - * class and invocation of s.checkPackageAccess() denies access to the package of this class
  • - *
- * @throws NoSuchMethodException - * if a matching method is not found. - */ - @SuppressWarnings("nls") - @Test - public void testTrim() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, - PoolDrainedException, PoolExtensionException, NoSuchMethodException, SecurityException { - - pool.setAllocator(this); - int SIZE = 50; - Testable[] array = new Testable[SIZE]; - - assertEquals(0, pool.getAllocatedSize()); - for (int i = 0; i < SIZE; i++) { - array[i] = pool.reserve(); - } - assertEquals(SIZE, pool.getAllocatedSize()); - - for (int i = 0; i < SIZE; i++) { - pool.release(array[i]); - } - assertEquals(0, pool.getAllocatedSize()); - - assertEquals(SIZE, pool.getFreeSize()); - - Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { - Integer.TYPE - }); - trimMethod.setAccessible(true); - trimMethod.invoke(pool, new Object[] { - SIZE - MIN - }); - - assertEquals(MIN, pool.getFreeSize()); - } - - /** - * Test that we can drain a pool containing a mix of free and allocated elements - * - * @throws PoolDrainedException - * If the caller is trying to release or reserve an element from a drained pool - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws IOException - * if an I/O error occurs - */ - @Test - public void testDrain() throws PoolExtensionException, PoolDrainedException, IOException { - int SIZE = 50; - int FREE = 20; - int ALLOC = SIZE - FREE; - - Testable[] array = new Testable[SIZE]; - pool.setAllocator(this); - pool.setDestructor(this); - - assertFalse(pool.isDrained()); - - assertEquals(0, pool.getAllocatedSize()); - for (int i = 0; i < SIZE; i++) { - array[i] = pool.reserve(); - } - assertEquals(SIZE, pool.getAllocatedSize()); - - for (int i = 0; i < FREE; i++) { - array[i].close(); - } - assertEquals(ALLOC, pool.getAllocatedSize()); - assertEquals(FREE, pool.getFreeSize()); - - pool.drain(); - assertEquals(0, pool.getFreeSize()); - assertEquals(0, pool.getAllocatedSize()); - assertTrue(pool.isDrained()); - - assertEquals(SIZE, destroyCount); - } - - /** - * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) - */ - @Override - public Testable allocate(Pool pool) { - Testable element = new Element(index++); - Testable ce = CachedElement.newInstance(pool, element, new Class[] { - Testable.class - }); - return ce; - } - - /** - * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) - */ - @Override - public void destroy(Testable obj, Pool pool) { - destroyCount++; - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/pool/Element.java b/appc-common/src/test/java/org/openecomp/appc/pool/Element.java deleted file mode 100644 index 877fab2aa..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/pool/Element.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import java.io.IOException; - -public class Element implements Testable { - private boolean closed; - private Integer id; - - public Element(int id) { - this.id = Integer.valueOf(id); - closed = false; - } - - @Override - public boolean equals(Object obj) { - boolean result = false; - if (obj instanceof Element) { - Element other = (Element) obj; - result = this.id.equals(other.id); - } - - return result; - } - - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * @see java.io.Closeable#close() - */ - @Override - public void close() throws IOException { - closed = true; - } - - @Override - public Boolean isClosed() { - return Boolean.valueOf(closed); - } - - @Override - public String toString() { - return Integer.toString(id); - } - - @Override - public Integer getId() { - return id; - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/pool/PoolTest.java b/appc-common/src/test/java/org/openecomp/appc/pool/PoolTest.java deleted file mode 100644 index db9a2e615..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/pool/PoolTest.java +++ /dev/null @@ -1,323 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.pool; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.pool.Allocator; -import org.onap.appc.pool.Destructor; -import org.onap.appc.pool.Pool; -import org.onap.appc.pool.PoolDrainedException; -import org.onap.appc.pool.PoolExtensionException; -import org.onap.appc.pool.PoolSpecificationException; -import org.onap.appc.pool.*; - - -public class PoolTest implements Allocator, Destructor { - - private Pool pool; - private static final int MIN = 10; - private static final int MAX = 100; - private int index = 0; - private int destroyCount = 0; - - /** - * Set up the test by allocating a pool with MIN-MAX size (bounded pool) - * - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - @Before - public void setup() throws PoolSpecificationException { - pool = new Pool<>(MIN, MAX); - index = 0; - destroyCount = 0; - } - - /** - * Test that trying to construct a pool with a bad minimum throws an exception - * - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - @Test(expected = PoolSpecificationException.class) - public void testInvalidMinSize() throws PoolSpecificationException { - pool = new Pool<>(-1, MAX); - } - - /** - * Test that trying to construct a pool with a bad maximum throws an exception - * - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - @Test(expected = PoolSpecificationException.class) - public void testInvalidMaxSize() throws PoolSpecificationException { - pool = new Pool<>(MIN, -1); - } - - /** - * Test creation of a pool where max is less than min fails - * - * @throws PoolSpecificationException - * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. - */ - @Test(expected = PoolSpecificationException.class) - public void testInvalidSizeRange() throws PoolSpecificationException { - pool = new Pool<>(MAX, MIN); - } - - /** - * Test state - */ - @Test - public void testMinPool() { - assertEquals(MIN, pool.getMinPool()); - } - - /** - * Test state - */ - @Test - public void testMaxPool() { - assertEquals(MAX, pool.getMaxPool()); - } - - /** - * Test state - */ - @Test - public void testAllocator() { - assertNull(pool.getAllocator()); - pool.setAllocator(this); - assertNotNull(pool.getAllocator()); - } - - /** - * Test state - */ - @Test - public void testDestructor() { - assertNull(pool.getDestructor()); - pool.setDestructor(this); - assertNotNull(pool.getDestructor()); - } - - /** - * Test that we can allocate and release elements and that the pool maintains them in MRU order - * - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws PoolDrainedException - * If the caller is trying to reserve an element from a drained pool - */ - @Test - public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { - pool.setAllocator(this); - - assertFalse(pool.isDrained()); - - /* - * Allocate three elements - */ - Testable value1 = pool.reserve(); - assertNotNull(value1); - assertEquals(Integer.valueOf(MIN - 1), value1.getId()); - assertEquals(1, pool.getAllocatedSize()); - assertEquals(MIN - 1, pool.getFreeSize()); - assertEquals(1, pool.getAllocatedSize()); - - Testable value2 = pool.reserve(); - assertNotNull(value2); - assertEquals(Integer.valueOf(MIN - 2), value2.getId()); - assertEquals(2, pool.getAllocatedSize()); - assertEquals(MIN - 2, pool.getFreeSize()); - assertEquals(2, pool.getAllocatedSize()); - - Testable value3 = pool.reserve(); - assertNotNull(value3); - assertEquals(Integer.valueOf(MIN - 3), value3.getId()); - assertEquals(3, pool.getAllocatedSize()); - assertEquals(MIN - 3, pool.getFreeSize()); - assertEquals(3, pool.getAllocatedSize()); - - /* - * Now, release them in the order obtained - */ - pool.release(value1); - pool.release(value2); - pool.release(value3); - - assertEquals(0, pool.getAllocatedSize()); - assertEquals(MIN, pool.getFreeSize()); - - /* - * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used - * to the least recently used. - */ - value1 = pool.reserve(); - assertNotNull(value1); - assertEquals(Integer.valueOf(MIN - 3), value1.getId()); - - value2 = pool.reserve(); - assertNotNull(value2); - assertEquals(Integer.valueOf(MIN - 2), value2.getId()); - - value3 = pool.reserve(); - assertNotNull(value3); - assertEquals(Integer.valueOf(MIN - 1), value3.getId()); - } - - /** - * Test that we can trim the pool to a desired size - * - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws NoSuchMethodException - * if a matching method is not found. - * @throws SecurityException - * if the request is denied. - * @throws IllegalAccessException - * if this Method object is enforcing Java language access control and the underlying method is - * inaccessible. - * @throws IllegalArgumentException - * if the method is an instance method and the specified object argument is not an instance of the class - * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number - * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or - * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal - * parameter type by a method invocation conversion. - * @throws InvocationTargetException - * if the underlying method throws an exception. - * @throws PoolDrainedException - * If the caller is trying to reserve an element from a drained pool - */ - @SuppressWarnings("nls") - @Test - public void testTrim() throws PoolExtensionException, NoSuchMethodException, SecurityException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, PoolDrainedException { - pool.setAllocator(this); - int SIZE = 50; - Proxy[] array = new Proxy[SIZE]; - - assertEquals(0, pool.getAllocatedSize()); - for (int i = 0; i < SIZE; i++) { - array[i] = (Proxy) pool.reserve(); - } - assertEquals(SIZE, pool.getAllocatedSize()); - - for (int i = 0; i < SIZE; i++) { - pool.release((Testable) array[i]); - } - assertEquals(0, pool.getAllocatedSize()); - - assertEquals(SIZE, pool.getFreeSize()); - - Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { - Integer.TYPE - }); - trimMethod.setAccessible(true); - trimMethod.invoke(pool, new Object[] { - SIZE - MIN - }); - - assertEquals(MIN, pool.getFreeSize()); - } - - /** - * Test that we can drain a pool containing a mix of free and allocated elements - * - * @throws PoolExtensionException - * If the pool cannot be extended - * @throws PoolDrainedException - * If the caller is trying to reserve an element from a drained pool - */ - @Test - public void testDrain() throws PoolExtensionException, PoolDrainedException { - int SIZE = 50; - int FREE = 20; - int ALLOC = SIZE - FREE; - - Proxy[] array = new Proxy[SIZE]; - pool.setAllocator(this); - pool.setDestructor(this); - - assertFalse(pool.isDrained()); - - assertEquals(0, pool.getAllocatedSize()); - for (int i = 0; i < SIZE; i++) { - array[i] = (Proxy) pool.reserve(); - } - assertEquals(SIZE, pool.getAllocatedSize()); - - for (int i = 0; i < FREE; i++) { - pool.release((Testable) array[i]); - } - assertEquals(ALLOC, pool.getAllocatedSize()); - assertEquals(FREE, pool.getFreeSize()); - - pool.drain(); - assertEquals(0, pool.getFreeSize()); - assertEquals(0, pool.getAllocatedSize()); - assertTrue(pool.isDrained()); - - assertEquals(SIZE, destroyCount); - } - - /** - * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) - */ - @Override - public void destroy(Testable obj, Pool pool) { - destroyCount++; - try { - obj.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) - */ - @Override - public Testable allocate(Pool pool) { - Testable e = new Element(index++); - - return e; - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/pool/Testable.java b/appc-common/src/test/java/org/openecomp/appc/pool/Testable.java deleted file mode 100644 index fb2fa75ef..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/pool/Testable.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.pool; - -import java.io.Closeable; - -public interface Testable extends Closeable { - - Integer getId(); - - Boolean isClosed(); -} - diff --git a/appc-common/src/test/java/org/openecomp/appc/util/TestJsonUtil.java b/appc-common/src/test/java/org/openecomp/appc/util/TestJsonUtil.java deleted file mode 100644 index 270f90f05..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/util/TestJsonUtil.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.util.JsonUtil; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import static org.junit.Assert.*; - - - -public class TestJsonUtil { - - @Test - public void testConvertJsonStringToFlatMap() { - try { - String jsonString = "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; - Map flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); - assertNotNull(flatMap); - Map expectedMap = new HashMap<>(); - expectedMap.put("A","A-value"); - expectedMap.put("B.C","B.C-value"); - expectedMap.put("B.D","B.D-value"); - assertEquals(expectedMap,flatMap); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(e.toString()); - } - } - - @Test - public void testConvertJsonStringToFlatMapWithInnerJson() { - try { - String jsonString = "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}"; - Map flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); - assertNotNull(flatMap); - Map expectedMap = new HashMap<>(); - expectedMap.put("A","A-value"); - expectedMap.put("B","{\"C\":\"C-value\",\"D\":\"D-value\"}"); - assertEquals(expectedMap,flatMap); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(e.toString()); - } - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/util/TestStringHelper.java b/appc-common/src/test/java/org/openecomp/appc/util/TestStringHelper.java deleted file mode 100644 index 06957cf2d..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/util/TestStringHelper.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; - -import org.junit.Test; -import org.onap.appc.util.StringHelper; - - -public class TestStringHelper { - - @Test - public void testAsListWithNullList() { - String value = StringHelper.asList((String[]) null); - assertNotNull(value); - assertEquals("[]", value); - } - - @Test - public void testAsListWithEmptyList() { - String value = StringHelper.asList(new String[] {}); - assertNotNull(value); - assertEquals("[]", value); - } - - @Test - public void testAsListWithSingleValue() { - String value = StringHelper.asList("one"); - assertNotNull(value); - assertEquals("[one]", value); - } - - @Test - public void testAsListWithTwoValues() { - String value = StringHelper.asList("one", "two"); - assertNotNull(value); - assertEquals("[one,two]", value); - } - - @Test - public void testAsListWithFiveValues() { - String value = StringHelper.asList("one", "two", "three", "four", "five"); - assertNotNull(value); - assertEquals("[one,two,three,four,five]", value); - } - - @Test - public void testPropertiesToString() { - String key1 = "key1"; - String val1 = "val1"; - String key2 = "key2"; - String val2 = "val2"; - - assertEquals(null, StringHelper.propertiesToString(null)); - - Properties props = new Properties(); - - String result = StringHelper.propertiesToString(props); - assertNotNull(result); - assertEquals("[ ]", result); - - props.setProperty(key1, val1); - result = StringHelper.propertiesToString(props); - assertNotNull(result); - assertTrue(result.contains(key1)); - assertTrue(result.contains(val1)); - assertTrue(result.lastIndexOf(",") < result.length() - 3); // No trailing comma - - props.setProperty(key2, val2); - result = StringHelper.propertiesToString(props); - assertNotNull(result); - assertTrue(result.contains(key1)); - assertTrue(result.contains(val1)); - assertTrue(result.contains(key2)); - assertTrue(result.contains(val2)); - assertTrue(result.lastIndexOf(",") < result.length() - 3); // No trailing comma - } -} diff --git a/appc-common/src/test/java/org/openecomp/appc/util/TestStructuredPropertyHelper.java b/appc-common/src/test/java/org/openecomp/appc/util/TestStructuredPropertyHelper.java deleted file mode 100644 index 06c27d0dd..000000000 --- a/appc-common/src/test/java/org/openecomp/appc/util/TestStructuredPropertyHelper.java +++ /dev/null @@ -1,236 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.util.StructuredPropertyHelper; -import org.onap.appc.util.StructuredPropertyHelper.Node; - -/** - * This class is used to test the structured property helper class. - *

- * A structured property is one where the name is constructed from a compound set of elements, concatenated by a period, - * and optionally being enumerated using a sequence number suffix. A java package name is an example of a structured - * name, where each element of the name represents a directory or name in the namespace hierarchy. Property names may - * also be structured. This class constructs a graph of the structured properties and this test case is used to verify - * its operation. - *

- * - */ -public class TestStructuredPropertyHelper { - - /** - * The properties to be parsed - */ - private Properties properties; - - /** - * The result of parsing the properties - */ - private List nodes = new ArrayList<>(); - - /** - * Initialize the test environment - */ - @SuppressWarnings("nls") - @Before - public void setup() { - nodes.clear(); - - properties = new Properties(); - - properties.setProperty("provider1.name", "provider1Name"); - properties.setProperty("provider1.type", "provider1type"); - properties.setProperty("provider1.URL", "provider1URL"); - properties.setProperty("provider2.name", "provider2Name"); - properties.setProperty("provider2.type", "provider2type"); - properties.setProperty("provider2.URL", "provider2URL"); - properties.setProperty("provider003.name", "provider3Name"); - properties.setProperty("provider003.type", "provider3type"); - properties.setProperty("provider003.URL", "provider3URL"); - - properties.setProperty("node1.level1.value1.key", "1.1.1"); - properties.setProperty("node1.level1.value2.key", "1.1.2"); - properties.setProperty("node1.level1.value3.key", "1.1.3"); - properties.setProperty("node1.level2.value1.key", "1.2.1"); - properties.setProperty("node1.level2.value2.key", "1.2.2"); - properties.setProperty("node1.level2.value3.key", "1.2.3"); - properties.setProperty("node1.level3.value1.key", "1.3.1"); - properties.setProperty("node1.level3.value2.key", "1.3.2"); - properties.setProperty("node1.level3.value3.key", "1.3.3"); - properties.setProperty("node2.level1.value1.key", "2.1.1"); - properties.setProperty("node2.level1.value2.key", "2.1.2"); - properties.setProperty("node2.level1.value3.key", "2.1.3"); - properties.setProperty("node2.level2.value1.key", "2.2.1"); - properties.setProperty("node2.level2.value2.key", "2.2.2"); - properties.setProperty("node2.level2.value3.key", "2.2.3"); - properties.setProperty("node2.level3.value1.key", "2.3.1"); - properties.setProperty("node2.level3.value2.key", "2.3.2"); - properties.setProperty("node2.level3.value3.key", "2.3.3"); - properties.setProperty("node3.level1.value1.key", "3.1.1"); - properties.setProperty("node3.level1.value2.key", "3.1.2"); - properties.setProperty("node3.level1.value3.key", "3.1.3"); - properties.setProperty("node3.level2.value1.key", "3.2.1"); - properties.setProperty("node3.level2.value2.key", "3.2.2"); - properties.setProperty("node3.level2.value3.key", "3.2.3"); - properties.setProperty("node3.level3.value1.key", "3.3.1"); - properties.setProperty("node3.level3.value2.key", "3.3.2"); - properties.setProperty("node3.level3.value3.key", "3.3.3"); - - properties.setProperty("other.property", "bogus"); - properties.setProperty("yet.another.property", "bogus"); - properties.setProperty("simpleProperty", "bogus"); - - } - - /** - * Test that a simple namespace works - */ - @SuppressWarnings("nls") - @Test - public void testSimpleNamespace() { - nodes = StructuredPropertyHelper.getStructuredProperties(properties, "provider"); - - assertNotNull(nodes); - assertFalse(nodes.isEmpty()); - - assertEquals(3, nodes.size()); - - List children; - for (Node node : nodes) { - switch (node.getName()) { - case "provider1": - assertNull(node.getValue()); - children = node.getChildren(); - assertNotNull(children); - assertEquals(3, children.size()); - for (Node child : children) { - switch (child.getName()) { - case "URL": - assertEquals("provider1URL", child.getValue()); - break; - case "type": - assertEquals("provider1type", child.getValue()); - break; - case "name": - assertEquals("provider1Name", child.getValue()); - break; - default: - fail("Unknown child of " + node.getName() + " with value " + child.toString()); - } - } - break; - case "provider2": - assertNull(node.getValue()); - children = node.getChildren(); - assertNotNull(children); - assertEquals(3, children.size()); - for (Node child : children) { - switch (child.getName()) { - case "URL": - assertEquals("provider2URL", child.getValue()); - break; - case "type": - assertEquals("provider2type", child.getValue()); - break; - case "name": - assertEquals("provider2Name", child.getValue()); - break; - default: - fail("Unknown child of " + node.getName() + " with value " + child.toString()); - } - } - break; - case "provider3": - /* - * Note that the helper normalizes any ordinal suffixes (003 became 3) - */ - assertNull(node.getValue()); - children = node.getChildren(); - assertNotNull(children); - assertEquals(3, children.size()); - for (Node child : children) { - switch (child.getName()) { - case "URL": - assertEquals("provider3URL", child.getValue()); - break; - case "type": - assertEquals("provider3type", child.getValue()); - break; - case "name": - assertEquals("provider3Name", child.getValue()); - break; - default: - fail("Unknown child of " + node.getName() + " with value " + child.toString()); - } - } - break; - default: - fail("Unknown provider " + node.toString()); - } - } - // System.out.println(nodes); - } - - /** - * Test a multi-dimensional namespace (3X3X3) - */ - @SuppressWarnings("nls") - @Test - public void testMultiLevelNamespace() { - nodes = StructuredPropertyHelper.getStructuredProperties(properties, "node"); - - assertNotNull(nodes); - assertFalse(nodes.isEmpty()); - - assertEquals(3, nodes.size()); - for (Node node : nodes) { - assertNull(node.getValue()); - List children = node.getChildren(); - assertNotNull(children); - assertEquals(3, children.size()); - for (Node child : children) { - assertNull(child.getValue()); - List grandChildren = child.getChildren(); - assertNotNull(grandChildren); - assertEquals(3, grandChildren.size()); - for (Node greatGrandChild : grandChildren) { - assertNull(greatGrandChild.getValue()); - List greatGrandChildren = greatGrandChild.getChildren(); - assertNotNull(greatGrandChildren); - assertEquals(1, greatGrandChildren.size()); - } - } - } - // System.out.println(nodes); - } -} diff --git a/appc-common/src/test/resources/org/onap/appc/i18n/TestAdditionalResources.properties b/appc-common/src/test/resources/org/onap/appc/i18n/TestAdditionalResources.properties new file mode 100644 index 000000000..3c0216aea --- /dev/null +++ b/appc-common/src/test/resources/org/onap/appc/i18n/TestAdditionalResources.properties @@ -0,0 +1,25 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +ADDITIONAL_RESOURCE=This is a message loaded from an additional resource bundle diff --git a/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_de.properties b/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_de.properties new file mode 100644 index 000000000..805b3dff0 --- /dev/null +++ b/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_de.properties @@ -0,0 +1,30 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# Message bundle for German (language de, no specific country) +# +# +MESSAGE_TEST=Eine Nachricht f\u00FCr Unit-Tests den Ressource-Manager, arg0 = {0}, arg1 = {1}, arg2 = {2} +TEST_001=Dies ist eine Testnachricht ohne Eins\u00FCtze bearbeitet werden! diff --git a/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_en_US.properties b/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_en_US.properties new file mode 100644 index 000000000..cd4582653 --- /dev/null +++ b/appc-common/src/test/resources/org/onap/appc/i18n/TestResources_en_US.properties @@ -0,0 +1,29 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# Message bundle for English - United States (en_US). This is also the default bundle if no other bundles are found. +# +MESSAGE_TEST=A message for unit testing the resource manager, arg0={0}, arg1={1}, arg2={2} +TEST_001=This is a test message with no inserts to be edited! diff --git a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestAdditionalResources.properties b/appc-common/src/test/resources/org/openecomp/appc/i18n/TestAdditionalResources.properties deleted file mode 100644 index 3c0216aea..000000000 --- a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestAdditionalResources.properties +++ /dev/null @@ -1,25 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -ADDITIONAL_RESOURCE=This is a message loaded from an additional resource bundle diff --git a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_de.properties b/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_de.properties deleted file mode 100644 index 805b3dff0..000000000 --- a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_de.properties +++ /dev/null @@ -1,30 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# -# Message bundle for German (language de, no specific country) -# -# -MESSAGE_TEST=Eine Nachricht f\u00FCr Unit-Tests den Ressource-Manager, arg0 = {0}, arg1 = {1}, arg2 = {2} -TEST_001=Dies ist eine Testnachricht ohne Eins\u00FCtze bearbeitet werden! diff --git a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_en_US.properties b/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_en_US.properties deleted file mode 100644 index cd4582653..000000000 --- a/appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_en_US.properties +++ /dev/null @@ -1,29 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# -# Message bundle for English - United States (en_US). This is also the default bundle if no other bundles are found. -# -MESSAGE_TEST=A message for unit testing the resource manager, arg0={0}, arg1={1}, arg2={2} -TEST_001=This is a test message with no inserts to be edited! diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/AppcDgUtilActivator.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/AppcDgUtilActivator.java new file mode 100644 index 000000000..486d475f4 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/AppcDgUtilActivator.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.onap.appc.dg.util; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class AppcDgUtilActivator implements BundleActivator { + + public void start(BundleContext context) { + System.out.println("Starting the bundle"); + } + + public void stop(BundleContext context) { + System.out.println("Stopping the bundle"); + } + +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/ExecuteNodeAction.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/ExecuteNodeAction.java new file mode 100644 index 000000000..38bc0955d --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/ExecuteNodeAction.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface ExecuteNodeAction extends SvcLogicJavaPlugin { + void getResource(Map params, SvcLogicContext ctx) throws APPCException; + + void postResource(Map params, SvcLogicContext ctx) throws APPCException; + + void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; + + void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; + void waitMethod(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/InputParameterValidation.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/InputParameterValidation.java new file mode 100644 index 000000000..714e12a03 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/InputParameterValidation.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface InputParameterValidation extends SvcLogicJavaPlugin { + + void validateAttribute(Map params, SvcLogicContext ctx) throws APPCException; + + void validateAttributeLength(Map params, SvcLogicContext ctx) throws APPCException; + + void validateAttributeCharacter(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/UpgradeStubNode.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/UpgradeStubNode.java new file mode 100644 index 000000000..4f0a80f5a --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/UpgradeStubNode.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface UpgradeStubNode extends SvcLogicJavaPlugin { + void handleUpgradeStub(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImpl.java new file mode 100644 index 000000000..b5dc40712 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImpl.java @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import org.onap.appc.dg.util.ExecuteNodeAction; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + + +public class ExecuteNodeActionImpl implements ExecuteNodeAction { + + private AAIService aaiService; + protected static AAIClient client; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ExecuteNodeActionImpl.class); + + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + public ExecuteNodeActionImpl() { + } + + /** + * initialize the SDNC adapter (AAIService) by building the context. + */ + private void initialize() { + getAAIservice(); + } + + private void getAAIservice() { + BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); + // Get AAIadapter reference + ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); + if (sref != null) { + logger.info("AAIService from bundlecontext"); + aaiService = (AAIService) bctx.getService(sref); + + } else { + logger.info("AAIService error from bundlecontext"); + logger.error(EELFResourceManager.format(Msg.AAI_CONNECTION_FAILED, "AAIService")); + } + } + + /** + * Method called in TestDG to test timeout scenario + * + * @param params waitTime time in millisecond DG is going to sleep + * @param ctx + * @throws APPCException + */ + @Override public void waitMethod(Map params, SvcLogicContext ctx) throws APPCException { + try { + String waitTime = params.get("waitTime"); + + logger.info("DG will waits for " + Long.parseLong(waitTime) + "milliseconds"); + Thread.sleep(Long.parseLong(waitTime)); + logger.info("DG waits for " + Long.parseLong(waitTime) + " milliseconds completed"); + } catch (InterruptedException e) { + logger.error("Error In ExecuteNodeActionImpl for waitMethod() due to InterruptedException: reason = " + e.getMessage()); + } + } + + @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { + initialize(); + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"); + if (logger.isDebugEnabled()) { + logger.debug("inside getResorce"); + logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); + } + client = aaiService; + try { + SvcLogicResource.QueryStatus response = + client.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("getResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting getResource======"); + } + } + + @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { + initialize(); + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"), att_name = params.get("attributeName"), att_value = + params.get("attributeValue"); + if (logger.isDebugEnabled()) { + logger.debug("inside postResource"); + logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); + logger.debug("Updating " + att_name + " to : " + att_value); + } + Map data = new HashMap(); + data.put(att_name, att_value); + client = aaiService; + + try { + SvcLogicResource.QueryStatus response = client.update(resourceType, resourceKey, data, ctx_prefix, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("postResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting postResource======"); + } + } + + @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { + initialize(); + String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); + + if (logger.isDebugEnabled()) { + logger.debug("inside deleteResource"); + logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); + } + client = aaiService; + try { + SvcLogicResource.QueryStatus response = client.delete(resourceType, resourceKey, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("deleteResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting deleteResource======"); + } + } + + @Override public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { + if (logger.isDebugEnabled()) { + logger.debug("Inside getVnfHierarchy======"); + } + //String ctx_prefix = params.get("prefix"); + String resourceKey = params.get("resourceKey"); + // String retrivalVnfKey = "vnf-id = '" + resourceKey + "' AND relationship-key = 'vserver.vserver-id'"; + String retrivalVnfKey = "generic-vnf.vnf-id = '" + resourceKey + "'"; + Map paramsVnf = new HashMap(); + paramsVnf.put("resourceType", "generic-vnf"); + paramsVnf.put("prefix", "vnfRetrived"); + paramsVnf.put("resourceKey", retrivalVnfKey); + logger.debug("Retrieving VNF details from A&AI"); + //Retrive all the relations of VNF + SvcLogicContext vnfCtx = new SvcLogicContext(); + getResource(paramsVnf, vnfCtx); + if (vnfCtx.getAttribute("getResource_result").equals("SUCCESS")) { + if (vnfCtx.getAttribute("vnfRetrived.heat-stack-id") != null) { + ctx.setAttribute("VNF.heat-stack-id", vnfCtx.getAttribute("vnfRetrived.heat-stack-id")); + } + ctx.setAttribute("vnf.type",vnfCtx.getAttribute("vnfRetrived.vnf-type")); + Map vnfHierarchyMap = new ConcurrentHashMap(); + + Map> vnfcHierarchyMap = new HashMap>(); + int vmCount = 0; + int vnfcCount = 0; + Set vmSet = null; + String vmURL = ""; + logger.debug("Parsing Vserver details from VNF relations"); + for (String ctxKeySet : vnfCtx + .getAttributeKeySet()) { //loop through relationship-list data, to get vserver relations + if (ctxKeySet.startsWith("vnfRetrived.") && vnfCtx.getAttribute(ctxKeySet).equalsIgnoreCase("vserver")) { + String vmKey = ctxKeySet.substring(0, ctxKeySet.length() - "related-to".length()); + String vserverID = null; + String tenantID = null; + String cloudOwner = null; + String cloudRegionId = null; + int relationshipLength = 0; + if (vnfCtx.getAttributeKeySet().contains(vmKey + "relationship-data_length")) { + relationshipLength = Integer.parseInt(vnfCtx.getAttribute(vmKey + "relationship-data_length")); + } + + for (int j = 0; j + < relationshipLength; j++) { //loop inside relationship data, to get vserver-id and tenant-id + String key = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-key"); + String value = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-value"); + vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value); + if ("vserver.vserver-id".equals(key)) { + vserverID = value; + } + if ("tenant.tenant-id".equals(key)) { + tenantID = value; + } + if ("cloud-region.cloud-owner".equals(key)) { + cloudOwner = value; + } + if ("cloud-region.cloud-region-id".equals(key)) { + cloudRegionId = value; + } + } + int relatedPropertyLength = 0; + if (vnfCtx.getAttributeKeySet().contains(vmKey + "related-to-property_length")) { + relatedPropertyLength = + Integer.parseInt(vnfCtx.getAttribute(vmKey + "related-to-property_length")); + } + for (int j = 0; + j < relatedPropertyLength; j++) { //loop inside related-to-property data, to get vserver-name + String key = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-key"); + String value = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-value"); + vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value); + } + //Retrive VM relations to find vnfc's + //VM to VNFC is 1 to 1 relation + String vmRetrivalKey = "vserver.vserver-id = '" + vserverID + "' AND tenant.tenant_id = '" + tenantID + "'" + "' AND cloud-region.cloud-owner = '" + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; + Map paramsVm = new HashMap(); + paramsVm.put("resourceType", "vserver"); + paramsVm.put("prefix", "vmRetrived"); + paramsVm.put("resourceKey", vmRetrivalKey); + SvcLogicContext vmCtx = new SvcLogicContext(); + + logger.debug("Retrieving VM details from A&AI"); + getResource(paramsVm, vmCtx); + if (vmCtx.getAttribute("getResource_result").equals("SUCCESS")) { + if (logger.isDebugEnabled()) { + logger.debug("Parsing VNFC details from VM relations"); + } + vmURL = vmCtx.getAttribute("vmRetrived.vserver-selflink"); + vnfHierarchyMap.put("VNF.VM[" + vmCount + "].URL",vmURL); + for (String ctxVnfcKeySet : vmCtx + .getAttributeKeySet()) { //loop through relationship-list data, to get vnfc relations + if (ctxVnfcKeySet.startsWith("vmRetrived.") && vmCtx.getAttribute(ctxVnfcKeySet) + .equalsIgnoreCase("vnfc")) { + String vnfcKey = ctxVnfcKeySet.substring(0, + ctxVnfcKeySet.length() - "related-to".length()); + relationshipLength = 0; + if (vmCtx.getAttributeKeySet().contains(vnfcKey + "relationship-data_length")) { + relationshipLength = Integer.parseInt( + vmCtx.getAttribute(vnfcKey + "relationship-data_length")); + } + for (int j = 0; j + < relationshipLength; j++) { //loop through relationship data, to get vnfc name + String key = vmCtx.getAttribute( + vnfcKey + "relationship-data[" + j + "].relationship-key"); + String value = vmCtx.getAttribute( + vnfcKey + "relationship-data[" + j + "].relationship-value"); + if (key.equalsIgnoreCase("vnfc.vnfc-name")) { + vnfHierarchyMap.put("VNF.VM[" + vmCount + "].VNFC", value); + vmSet = vnfcHierarchyMap.get(value); + if(vmSet == null){ + vmSet = new HashSet<>(); + } + vmSet.add(vmURL); + vnfcHierarchyMap.put(value,vmSet); + break; //VM to VNFC is 1 to 1 relation, once we got the VNFC name we can break the loop + } + } + } + } + } else { + ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy"); + vnfHierarchyMap.put("getVnfHierarchy_result", "FAILURE"); + logger.error("Failed in getVnfHierarchy, Error retrieving Vserver details. Error message: " + + vmCtx.getAttribute("getResource_result")); + logger.warn("Incorrect or Incomplete VNF Hierarchy"); + throw new APPCException("Error Retrieving VNFC hierarchy"); + } + vmCount++; + } + } + vnfHierarchyMap.put("VNF.VMCount", vmCount + ""); + if (vmCount == 0) { + ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "VM count is 0"); + } + //code changes for getting vnfcs hirearchy + populateVnfcsDetailsinContext(vnfcHierarchyMap,ctx); + //vnf,vnfcCount + ctx.setAttribute("VNF.VNFCCount", + Integer.toString(vnfcHierarchyMap.size())); + //code changes for getting vnfcs hirearchy + ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); + //Finally set all attributes to ctx + for (String attribute : vnfHierarchyMap.keySet()) { + ctx.setAttribute(attribute, vnfHierarchyMap.get(attribute)); + } + } else { + ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); + ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy"); + logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx + .getAttribute("getResource_result")); + logger.warn("Incorrect or Incomplete VNF Hierarchy"); + throw new APPCException("Error Retrieving VNFC hierarchy"); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting getVnfHierarchy======"); + } + } + + private void populateVnfcsDetailsinContext(Map> vnfcHierarchyMap, SvcLogicContext ctx) throws APPCException { +// int vnfcCount = vnfcHierarchyMap.size(); + SvcLogicContext vnfcCtx = new SvcLogicContext(); + int vnfcCounter = 0; + for (String vnfcName : vnfcHierarchyMap.keySet()) { + String vnfcRetrivalKey = "vnfc-name = '" + vnfcName + "'"; + Map paramsVnfc = new HashMap(); + paramsVnfc.put("resourceType", "vnfc"); + paramsVnfc.put("prefix", "vnfcRetrived"); + paramsVnfc.put("resourceKey", vnfcRetrivalKey); + + logger.debug("Retrieving VM details from A&AI"); + getResource(paramsVnfc, vnfcCtx); + if (vnfcCtx.getAttribute("getResource_result").equals("SUCCESS")) { + if (logger.isDebugEnabled()) { + logger.debug("Parsing VNFC details from VM relations"); + } + //putting required values in the map + //vnf.vnfc[vnfcIndex].type + ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].TYPE", + vnfcCtx.getAttribute("vnfcRetrived.vnfc-type")); + + // vnf.vnfc[vnfcIndex].name + ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].NAME", + vnfcCtx.getAttribute("vnfcRetrived.vnfc-name")); + + //vnf.vnfc[vnfcIndex].vmCount + Set vmSet = vnfcHierarchyMap.get(vnfcName); + String vmCountinVnfcs = Integer.toString(vmSet.size()); + ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM_COUNT", + vmCountinVnfcs); + int vmCount =0; + for(String vmURL:vmSet){ + ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM[" + vmCount++ + "].URL",vmURL); + } + + } + vnfcCounter++; + } + } +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/InputParameterValidationImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/InputParameterValidationImpl.java new file mode 100644 index 000000000..5ea48bf44 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/InputParameterValidationImpl.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import org.onap.appc.dg.util.InputParameterValidation; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class InputParameterValidationImpl implements InputParameterValidation +{ + private static final char NL = '\n'; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(InputParameterValidationImpl.class); + + public InputParameterValidationImpl() { + } + + + @SuppressWarnings("nls") + @Override + public void validateAttribute(Map params, SvcLogicContext ctx) throws APPCException { + Map contextParams=getValueFromContext(ctx); + boolean isSuccess = true; + try { + for (String k : params.keySet()) { + logger.info("validating attribute " + k); + if (!contextParams.containsKey(k)) { + logger.info("missing attribute " + k); + isSuccess =false; + } + if(contextParams.get(k)==null){ + logger.info("mandatory attribute " + k+ "is null"); + isSuccess =false; + } + } + }catch (NullPointerException np) { + isSuccess =false; + } + ctx.setAttribute("validateAttribute", String.valueOf(isSuccess)); + } + + @SuppressWarnings("nls") + @Override + public void validateAttributeLength(Map params, SvcLogicContext ctx) throws APPCException { + Map contextParams=getValueFromContext(ctx); + boolean isSuccess =true; + try { + int maxLength = Integer.parseInt(params.get("maximum_length_param")); + params.remove("maximum_length_param"); + + for (String k : params.keySet()) { + logger.info("validating attribute " + k); + if(contextParams.get(k).length() > maxLength){ + logger.info("attribute " + k+ "'s length is exceeding Maximum limit of " + maxLength +" character"); + isSuccess=false; + } + } + }catch (NullPointerException np) { + isSuccess=false; + } + ctx.setAttribute("validateAttributeLength", String.valueOf(isSuccess)); + } + + @SuppressWarnings("nls") + @Override + public void validateAttributeCharacter(Map params, SvcLogicContext ctx) throws APPCException { + Map contextParams=getValueFromContext(ctx); + boolean isSuccess =true; + try { + String specialCharacter = params.get("special_characters"); + String pattern = ".*[" + Pattern.quote(specialCharacter) + "].*"; + params.remove("special_characters"); + + for (String k : params.keySet()) { + logger.info("validating attribute " + k); + if(contextParams.get(k).matches(pattern)){ + logger.info("attribute " + k + " contains any of these " + specialCharacter + " special character "); + isSuccess =false; + } + + } + }catch (NullPointerException np) { + isSuccess =false; + } + ctx.setAttribute("validateAttributeCharacter", String.valueOf(isSuccess)); + } + + + private Map getValueFromContext(SvcLogicContext context) { + Set keys = context.getAttributeKeySet(); + Map params = new HashMap(); + StringBuilder builder = new StringBuilder(); + if (keys != null && !keys.isEmpty()) { + builder.append(NL); + for (String key : keys) { + String value = context.getAttribute(key); + params.put(key,value); + + } + } + return params; + + } + + +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImpl.java new file mode 100644 index 000000000..a7e650e9f --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImpl.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import java.util.Map; + +import org.onap.appc.dg.util.UpgradeStubNode; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class UpgradeStubNodeImpl implements UpgradeStubNode { + + public static final String FAILURE_INDICATOR_FIELD_NAME = "failureIndicator"; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(UpgradeStubNodeImpl.class); + + @Override + public void handleUpgradeStub(Map params, SvcLogicContext ctx) throws APPCException { + logger.debug("Entering in handleUpgradeStub : "+ params.toString()); + String failureInd = params.get(FAILURE_INDICATOR_FIELD_NAME); + if (null != failureInd && Boolean.valueOf(failureInd)){ + throw new APPCException("Simulating exception..."); + } + logger.info("Simulating was successful"); + } +} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/AppcDgUtilActivator.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/AppcDgUtilActivator.java deleted file mode 100644 index 486d475f4..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/AppcDgUtilActivator.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.onap.appc.dg.util; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -public class AppcDgUtilActivator implements BundleActivator { - - public void start(BundleContext context) { - System.out.println("Starting the bundle"); - } - - public void stop(BundleContext context) { - System.out.println("Stopping the bundle"); - } - -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/ExecuteNodeAction.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/ExecuteNodeAction.java deleted file mode 100644 index 38bc0955d..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/ExecuteNodeAction.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface ExecuteNodeAction extends SvcLogicJavaPlugin { - void getResource(Map params, SvcLogicContext ctx) throws APPCException; - - void postResource(Map params, SvcLogicContext ctx) throws APPCException; - - void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; - - void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; - void waitMethod(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/InputParameterValidation.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/InputParameterValidation.java deleted file mode 100644 index 714e12a03..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/InputParameterValidation.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface InputParameterValidation extends SvcLogicJavaPlugin { - - void validateAttribute(Map params, SvcLogicContext ctx) throws APPCException; - - void validateAttributeLength(Map params, SvcLogicContext ctx) throws APPCException; - - void validateAttributeCharacter(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/UpgradeStubNode.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/UpgradeStubNode.java deleted file mode 100644 index 4f0a80f5a..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/UpgradeStubNode.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface UpgradeStubNode extends SvcLogicJavaPlugin { - void handleUpgradeStub(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImpl.java deleted file mode 100644 index b5dc40712..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImpl.java +++ /dev/null @@ -1,362 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import org.onap.appc.dg.util.ExecuteNodeAction; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - - -public class ExecuteNodeActionImpl implements ExecuteNodeAction { - - private AAIService aaiService; - protected static AAIClient client; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ExecuteNodeActionImpl.class); - - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - public ExecuteNodeActionImpl() { - } - - /** - * initialize the SDNC adapter (AAIService) by building the context. - */ - private void initialize() { - getAAIservice(); - } - - private void getAAIservice() { - BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); - // Get AAIadapter reference - ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); - if (sref != null) { - logger.info("AAIService from bundlecontext"); - aaiService = (AAIService) bctx.getService(sref); - - } else { - logger.info("AAIService error from bundlecontext"); - logger.error(EELFResourceManager.format(Msg.AAI_CONNECTION_FAILED, "AAIService")); - } - } - - /** - * Method called in TestDG to test timeout scenario - * - * @param params waitTime time in millisecond DG is going to sleep - * @param ctx - * @throws APPCException - */ - @Override public void waitMethod(Map params, SvcLogicContext ctx) throws APPCException { - try { - String waitTime = params.get("waitTime"); - - logger.info("DG will waits for " + Long.parseLong(waitTime) + "milliseconds"); - Thread.sleep(Long.parseLong(waitTime)); - logger.info("DG waits for " + Long.parseLong(waitTime) + " milliseconds completed"); - } catch (InterruptedException e) { - logger.error("Error In ExecuteNodeActionImpl for waitMethod() due to InterruptedException: reason = " + e.getMessage()); - } - } - - @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { - initialize(); - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"); - if (logger.isDebugEnabled()) { - logger.debug("inside getResorce"); - logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); - } - client = aaiService; - try { - SvcLogicResource.QueryStatus response = - client.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("getResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting getResource======"); - } - } - - @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { - initialize(); - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"), att_name = params.get("attributeName"), att_value = - params.get("attributeValue"); - if (logger.isDebugEnabled()) { - logger.debug("inside postResource"); - logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); - logger.debug("Updating " + att_name + " to : " + att_value); - } - Map data = new HashMap(); - data.put(att_name, att_value); - client = aaiService; - - try { - SvcLogicResource.QueryStatus response = client.update(resourceType, resourceKey, data, ctx_prefix, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("postResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting postResource======"); - } - } - - @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { - initialize(); - String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); - - if (logger.isDebugEnabled()) { - logger.debug("inside deleteResource"); - logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); - } - client = aaiService; - try { - SvcLogicResource.QueryStatus response = client.delete(resourceType, resourceKey, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("deleteResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting deleteResource======"); - } - } - - @Override public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { - if (logger.isDebugEnabled()) { - logger.debug("Inside getVnfHierarchy======"); - } - //String ctx_prefix = params.get("prefix"); - String resourceKey = params.get("resourceKey"); - // String retrivalVnfKey = "vnf-id = '" + resourceKey + "' AND relationship-key = 'vserver.vserver-id'"; - String retrivalVnfKey = "generic-vnf.vnf-id = '" + resourceKey + "'"; - Map paramsVnf = new HashMap(); - paramsVnf.put("resourceType", "generic-vnf"); - paramsVnf.put("prefix", "vnfRetrived"); - paramsVnf.put("resourceKey", retrivalVnfKey); - logger.debug("Retrieving VNF details from A&AI"); - //Retrive all the relations of VNF - SvcLogicContext vnfCtx = new SvcLogicContext(); - getResource(paramsVnf, vnfCtx); - if (vnfCtx.getAttribute("getResource_result").equals("SUCCESS")) { - if (vnfCtx.getAttribute("vnfRetrived.heat-stack-id") != null) { - ctx.setAttribute("VNF.heat-stack-id", vnfCtx.getAttribute("vnfRetrived.heat-stack-id")); - } - ctx.setAttribute("vnf.type",vnfCtx.getAttribute("vnfRetrived.vnf-type")); - Map vnfHierarchyMap = new ConcurrentHashMap(); - - Map> vnfcHierarchyMap = new HashMap>(); - int vmCount = 0; - int vnfcCount = 0; - Set vmSet = null; - String vmURL = ""; - logger.debug("Parsing Vserver details from VNF relations"); - for (String ctxKeySet : vnfCtx - .getAttributeKeySet()) { //loop through relationship-list data, to get vserver relations - if (ctxKeySet.startsWith("vnfRetrived.") && vnfCtx.getAttribute(ctxKeySet).equalsIgnoreCase("vserver")) { - String vmKey = ctxKeySet.substring(0, ctxKeySet.length() - "related-to".length()); - String vserverID = null; - String tenantID = null; - String cloudOwner = null; - String cloudRegionId = null; - int relationshipLength = 0; - if (vnfCtx.getAttributeKeySet().contains(vmKey + "relationship-data_length")) { - relationshipLength = Integer.parseInt(vnfCtx.getAttribute(vmKey + "relationship-data_length")); - } - - for (int j = 0; j - < relationshipLength; j++) { //loop inside relationship data, to get vserver-id and tenant-id - String key = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-key"); - String value = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-value"); - vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value); - if ("vserver.vserver-id".equals(key)) { - vserverID = value; - } - if ("tenant.tenant-id".equals(key)) { - tenantID = value; - } - if ("cloud-region.cloud-owner".equals(key)) { - cloudOwner = value; - } - if ("cloud-region.cloud-region-id".equals(key)) { - cloudRegionId = value; - } - } - int relatedPropertyLength = 0; - if (vnfCtx.getAttributeKeySet().contains(vmKey + "related-to-property_length")) { - relatedPropertyLength = - Integer.parseInt(vnfCtx.getAttribute(vmKey + "related-to-property_length")); - } - for (int j = 0; - j < relatedPropertyLength; j++) { //loop inside related-to-property data, to get vserver-name - String key = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-key"); - String value = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-value"); - vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value); - } - //Retrive VM relations to find vnfc's - //VM to VNFC is 1 to 1 relation - String vmRetrivalKey = "vserver.vserver-id = '" + vserverID + "' AND tenant.tenant_id = '" + tenantID + "'" + "' AND cloud-region.cloud-owner = '" + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; - Map paramsVm = new HashMap(); - paramsVm.put("resourceType", "vserver"); - paramsVm.put("prefix", "vmRetrived"); - paramsVm.put("resourceKey", vmRetrivalKey); - SvcLogicContext vmCtx = new SvcLogicContext(); - - logger.debug("Retrieving VM details from A&AI"); - getResource(paramsVm, vmCtx); - if (vmCtx.getAttribute("getResource_result").equals("SUCCESS")) { - if (logger.isDebugEnabled()) { - logger.debug("Parsing VNFC details from VM relations"); - } - vmURL = vmCtx.getAttribute("vmRetrived.vserver-selflink"); - vnfHierarchyMap.put("VNF.VM[" + vmCount + "].URL",vmURL); - for (String ctxVnfcKeySet : vmCtx - .getAttributeKeySet()) { //loop through relationship-list data, to get vnfc relations - if (ctxVnfcKeySet.startsWith("vmRetrived.") && vmCtx.getAttribute(ctxVnfcKeySet) - .equalsIgnoreCase("vnfc")) { - String vnfcKey = ctxVnfcKeySet.substring(0, - ctxVnfcKeySet.length() - "related-to".length()); - relationshipLength = 0; - if (vmCtx.getAttributeKeySet().contains(vnfcKey + "relationship-data_length")) { - relationshipLength = Integer.parseInt( - vmCtx.getAttribute(vnfcKey + "relationship-data_length")); - } - for (int j = 0; j - < relationshipLength; j++) { //loop through relationship data, to get vnfc name - String key = vmCtx.getAttribute( - vnfcKey + "relationship-data[" + j + "].relationship-key"); - String value = vmCtx.getAttribute( - vnfcKey + "relationship-data[" + j + "].relationship-value"); - if (key.equalsIgnoreCase("vnfc.vnfc-name")) { - vnfHierarchyMap.put("VNF.VM[" + vmCount + "].VNFC", value); - vmSet = vnfcHierarchyMap.get(value); - if(vmSet == null){ - vmSet = new HashSet<>(); - } - vmSet.add(vmURL); - vnfcHierarchyMap.put(value,vmSet); - break; //VM to VNFC is 1 to 1 relation, once we got the VNFC name we can break the loop - } - } - } - } - } else { - ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy"); - vnfHierarchyMap.put("getVnfHierarchy_result", "FAILURE"); - logger.error("Failed in getVnfHierarchy, Error retrieving Vserver details. Error message: " - + vmCtx.getAttribute("getResource_result")); - logger.warn("Incorrect or Incomplete VNF Hierarchy"); - throw new APPCException("Error Retrieving VNFC hierarchy"); - } - vmCount++; - } - } - vnfHierarchyMap.put("VNF.VMCount", vmCount + ""); - if (vmCount == 0) { - ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "VM count is 0"); - } - //code changes for getting vnfcs hirearchy - populateVnfcsDetailsinContext(vnfcHierarchyMap,ctx); - //vnf,vnfcCount - ctx.setAttribute("VNF.VNFCCount", - Integer.toString(vnfcHierarchyMap.size())); - //code changes for getting vnfcs hirearchy - ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); - //Finally set all attributes to ctx - for (String attribute : vnfHierarchyMap.keySet()) { - ctx.setAttribute(attribute, vnfHierarchyMap.get(attribute)); - } - } else { - ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); - ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy"); - logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx - .getAttribute("getResource_result")); - logger.warn("Incorrect or Incomplete VNF Hierarchy"); - throw new APPCException("Error Retrieving VNFC hierarchy"); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting getVnfHierarchy======"); - } - } - - private void populateVnfcsDetailsinContext(Map> vnfcHierarchyMap, SvcLogicContext ctx) throws APPCException { -// int vnfcCount = vnfcHierarchyMap.size(); - SvcLogicContext vnfcCtx = new SvcLogicContext(); - int vnfcCounter = 0; - for (String vnfcName : vnfcHierarchyMap.keySet()) { - String vnfcRetrivalKey = "vnfc-name = '" + vnfcName + "'"; - Map paramsVnfc = new HashMap(); - paramsVnfc.put("resourceType", "vnfc"); - paramsVnfc.put("prefix", "vnfcRetrived"); - paramsVnfc.put("resourceKey", vnfcRetrivalKey); - - logger.debug("Retrieving VM details from A&AI"); - getResource(paramsVnfc, vnfcCtx); - if (vnfcCtx.getAttribute("getResource_result").equals("SUCCESS")) { - if (logger.isDebugEnabled()) { - logger.debug("Parsing VNFC details from VM relations"); - } - //putting required values in the map - //vnf.vnfc[vnfcIndex].type - ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].TYPE", - vnfcCtx.getAttribute("vnfcRetrived.vnfc-type")); - - // vnf.vnfc[vnfcIndex].name - ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].NAME", - vnfcCtx.getAttribute("vnfcRetrived.vnfc-name")); - - //vnf.vnfc[vnfcIndex].vmCount - Set vmSet = vnfcHierarchyMap.get(vnfcName); - String vmCountinVnfcs = Integer.toString(vmSet.size()); - ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM_COUNT", - vmCountinVnfcs); - int vmCount =0; - for(String vmURL:vmSet){ - ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM[" + vmCount++ + "].URL",vmURL); - } - - } - vnfcCounter++; - } - } -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImpl.java deleted file mode 100644 index 5ea48bf44..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImpl.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.onap.appc.dg.util.InputParameterValidation; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class InputParameterValidationImpl implements InputParameterValidation -{ - private static final char NL = '\n'; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(InputParameterValidationImpl.class); - - public InputParameterValidationImpl() { - } - - - @SuppressWarnings("nls") - @Override - public void validateAttribute(Map params, SvcLogicContext ctx) throws APPCException { - Map contextParams=getValueFromContext(ctx); - boolean isSuccess = true; - try { - for (String k : params.keySet()) { - logger.info("validating attribute " + k); - if (!contextParams.containsKey(k)) { - logger.info("missing attribute " + k); - isSuccess =false; - } - if(contextParams.get(k)==null){ - logger.info("mandatory attribute " + k+ "is null"); - isSuccess =false; - } - } - }catch (NullPointerException np) { - isSuccess =false; - } - ctx.setAttribute("validateAttribute", String.valueOf(isSuccess)); - } - - @SuppressWarnings("nls") - @Override - public void validateAttributeLength(Map params, SvcLogicContext ctx) throws APPCException { - Map contextParams=getValueFromContext(ctx); - boolean isSuccess =true; - try { - int maxLength = Integer.parseInt(params.get("maximum_length_param")); - params.remove("maximum_length_param"); - - for (String k : params.keySet()) { - logger.info("validating attribute " + k); - if(contextParams.get(k).length() > maxLength){ - logger.info("attribute " + k+ "'s length is exceeding Maximum limit of " + maxLength +" character"); - isSuccess=false; - } - } - }catch (NullPointerException np) { - isSuccess=false; - } - ctx.setAttribute("validateAttributeLength", String.valueOf(isSuccess)); - } - - @SuppressWarnings("nls") - @Override - public void validateAttributeCharacter(Map params, SvcLogicContext ctx) throws APPCException { - Map contextParams=getValueFromContext(ctx); - boolean isSuccess =true; - try { - String specialCharacter = params.get("special_characters"); - String pattern = ".*[" + Pattern.quote(specialCharacter) + "].*"; - params.remove("special_characters"); - - for (String k : params.keySet()) { - logger.info("validating attribute " + k); - if(contextParams.get(k).matches(pattern)){ - logger.info("attribute " + k + " contains any of these " + specialCharacter + " special character "); - isSuccess =false; - } - - } - }catch (NullPointerException np) { - isSuccess =false; - } - ctx.setAttribute("validateAttributeCharacter", String.valueOf(isSuccess)); - } - - - private Map getValueFromContext(SvcLogicContext context) { - Set keys = context.getAttributeKeySet(); - Map params = new HashMap(); - StringBuilder builder = new StringBuilder(); - if (keys != null && !keys.isEmpty()) { - builder.append(NL); - for (String key : keys) { - String value = context.getAttribute(key); - params.put(key,value); - - } - } - return params; - - } - - -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImpl.java b/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImpl.java deleted file mode 100644 index a7e650e9f..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import java.util.Map; - -import org.onap.appc.dg.util.UpgradeStubNode; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class UpgradeStubNodeImpl implements UpgradeStubNode { - - public static final String FAILURE_INDICATOR_FIELD_NAME = "failureIndicator"; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(UpgradeStubNodeImpl.class); - - @Override - public void handleUpgradeStub(Map params, SvcLogicContext ctx) throws APPCException { - logger.debug("Entering in handleUpgradeStub : "+ params.toString()); - String failureInd = params.get(FAILURE_INDICATOR_FIELD_NAME); - if (null != failureInd && Boolean.valueOf(failureInd)){ - throw new APPCException("Simulating exception..."); - } - logger.info("Simulating was successful"); - } -} diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/onap/appc/default.properties b/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..0185c72a9 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,29 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. +# diff --git a/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 0185c72a9..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,29 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. -# diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/AppcDgUtilActivatorTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/AppcDgUtilActivatorTest.java new file mode 100644 index 000000000..066863bb8 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/AppcDgUtilActivatorTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.osgi.framework.BundleContext; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class AppcDgUtilActivatorTest { + + @Mock + private BundleContext bundleContext; + + private AppcDgUtilActivator appcDgUtilActivator; + + @Before + public void setUp() throws Exception { + appcDgUtilActivator = new AppcDgUtilActivator(); + } + + @Test + public void start() { + appcDgUtilActivator.start(bundleContext); + PowerMockito.verifyStatic(); + } + + @Test + public void stop() { + appcDgUtilActivator.stop(bundleContext); + PowerMockito.verifyStatic(); + } +} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImplTest.java new file mode 100644 index 000000000..3280cb954 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/ExecuteNodeActionImplTest.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.appc.exceptions.APPCException; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ExecuteNodeActionImpl.class, FrameworkUtil.class, Thread.class}) +public class ExecuteNodeActionImplTest { + @Spy + private ExecuteNodeActionImpl mockedExecuteNodeActionImpl = new ExecuteNodeActionImpl(); + @Mock + private EELFLogger eelfLogger; + @Mock + private AAIService aaiService; + + private final String resourceType = "resourceType"; + private final String prefix = "prefix"; + private final String resourceKey = "resourceKey"; + private final String attributeName = "attributeName"; + private final String attributeValue = "attributeValue"; + + private Map params = new HashMap<>(); + private SvcLogicContext svcLogicContext = new SvcLogicContext(); + private SvcLogicResource.QueryStatus queryStatus = SvcLogicResource.QueryStatus.SUCCESS; + + + @Before + public void setUp() throws Exception { + Whitebox.setInternalState(mockedExecuteNodeActionImpl, "aaiService", aaiService); + + params.put("resourceType", resourceType); + params.put("prefix", prefix); + params.put("resourceKey", resourceKey); + params.put("attributeName", attributeName); + params.put("attributeValue", attributeValue); + } + + @Test + public void testInitialize() throws Exception { + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "getAAIservice"); + Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "initialize"); + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("getAAIservice"); + } + + @Test + public void testGetAAIservice() throws Exception { + // sref is not null + mockStatic(FrameworkUtil.class); + Bundle mockedBundle = mock(Bundle.class); + BundleContext mockedBundleContext = mock(BundleContext.class); + ServiceReference mockedServiceReference = mock(ServiceReference.class); + PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(mockedBundle); + PowerMockito.doReturn(mockedBundleContext).when(mockedBundle).getBundleContext(); + PowerMockito.doReturn(mockedServiceReference).when(mockedBundleContext) + .getServiceReference(AAIService.class.getName()); + + Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "getAAIservice"); + verify(mockedBundleContext, times(1)).getService(mockedServiceReference); + + // sref is null + PowerMockito.doReturn(null).when(mockedBundleContext) + .getServiceReference(AAIService.class.getName()); + Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "getAAIservice"); + verify(mockedBundleContext, times(1)).getService(mockedServiceReference); + } + + @Test + public void testWaitMethod() throws Exception { + mockStatic(Thread.class); + params.put("waitTime", "1"); + mockedExecuteNodeActionImpl.waitMethod(params, svcLogicContext); + verifyStatic(times(1)); + } + + @Test + public void testGetResource() throws Exception { + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + PowerMockito.doReturn(queryStatus).when(aaiService).query(resourceType, false, null, + resourceKey, prefix, null, svcLogicContext); + + mockedExecuteNodeActionImpl.getResource(params, svcLogicContext); + + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + verify(aaiService, times(1)).query(resourceType, false, null, + resourceKey, prefix, null, svcLogicContext); + assertEquals(queryStatus.toString(), svcLogicContext.getAttribute("getResource_result")); + } + + @Test + public void testPostResource() throws Exception { + + + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + PowerMockito.doReturn(queryStatus).when(aaiService).update(eq(resourceType), eq(resourceKey), anyMap(), + eq(prefix), eq(svcLogicContext)); + + mockedExecuteNodeActionImpl.postResource(params, svcLogicContext); + + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + verify(aaiService, times(1)).update(eq(resourceType), eq(resourceKey), anyMap(), + eq(prefix), eq(svcLogicContext)); + assertEquals(svcLogicContext.getAttribute("postResource_result"), queryStatus.toString()); + } + + @Test + public void testDeleteResource() throws Exception { + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + + PowerMockito.doReturn(queryStatus).when(aaiService).delete(eq(resourceType), eq(resourceKey), + eq(svcLogicContext)); + + mockedExecuteNodeActionImpl.deleteResource(params, svcLogicContext); + + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + verify(aaiService, times(1)).delete(eq(resourceType), eq(resourceKey), + eq(svcLogicContext)); + assertEquals(svcLogicContext.getAttribute("deleteResource_result"), queryStatus.toString()); + } + + @Test + public void testGetVnfHierarchySuccess() throws Exception { + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", anyMap(), eq + (svcLogicContext)); + PowerMockito.when(aaiService.query(any(), eq(false), anyString(), any(), any(), anyString(), + any(SvcLogicContext.class))).thenReturn(queryStatus); + + mockedExecuteNodeActionImpl.getVnfHierarchy(params, svcLogicContext); + + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + assertEquals("0", svcLogicContext.getAttribute("VNF.VNFCCount")); + assertEquals("SUCCESS", svcLogicContext.getAttribute("getVnfHierarchy_result")); + } + + @Test(expected = APPCException.class) + public void testGetVnfHierarchyFailure() throws Exception { + queryStatus = SvcLogicResource.QueryStatus.FAILURE; + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", anyMap(), + eq(svcLogicContext)); + PowerMockito.when(aaiService.query(any(), eq(false), anyString(), any(), any(), anyString(), + any(SvcLogicContext.class))).thenReturn(queryStatus); + + mockedExecuteNodeActionImpl.getVnfHierarchy(params, svcLogicContext); + + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + assertEquals("0", svcLogicContext.getAttribute("VNF.VNFCCount")); + assertEquals("FAILURE", svcLogicContext.getAttribute("getVnfHierarchy_result")); + assertTrue(svcLogicContext.getAttribute("output.status.message") != null); + } + + @Test + public void testPopulateVnfcsDetailsinContext() throws Exception { + Map> vnfcHierarchyMap = new HashMap<>(); + Set vServersList = new HashSet<>(); + vnfcHierarchyMap.put("SMP", vServersList); + vServersList.add("smp-0-url"); + vServersList.add("smp-1-url"); + + PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); + PowerMockito.when(aaiService.query(eq("vnfc"), eq(false), anyString(), + eq("vnfc-name = 'SMP'"), eq("vnfcRetrived"), anyString(), any(SvcLogicContext.class))) + .thenReturn(queryStatus); + + Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", + vnfcHierarchyMap, svcLogicContext); + + verify(mockedExecuteNodeActionImpl, times(1)).getResource(anyMap(), + any(SvcLogicContext.class)); + verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); + assertEquals(null, svcLogicContext.getAttribute("VNF.VNFC[0].TYPE")); + assertEquals(null, svcLogicContext.getAttribute("VNF.VNFC[0].NAME")); + assertEquals("2", svcLogicContext.getAttribute("VNF.VNFC[0].VM_COUNT")); + assertTrue(vServersList.contains(svcLogicContext.getAttribute("VNF.VNFC[0].VM[0].URL"))); + assertTrue(vServersList.contains(svcLogicContext.getAttribute("VNF.VNFC[0].VM[1].URL"))); + } +} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/InputParameterValidationImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/InputParameterValidationImplTest.java new file mode 100644 index 000000000..405c1d92a --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/InputParameterValidationImplTest.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.powermock.reflect.Whitebox; + +import java.util.HashMap; +import java.util.Map; + +public class InputParameterValidationImplTest { + private SvcLogicContext svcLogicContext; + + private InputParameterValidationImpl inputParameterValidation; + + @Before + public void setUp() throws Exception { + inputParameterValidation = new InputParameterValidationImpl(); + svcLogicContext = new SvcLogicContext(); + svcLogicContext.setAttribute("a", "b"); + svcLogicContext.setAttribute("b", "c"); + } + + @Test + public void validateAttributeSuccess() throws Exception { + Map params = new HashMap<>(); + params.put("a", "b"); + params.put("b", "c"); + + inputParameterValidation.validateAttribute(params, svcLogicContext); + + Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttribute")); + } + + @Test + public void validateAttributeFailure() throws Exception { + // wrong value + Map params = new HashMap<>(); + params.put("e", "f"); + + inputParameterValidation.validateAttribute(params, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); + + // null value + params = new HashMap<>(); + params.put("e", null); + + inputParameterValidation.validateAttribute(params, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); + } + + @Test + public void validateAttributeNull() throws Exception { + inputParameterValidation.validateAttribute(null, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); + } + + @Test + public void validateAttributeLengthSuccess() throws Exception { + Map params = new HashMap<>(); + params.put("maximum_length_param", "2"); + params.put("a", "1"); + + inputParameterValidation.validateAttributeLength(params, svcLogicContext); + + Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttributeLength")); + } + + @Test + public void validateAttributeLengthFailure() throws Exception { + // wrong key + Map params = new HashMap<>(); + params.put("maximum_length_param", "2"); + params.put("e", "1"); + + inputParameterValidation.validateAttributeLength(params, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); + + //over length + params = new HashMap<>(); + params.put("maximum_length_param", "2"); + params.put("c", "3"); + + inputParameterValidation.validateAttributeLength(params, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); + } + + @Test + public void validateAttributeLengthNull() throws Exception { + inputParameterValidation.validateAttributeLength(null, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); + } + + @Test + public void validateAttributeCharacterSuccess() throws Exception { + Map params = new HashMap<>(); + params.put("special_characters", "z"); + params.put("a", "1"); + + inputParameterValidation.validateAttributeCharacter(params, svcLogicContext); + + Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttributeCharacter")); + } + + @Test + public void validateAttributeCharacterFailure() throws Exception { + Map params = new HashMap<>(); + params.put("special_characters", "z"); + params.put("d", "1"); + + inputParameterValidation.validateAttributeCharacter(params, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeCharacter")); + } + + @Test + public void validateAttributeCharacterNull() throws Exception { + inputParameterValidation.validateAttributeCharacter(null, svcLogicContext); + + Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeCharacter")); + } + + @Test + public void testGetValueFromContext() throws Exception { + Map result = Whitebox.invokeMethod(inputParameterValidation, "getValueFromContext", + svcLogicContext); + Assert.assertEquals("b", result.get("a")); + Assert.assertEquals("c", result.get("b")); + } +} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImplTest.java new file mode 100644 index 000000000..6eb732064 --- /dev/null +++ b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/onap/appc/dg/util/impl/UpgradeStubNodeImplTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.util.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; + +import java.util.HashMap; +import java.util.Map; + +public class UpgradeStubNodeImplTest { + @Mock + private SvcLogicContext svcLogicContext; + + private UpgradeStubNodeImpl upgradeStubNode; + + @Before + public void setUp() throws Exception { + upgradeStubNode = new UpgradeStubNodeImpl(); + } + + @Test + public void testHandleUpgradeStubSuccess() throws APPCException { + Map params = new HashMap<>(); + upgradeStubNode.handleUpgradeStub(params, svcLogicContext); + } + + @Test(expected = APPCException.class) + public void testHandleUpgradeStubException() throws APPCException { + Map params = new HashMap<>(); + params.put("failureIndicator", "true"); + upgradeStubNode.handleUpgradeStub(params, svcLogicContext); + } +} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/AppcDgUtilActivatorTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/AppcDgUtilActivatorTest.java deleted file mode 100644 index 066863bb8..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/AppcDgUtilActivatorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.osgi.framework.BundleContext; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -public class AppcDgUtilActivatorTest { - - @Mock - private BundleContext bundleContext; - - private AppcDgUtilActivator appcDgUtilActivator; - - @Before - public void setUp() throws Exception { - appcDgUtilActivator = new AppcDgUtilActivator(); - } - - @Test - public void start() { - appcDgUtilActivator.start(bundleContext); - PowerMockito.verifyStatic(); - } - - @Test - public void stop() { - appcDgUtilActivator.stop(bundleContext); - PowerMockito.verifyStatic(); - } -} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImplTest.java deleted file mode 100644 index 3280cb954..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/ExecuteNodeActionImplTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.appc.exceptions.APPCException; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.verifyPrivate; -import static org.powermock.api.mockito.PowerMockito.verifyStatic; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ExecuteNodeActionImpl.class, FrameworkUtil.class, Thread.class}) -public class ExecuteNodeActionImplTest { - @Spy - private ExecuteNodeActionImpl mockedExecuteNodeActionImpl = new ExecuteNodeActionImpl(); - @Mock - private EELFLogger eelfLogger; - @Mock - private AAIService aaiService; - - private final String resourceType = "resourceType"; - private final String prefix = "prefix"; - private final String resourceKey = "resourceKey"; - private final String attributeName = "attributeName"; - private final String attributeValue = "attributeValue"; - - private Map params = new HashMap<>(); - private SvcLogicContext svcLogicContext = new SvcLogicContext(); - private SvcLogicResource.QueryStatus queryStatus = SvcLogicResource.QueryStatus.SUCCESS; - - - @Before - public void setUp() throws Exception { - Whitebox.setInternalState(mockedExecuteNodeActionImpl, "aaiService", aaiService); - - params.put("resourceType", resourceType); - params.put("prefix", prefix); - params.put("resourceKey", resourceKey); - params.put("attributeName", attributeName); - params.put("attributeValue", attributeValue); - } - - @Test - public void testInitialize() throws Exception { - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "getAAIservice"); - Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "initialize"); - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("getAAIservice"); - } - - @Test - public void testGetAAIservice() throws Exception { - // sref is not null - mockStatic(FrameworkUtil.class); - Bundle mockedBundle = mock(Bundle.class); - BundleContext mockedBundleContext = mock(BundleContext.class); - ServiceReference mockedServiceReference = mock(ServiceReference.class); - PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(mockedBundle); - PowerMockito.doReturn(mockedBundleContext).when(mockedBundle).getBundleContext(); - PowerMockito.doReturn(mockedServiceReference).when(mockedBundleContext) - .getServiceReference(AAIService.class.getName()); - - Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "getAAIservice"); - verify(mockedBundleContext, times(1)).getService(mockedServiceReference); - - // sref is null - PowerMockito.doReturn(null).when(mockedBundleContext) - .getServiceReference(AAIService.class.getName()); - Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "getAAIservice"); - verify(mockedBundleContext, times(1)).getService(mockedServiceReference); - } - - @Test - public void testWaitMethod() throws Exception { - mockStatic(Thread.class); - params.put("waitTime", "1"); - mockedExecuteNodeActionImpl.waitMethod(params, svcLogicContext); - verifyStatic(times(1)); - } - - @Test - public void testGetResource() throws Exception { - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - PowerMockito.doReturn(queryStatus).when(aaiService).query(resourceType, false, null, - resourceKey, prefix, null, svcLogicContext); - - mockedExecuteNodeActionImpl.getResource(params, svcLogicContext); - - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - verify(aaiService, times(1)).query(resourceType, false, null, - resourceKey, prefix, null, svcLogicContext); - assertEquals(queryStatus.toString(), svcLogicContext.getAttribute("getResource_result")); - } - - @Test - public void testPostResource() throws Exception { - - - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - PowerMockito.doReturn(queryStatus).when(aaiService).update(eq(resourceType), eq(resourceKey), anyMap(), - eq(prefix), eq(svcLogicContext)); - - mockedExecuteNodeActionImpl.postResource(params, svcLogicContext); - - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - verify(aaiService, times(1)).update(eq(resourceType), eq(resourceKey), anyMap(), - eq(prefix), eq(svcLogicContext)); - assertEquals(svcLogicContext.getAttribute("postResource_result"), queryStatus.toString()); - } - - @Test - public void testDeleteResource() throws Exception { - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - - PowerMockito.doReturn(queryStatus).when(aaiService).delete(eq(resourceType), eq(resourceKey), - eq(svcLogicContext)); - - mockedExecuteNodeActionImpl.deleteResource(params, svcLogicContext); - - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - verify(aaiService, times(1)).delete(eq(resourceType), eq(resourceKey), - eq(svcLogicContext)); - assertEquals(svcLogicContext.getAttribute("deleteResource_result"), queryStatus.toString()); - } - - @Test - public void testGetVnfHierarchySuccess() throws Exception { - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", anyMap(), eq - (svcLogicContext)); - PowerMockito.when(aaiService.query(any(), eq(false), anyString(), any(), any(), anyString(), - any(SvcLogicContext.class))).thenReturn(queryStatus); - - mockedExecuteNodeActionImpl.getVnfHierarchy(params, svcLogicContext); - - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - assertEquals("0", svcLogicContext.getAttribute("VNF.VNFCCount")); - assertEquals("SUCCESS", svcLogicContext.getAttribute("getVnfHierarchy_result")); - } - - @Test(expected = APPCException.class) - public void testGetVnfHierarchyFailure() throws Exception { - queryStatus = SvcLogicResource.QueryStatus.FAILURE; - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", anyMap(), - eq(svcLogicContext)); - PowerMockito.when(aaiService.query(any(), eq(false), anyString(), any(), any(), anyString(), - any(SvcLogicContext.class))).thenReturn(queryStatus); - - mockedExecuteNodeActionImpl.getVnfHierarchy(params, svcLogicContext); - - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - assertEquals("0", svcLogicContext.getAttribute("VNF.VNFCCount")); - assertEquals("FAILURE", svcLogicContext.getAttribute("getVnfHierarchy_result")); - assertTrue(svcLogicContext.getAttribute("output.status.message") != null); - } - - @Test - public void testPopulateVnfcsDetailsinContext() throws Exception { - Map> vnfcHierarchyMap = new HashMap<>(); - Set vServersList = new HashSet<>(); - vnfcHierarchyMap.put("SMP", vServersList); - vServersList.add("smp-0-url"); - vServersList.add("smp-1-url"); - - PowerMockito.doNothing().when(mockedExecuteNodeActionImpl, "initialize"); - PowerMockito.when(aaiService.query(eq("vnfc"), eq(false), anyString(), - eq("vnfc-name = 'SMP'"), eq("vnfcRetrived"), anyString(), any(SvcLogicContext.class))) - .thenReturn(queryStatus); - - Whitebox.invokeMethod(mockedExecuteNodeActionImpl, "populateVnfcsDetailsinContext", - vnfcHierarchyMap, svcLogicContext); - - verify(mockedExecuteNodeActionImpl, times(1)).getResource(anyMap(), - any(SvcLogicContext.class)); - verifyPrivate(mockedExecuteNodeActionImpl, times(1)).invoke("initialize"); - assertEquals(null, svcLogicContext.getAttribute("VNF.VNFC[0].TYPE")); - assertEquals(null, svcLogicContext.getAttribute("VNF.VNFC[0].NAME")); - assertEquals("2", svcLogicContext.getAttribute("VNF.VNFC[0].VM_COUNT")); - assertTrue(vServersList.contains(svcLogicContext.getAttribute("VNF.VNFC[0].VM[0].URL"))); - assertTrue(vServersList.contains(svcLogicContext.getAttribute("VNF.VNFC[0].VM[1].URL"))); - } -} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImplTest.java deleted file mode 100644 index 405c1d92a..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/InputParameterValidationImplTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.powermock.reflect.Whitebox; - -import java.util.HashMap; -import java.util.Map; - -public class InputParameterValidationImplTest { - private SvcLogicContext svcLogicContext; - - private InputParameterValidationImpl inputParameterValidation; - - @Before - public void setUp() throws Exception { - inputParameterValidation = new InputParameterValidationImpl(); - svcLogicContext = new SvcLogicContext(); - svcLogicContext.setAttribute("a", "b"); - svcLogicContext.setAttribute("b", "c"); - } - - @Test - public void validateAttributeSuccess() throws Exception { - Map params = new HashMap<>(); - params.put("a", "b"); - params.put("b", "c"); - - inputParameterValidation.validateAttribute(params, svcLogicContext); - - Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttribute")); - } - - @Test - public void validateAttributeFailure() throws Exception { - // wrong value - Map params = new HashMap<>(); - params.put("e", "f"); - - inputParameterValidation.validateAttribute(params, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); - - // null value - params = new HashMap<>(); - params.put("e", null); - - inputParameterValidation.validateAttribute(params, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); - } - - @Test - public void validateAttributeNull() throws Exception { - inputParameterValidation.validateAttribute(null, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttribute")); - } - - @Test - public void validateAttributeLengthSuccess() throws Exception { - Map params = new HashMap<>(); - params.put("maximum_length_param", "2"); - params.put("a", "1"); - - inputParameterValidation.validateAttributeLength(params, svcLogicContext); - - Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttributeLength")); - } - - @Test - public void validateAttributeLengthFailure() throws Exception { - // wrong key - Map params = new HashMap<>(); - params.put("maximum_length_param", "2"); - params.put("e", "1"); - - inputParameterValidation.validateAttributeLength(params, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); - - //over length - params = new HashMap<>(); - params.put("maximum_length_param", "2"); - params.put("c", "3"); - - inputParameterValidation.validateAttributeLength(params, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); - } - - @Test - public void validateAttributeLengthNull() throws Exception { - inputParameterValidation.validateAttributeLength(null, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeLength")); - } - - @Test - public void validateAttributeCharacterSuccess() throws Exception { - Map params = new HashMap<>(); - params.put("special_characters", "z"); - params.put("a", "1"); - - inputParameterValidation.validateAttributeCharacter(params, svcLogicContext); - - Assert.assertEquals("true", svcLogicContext.getAttribute("validateAttributeCharacter")); - } - - @Test - public void validateAttributeCharacterFailure() throws Exception { - Map params = new HashMap<>(); - params.put("special_characters", "z"); - params.put("d", "1"); - - inputParameterValidation.validateAttributeCharacter(params, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeCharacter")); - } - - @Test - public void validateAttributeCharacterNull() throws Exception { - inputParameterValidation.validateAttributeCharacter(null, svcLogicContext); - - Assert.assertEquals("false", svcLogicContext.getAttribute("validateAttributeCharacter")); - } - - @Test - public void testGetValueFromContext() throws Exception { - Map result = Whitebox.invokeMethod(inputParameterValidation, "getValueFromContext", - svcLogicContext); - Assert.assertEquals("b", result.get("a")); - Assert.assertEquals("c", result.get("b")); - } -} \ No newline at end of file diff --git a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImplTest.java b/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImplTest.java deleted file mode 100644 index 6eb732064..000000000 --- a/appc-dg-util/appc-dg-util-bundle/src/test/java/org/openecomp/appc/dg/util/impl/UpgradeStubNodeImplTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.util.impl; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; - -import java.util.HashMap; -import java.util.Map; - -public class UpgradeStubNodeImplTest { - @Mock - private SvcLogicContext svcLogicContext; - - private UpgradeStubNodeImpl upgradeStubNode; - - @Before - public void setUp() throws Exception { - upgradeStubNode = new UpgradeStubNodeImpl(); - } - - @Test - public void testHandleUpgradeStubSuccess() throws APPCException { - Map params = new HashMap<>(); - upgradeStubNode.handleUpgradeStub(params, svcLogicContext); - } - - @Test(expected = APPCException.class) - public void testHandleUpgradeStubException() throws APPCException { - Map params = new HashMap<>(); - params.put("failureIndicator", "true"); - upgradeStubNode.handleUpgradeStub(params, svcLogicContext); - } -} \ No newline at end of file diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java new file mode 100644 index 000000000..64033dd38 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public interface AAIPlugin extends SvcLogicJavaPlugin { + void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; + + void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; + + void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; + + void getResource(Map params, SvcLogicContext ctx) throws APPCException; + + void postResource(Map params, SvcLogicContext ctx) throws APPCException; + + void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java new file mode 100644 index 000000000..2ec604dcd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.exception; + + +public class AAIQueryException extends Exception{ + public AAIQueryException(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java new file mode 100644 index 000000000..1b510a8ca --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java @@ -0,0 +1,401 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.i18n.EELFResourceManager; + +import org.onap.appc.dg.aai.AAIPlugin; +import org.onap.appc.dg.aai.exception.AAIQueryException; +import org.onap.appc.dg.aai.objects.AAIQueryResult; +import org.onap.appc.dg.aai.objects.Relationship; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + + +public class AAIPluginImpl implements AAIPlugin { + private AAIClient aaiClient; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class); + + @SuppressWarnings("unchecked") + public AAIPluginImpl() { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(AAIService.class); + aaiClient = (AAIClient) bctx.getService(sref); + } + + @Override + public void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { + String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); + String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); + + String key = "vnf-id = '" + vnf_id + "'"; + + Map data = new HashMap<>(); + for (Map.Entry entry : params.entrySet()) { + String paramKey = entry.getKey(); + int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA); + if (pos == 0) { + data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue()); + } + } + + try { + SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + logger.info("AAIResponse: " + response.toString()); + if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + } catch (SvcLogicException e) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error(msg); + throw new APPCException(e); + } + } + + @Override + public void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { + String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); + String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); + + String key = "vnf-id = '" + vnf_id + "'"; + try { + SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); +// String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); + if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; + String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); + if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; + + ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty())); + ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty())); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + logger.info("AAIResponse: " + response.toString()); + } catch (SvcLogicException e) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error(msg); + throw new APPCException(e); + } + } + + @Override + public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { + + Map> vnfcMap = new HashMap<>(); + String vnfType,vnfVersion; + String vnfId = params.get("resourceKey"); + AAIQueryResult vnfQueryResult; + int vmCount =0; + try { + vnfQueryResult = readVnf(vnfId); + + vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type"); + vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID); + + for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){ + if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){ + vmCount++; + String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id"); + String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id"); + String vmRelatedLink = vnfRelationship.getRelatedLink(); + String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name"); + String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner"); + String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id"); + + AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId); + String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink"); + + Vserver vm = new Vserver(vmURL,tenantId,vmId,vmRelatedLink,vmName); + for(Relationship vmRelation:vmQueryResult.getRelationshipList()){ + + if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){ + String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name"); + AAIQueryResult vnfcQueryResult = readVnfc(vnfcName); + String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type"); + + Vnfc vnfc = new Vnfc(vnfcType,null,vnfcName); + Set vmSet = vnfcMap.get(vnfc); + if(vmSet == null){ + vmSet = new HashSet<>(); + vnfcMap.put(vnfc,vmSet); + } + vmSet.add(vm); + } + } + } + } + ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount)); + } catch (AAIQueryException e) { + ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx + .getAttribute("getResource_result")); + logger.warn("Incorrect or Incomplete VNF Hierarchy"); + throw new APPCException("Error Retrieving VNF hierarchy"); + } + + Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); + for(Vnfc vnfc:vnfcMap.keySet()){ + for(Vserver vm:vnfcMap.get(vnfc)){ + vnfc.addVm(vm); + } + vnf.addVnfc(vnfc); + } + + populateContext(vnf,ctx); + ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + } + + private void populateContext(Vnf vnf ,SvcLogicContext ctx) { + ctx.setAttribute("vnf.type",vnf.getVnfType()); + ctx.setAttribute("vnf.version",vnf.getVnfVersion()); + ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size())); + int vnfcCount =0; + for(Vnfc vnfc:vnf.getVnfcs()){ + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName()); + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType()); + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size())); + int vmCount =0; + for(Vserver vm:vnfc.getVserverList()){ + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl()); + } + vnfcCount++; + } + } + + private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException { + String query = "vnfc.vnfc-name = '" + vnfcName + "'"; + String prefix = "VNFC"; + String resourceType = "vnfc"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + String[] additionalProperties = new String[]{"vnfc-type","vnfc-name", + "vnfc-function-code","in-maint","prov-status", + "is-closed-loop-disabled","orchestration-status","resource-version"}; + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) + throws AAIQueryException { + String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId + + "' AND cloud-region.cloud-owner = '" + cloudOwner + + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; + String prefix = "VM"; + String resourceType = "vserver"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + String[] additionalProperties = new String[]{"vserver-id","vserver-selflink", + "vserver-name","in-maint","prov-status","is-closed-loop-disabled", + "vserver-name2","resource-version",}; + + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readVnf(String vnfId) throws AAIQueryException { + String query = "generic-vnf.vnf-id = '" + vnfId + "'"; + String prefix = "VNF"; + String resourceType = "generic-vnf"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + + String[] additionalProperties = new String[]{"vnf-type","vnf-name", + "in-maint","prov-status","heat-stack-id", + "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID}; + + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readRelationDataAndProperties(String prefix, + SvcLogicContext context, + String[] additionalProperties) { + AAIQueryResult result = new AAIQueryResult(); + + if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) { + Integer relationsCount = Integer.parseInt(context.getAttribute( + prefix + ".relationship-list.relationship_length")); + for (int i = 0; i < relationsCount; i++) { + String rsKey = prefix + ".relationship-list.relationship[" + i + "]"; + Relationship relationShip = new Relationship(); + relationShip.setRelatedLink(context.getAttribute(rsKey + ".related-link")); + relationShip.setRelatedTo(context.getAttribute(rsKey + ".related-to")); + Integer relationDataCount = + Integer.parseInt(context.getAttribute(rsKey + ".relationship-data_length")); + for (int j = 0; j < relationDataCount; j++) { + String rsDataKey = rsKey + ".relationship-data[" + j + "]"; + String key = context.getAttribute(rsDataKey + ".relationship-key"); + String value = context.getAttribute(rsDataKey + ".relationship-value"); + relationShip.getRelationShipDataMap().put(key, value); + } + Integer relatedPropertyCount = 0; + String relatedPropertyCountStr = null; + try { + relatedPropertyCountStr = context.getAttribute(rsKey + ".related-to-property_length"); + relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr); + } catch (NumberFormatException e) { + logger.debug( + "Invalid value in the context for Related Property Count " + relatedPropertyCountStr); + } + + for (int j = 0; j < relatedPropertyCount; j++) { + String rsPropKey = rsKey + ".related-to-property[" + j + "]"; + String key = context.getAttribute(rsPropKey + ".property-key"); + String value = context.getAttribute(rsPropKey + ".property-value"); + relationShip.getRelatedProperties().put(key, value); + } + result.getRelationshipList().add(relationShip); + } + } else { + logger.error("Relationship-list not present in the SvcLogicContext attributes set." + + (context == null ? "" : "Attribute KeySet = "+ context.getAttributeKeySet())); + } + + if (context != null) { + for (String key : additionalProperties) { + result.getAdditionProperties().put(key, context.getAttribute(prefix + "." + key)); + } + } + return result; + } + + private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException { + SvcLogicContext resourceContext = new SvcLogicContext(); + try { + SvcLogicResource.QueryStatus response = + aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); + logger.info("AAIResponse: " + response.toString()); + if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ + throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); + } + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage())); + throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); + } + return resourceContext; + } + + @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"); + if (logger.isDebugEnabled()) { + logger.debug("inside getResorce"); + logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); + } + try { + SvcLogicResource.QueryStatus response = + aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("getResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error( + EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting getResource======"); + } + } + + @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"), att_name = params.get("attributeName"), att_value = + params.get("attributeValue"); + if (logger.isDebugEnabled()) { + logger.debug("inside postResource"); + logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); + logger.debug("Updating " + att_name + " to : " + att_value); + } + Map data = new HashMap<>(); + data.put(att_name, att_value); + + try { + SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("postResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting postResource======"); + } + } + + @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); + + if (logger.isDebugEnabled()) { + logger.debug("inside deleteResource"); + logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); + } + try { + SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("deleteResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting deleteResource======"); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java new file mode 100644 index 000000000..6a6818e06 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + + +public class Constants { + public final static String VNF_ID_PARAM_NAME = "aai.vnfID"; + public static final String AAI_PREFIX_PARAM_NAME = "aai.prefix"; + public static final String AAI_INPUT_DATA = "aai.input.data"; + public static final String AAI_ERROR_MESSAGE = "org.onap.appc.dg.error"; + + public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; + public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; + public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; + public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; + + public static final String CONTROLLER_IP = "127.0.0.1"; + public static final int CONTROLLER_PORT = 8181; + public static final String PROTOCOL = "http"; + + public static final String VF_LICENSE = "VF_LICENSE"; + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String SDNCTL_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + public static final String SDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; + + // input fields names + public static final String PAYLOAD = "payload"; + + // constants fo DG + public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; + public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; + public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; + public static final String TARGET_VNF_TYPE = "target-vnf-type"; + public static final String FILE_CONTENT_FIELD_NAME = "file-content"; + public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; + public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String UPGRADE_VERSION = "upgrade-version"; + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String RESOURCEKEY = "resourceKey"; + public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; + public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; + public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; + public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; + public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; + public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; + public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; + public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; + + public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; + public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; + public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; + public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; + public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; + + /** + * AAI property names + */ + public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id"; + + public enum SDC_ARTIFACTS_FIELDS { + SERVICE_UUID, + DISTRIBUTION_ID, + SERVICE_NAME, + SERVICE_DESCRIPTION, + RESOURCE_UUID, + RESOURCE_INSTANCE_NAME, + RESOURCE_NAME, + RESOURCE_VERSION, + RESOURCE_TYPE, + ARTIFACT_UUID, + ARTIFACT_TYPE, + ARTIFACT_VERSION, + ARTIFACT_DESCRIPTION, + INTERNAL_VERSION, + CREATION_DATE, + ARTIFACT_NAME, + ARTIFACT_CONTENT + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java new file mode 100644 index 000000000..674da55dd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.objects; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class AAIQueryResult { + private List relationshipList; + + private Map additionProperties; + + + public AAIQueryResult(){ + relationshipList = new ArrayList<>(); + additionProperties = new HashMap<>(); + } + + + public List getRelationshipList() { + return relationshipList; + } + + public Map getAdditionProperties() { + return additionProperties; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java new file mode 100644 index 000000000..d32898f1c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.objects; + +import java.util.HashMap; +import java.util.Map; + + +public class Relationship { + + private String relatedTo; + + private String relatedLink; + + private Map relationShipDataMap; + + private Map relatedProperties; + + public Relationship(){ + relationShipDataMap = new HashMap<>(); + relatedProperties = new HashMap<>(); + } + + public String getRelatedTo() { + return relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public Map getRelationShipDataMap() { + return relationShipDataMap; + } + + public Map getRelatedProperties() { + return relatedProperties; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java deleted file mode 100644 index 64033dd38..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public interface AAIPlugin extends SvcLogicJavaPlugin { - void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; - - void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; - - void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; - - void getResource(Map params, SvcLogicContext ctx) throws APPCException; - - void postResource(Map params, SvcLogicContext ctx) throws APPCException; - - void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java deleted file mode 100644 index 2ec604dcd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.exception; - - -public class AAIQueryException extends Exception{ - public AAIQueryException(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java deleted file mode 100644 index 1b510a8ca..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java +++ /dev/null @@ -1,401 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.i18n.EELFResourceManager; - -import org.onap.appc.dg.aai.AAIPlugin; -import org.onap.appc.dg.aai.exception.AAIQueryException; -import org.onap.appc.dg.aai.objects.AAIQueryResult; -import org.onap.appc.dg.aai.objects.Relationship; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - - -public class AAIPluginImpl implements AAIPlugin { - private AAIClient aaiClient; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class); - - @SuppressWarnings("unchecked") - public AAIPluginImpl() { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(AAIService.class); - aaiClient = (AAIClient) bctx.getService(sref); - } - - @Override - public void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { - String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); - String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); - - String key = "vnf-id = '" + vnf_id + "'"; - - Map data = new HashMap<>(); - for (Map.Entry entry : params.entrySet()) { - String paramKey = entry.getKey(); - int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA); - if (pos == 0) { - data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue()); - } - } - - try { - SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - logger.info("AAIResponse: " + response.toString()); - if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - } catch (SvcLogicException e) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error(msg); - throw new APPCException(e); - } - } - - @Override - public void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { - String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); - String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); - - String key = "vnf-id = '" + vnf_id + "'"; - try { - SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); -// String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); - if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; - String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); - if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; - - ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty())); - ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty())); - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - logger.info("AAIResponse: " + response.toString()); - } catch (SvcLogicException e) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error(msg); - throw new APPCException(e); - } - } - - @Override - public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { - - Map> vnfcMap = new HashMap<>(); - String vnfType,vnfVersion; - String vnfId = params.get("resourceKey"); - AAIQueryResult vnfQueryResult; - int vmCount =0; - try { - vnfQueryResult = readVnf(vnfId); - - vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type"); - vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID); - - for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){ - if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){ - vmCount++; - String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id"); - String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id"); - String vmRelatedLink = vnfRelationship.getRelatedLink(); - String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name"); - String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner"); - String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id"); - - AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId); - String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink"); - - Vserver vm = new Vserver(vmURL,tenantId,vmId,vmRelatedLink,vmName); - for(Relationship vmRelation:vmQueryResult.getRelationshipList()){ - - if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){ - String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name"); - AAIQueryResult vnfcQueryResult = readVnfc(vnfcName); - String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type"); - - Vnfc vnfc = new Vnfc(vnfcType,null,vnfcName); - Set vmSet = vnfcMap.get(vnfc); - if(vmSet == null){ - vmSet = new HashSet<>(); - vnfcMap.put(vnfc,vmSet); - } - vmSet.add(vm); - } - } - } - } - ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount)); - } catch (AAIQueryException e) { - ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx - .getAttribute("getResource_result")); - logger.warn("Incorrect or Incomplete VNF Hierarchy"); - throw new APPCException("Error Retrieving VNF hierarchy"); - } - - Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); - for(Vnfc vnfc:vnfcMap.keySet()){ - for(Vserver vm:vnfcMap.get(vnfc)){ - vnfc.addVm(vm); - } - vnf.addVnfc(vnfc); - } - - populateContext(vnf,ctx); - ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - } - - private void populateContext(Vnf vnf ,SvcLogicContext ctx) { - ctx.setAttribute("vnf.type",vnf.getVnfType()); - ctx.setAttribute("vnf.version",vnf.getVnfVersion()); - ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size())); - int vnfcCount =0; - for(Vnfc vnfc:vnf.getVnfcs()){ - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName()); - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType()); - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size())); - int vmCount =0; - for(Vserver vm:vnfc.getVserverList()){ - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl()); - } - vnfcCount++; - } - } - - private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException { - String query = "vnfc.vnfc-name = '" + vnfcName + "'"; - String prefix = "VNFC"; - String resourceType = "vnfc"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - String[] additionalProperties = new String[]{"vnfc-type","vnfc-name", - "vnfc-function-code","in-maint","prov-status", - "is-closed-loop-disabled","orchestration-status","resource-version"}; - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) - throws AAIQueryException { - String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId - + "' AND cloud-region.cloud-owner = '" + cloudOwner - + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; - String prefix = "VM"; - String resourceType = "vserver"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - String[] additionalProperties = new String[]{"vserver-id","vserver-selflink", - "vserver-name","in-maint","prov-status","is-closed-loop-disabled", - "vserver-name2","resource-version",}; - - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readVnf(String vnfId) throws AAIQueryException { - String query = "generic-vnf.vnf-id = '" + vnfId + "'"; - String prefix = "VNF"; - String resourceType = "generic-vnf"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - - String[] additionalProperties = new String[]{"vnf-type","vnf-name", - "in-maint","prov-status","heat-stack-id", - "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID}; - - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readRelationDataAndProperties(String prefix, - SvcLogicContext context, - String[] additionalProperties) { - AAIQueryResult result = new AAIQueryResult(); - - if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) { - Integer relationsCount = Integer.parseInt(context.getAttribute( - prefix + ".relationship-list.relationship_length")); - for (int i = 0; i < relationsCount; i++) { - String rsKey = prefix + ".relationship-list.relationship[" + i + "]"; - Relationship relationShip = new Relationship(); - relationShip.setRelatedLink(context.getAttribute(rsKey + ".related-link")); - relationShip.setRelatedTo(context.getAttribute(rsKey + ".related-to")); - Integer relationDataCount = - Integer.parseInt(context.getAttribute(rsKey + ".relationship-data_length")); - for (int j = 0; j < relationDataCount; j++) { - String rsDataKey = rsKey + ".relationship-data[" + j + "]"; - String key = context.getAttribute(rsDataKey + ".relationship-key"); - String value = context.getAttribute(rsDataKey + ".relationship-value"); - relationShip.getRelationShipDataMap().put(key, value); - } - Integer relatedPropertyCount = 0; - String relatedPropertyCountStr = null; - try { - relatedPropertyCountStr = context.getAttribute(rsKey + ".related-to-property_length"); - relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr); - } catch (NumberFormatException e) { - logger.debug( - "Invalid value in the context for Related Property Count " + relatedPropertyCountStr); - } - - for (int j = 0; j < relatedPropertyCount; j++) { - String rsPropKey = rsKey + ".related-to-property[" + j + "]"; - String key = context.getAttribute(rsPropKey + ".property-key"); - String value = context.getAttribute(rsPropKey + ".property-value"); - relationShip.getRelatedProperties().put(key, value); - } - result.getRelationshipList().add(relationShip); - } - } else { - logger.error("Relationship-list not present in the SvcLogicContext attributes set." - + (context == null ? "" : "Attribute KeySet = "+ context.getAttributeKeySet())); - } - - if (context != null) { - for (String key : additionalProperties) { - result.getAdditionProperties().put(key, context.getAttribute(prefix + "." + key)); - } - } - return result; - } - - private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException { - SvcLogicContext resourceContext = new SvcLogicContext(); - try { - SvcLogicResource.QueryStatus response = - aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); - logger.info("AAIResponse: " + response.toString()); - if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ - throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); - } - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage())); - throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); - } - return resourceContext; - } - - @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"); - if (logger.isDebugEnabled()) { - logger.debug("inside getResorce"); - logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); - } - try { - SvcLogicResource.QueryStatus response = - aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("getResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error( - EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting getResource======"); - } - } - - @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"), att_name = params.get("attributeName"), att_value = - params.get("attributeValue"); - if (logger.isDebugEnabled()) { - logger.debug("inside postResource"); - logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); - logger.debug("Updating " + att_name + " to : " + att_value); - } - Map data = new HashMap<>(); - data.put(att_name, att_value); - - try { - SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("postResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting postResource======"); - } - } - - @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); - - if (logger.isDebugEnabled()) { - logger.debug("inside deleteResource"); - logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); - } - try { - SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("deleteResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting deleteResource======"); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java deleted file mode 100644 index 6a6818e06..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - - -public class Constants { - public final static String VNF_ID_PARAM_NAME = "aai.vnfID"; - public static final String AAI_PREFIX_PARAM_NAME = "aai.prefix"; - public static final String AAI_INPUT_DATA = "aai.input.data"; - public static final String AAI_ERROR_MESSAGE = "org.onap.appc.dg.error"; - - public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; - public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; - public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; - public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; - - public static final String CONTROLLER_IP = "127.0.0.1"; - public static final int CONTROLLER_PORT = 8181; - public static final String PROTOCOL = "http"; - - public static final String VF_LICENSE = "VF_LICENSE"; - - // tables and fields - public static final String NETCONF_SCHEMA = "sdnctl"; - public static final String SDNCTL_SCHEMA = "sdnctl"; - public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; - public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; - public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; - public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; - public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; - public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; - public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; - public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; - public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; - public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; - public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; - public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; - public static final String LOG_FIELD_NAME = "LOG"; - public static final String SDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; - - // input fields names - public static final String PAYLOAD = "payload"; - - // constants fo DG - public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; - public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; - public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; - public static final String TARGET_VNF_TYPE = "target-vnf-type"; - public static final String FILE_CONTENT_FIELD_NAME = "file-content"; - public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; - public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; - public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; - public static final String UPGRADE_VERSION = "upgrade-version"; - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - public static final String RESOURCEKEY = "resourceKey"; - public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; - public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; - public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; - public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; - public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; - public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; - public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; - public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; - - public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; - public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; - public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; - public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; - public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; - - /** - * AAI property names - */ - public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id"; - - public enum SDC_ARTIFACTS_FIELDS { - SERVICE_UUID, - DISTRIBUTION_ID, - SERVICE_NAME, - SERVICE_DESCRIPTION, - RESOURCE_UUID, - RESOURCE_INSTANCE_NAME, - RESOURCE_NAME, - RESOURCE_VERSION, - RESOURCE_TYPE, - ARTIFACT_UUID, - ARTIFACT_TYPE, - ARTIFACT_VERSION, - ARTIFACT_DESCRIPTION, - INTERNAL_VERSION, - CREATION_DATE, - ARTIFACT_NAME, - ARTIFACT_CONTENT - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java deleted file mode 100644 index 674da55dd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class AAIQueryResult { - private List relationshipList; - - private Map additionProperties; - - - public AAIQueryResult(){ - relationshipList = new ArrayList<>(); - additionProperties = new HashMap<>(); - } - - - public List getRelationshipList() { - return relationshipList; - } - - public Map getAdditionProperties() { - return additionProperties; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java deleted file mode 100644 index d32898f1c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.objects; - -import java.util.HashMap; -import java.util.Map; - - -public class Relationship { - - private String relatedTo; - - private String relatedLink; - - private Map relationShipDataMap; - - private Map relatedProperties; - - public Relationship(){ - relationShipDataMap = new HashMap<>(); - relatedProperties = new HashMap<>(); - } - - public String getRelatedTo() { - return relatedTo; - } - - public String getRelatedLink() { - return relatedLink; - } - - public Map getRelationShipDataMap() { - return relationShipDataMap; - } - - public Map getRelatedProperties() { - return relatedProperties; - } - - public void setRelatedTo(String relatedTo) { - this.relatedTo = relatedTo; - } - - public void setRelatedLink(String relatedLink) { - this.relatedLink = relatedLink; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java new file mode 100644 index 000000000..3de308392 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java @@ -0,0 +1,547 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException; +import org.onap.ccsdk.sli.adaptors.aai.data.*; +import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent; +import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer; +import org.onap.ccsdk.sli.adaptors.aai.update.Update; + + +public class AAIClientMock implements AAIClient { + + Map mockAAI = new HashMap<>(); + + public void setMockAAI(Map mockAAI) { + this.mockAAI = mockAAI; + } + + @Override + public AAIResponse requestSdnZoneQuery(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVceData(String s, Vce vce) throws AAIServiceException { + return false; + } + + @Override + public Vce requestNetworkVceData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean deleteNetworkVceData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public ServiceInstance requestServiceInterfaceData(String s) throws AAIServiceException { + return null; + } + + @Override + public ServiceInstance requestServiceInterfaceData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postServiceInterfaceData(String s, String s1, String s2, ServiceInstance serviceInstance) throws AAIServiceException { + return false; + } + + @Override + public SearchResults requestServiceInstanceURL(String s) throws AAIServiceException { + return null; + } + + @Override + public Vpe requestNetworkVpeData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVpeData(String s, Vpe vpe) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkVpeData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Vserver requestVServerData(String s, String s1, String s2, String s3) throws AAIServiceException { + return null; + } + + @Override + public boolean postVServerData(String s, String s1, String s2, String s3, Vserver vserver) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteVServerData(String s, String s1, String s2, String s3, String s4) throws AAIServiceException { + return false; + } + + @Override + public URL requestVserverURLNodeQuery(String s) throws AAIServiceException { + return null; + } + + @Override + public String getTenantIdFromVserverUrl(URL url) { + return null; + } + + @Override + public String getCloudOwnerFromVserverUrl(URL url) { + return null; + } + + @Override + public String getCloudRegionFromVserverUrl(URL url) { + return null; + } + + @Override + public String getVServerIdFromVserverUrl(URL url, String s) { + return null; + } + + @Override + public Vserver requestVServerDataByURL(URL url) throws AAIServiceException { + return null; + } + + @Override + public VplsPe requestNetworkVplsPeData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVplsPeData(String s, VplsPe vplsPe) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkVplsPeData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Complex requestNetworkComplexData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkComplexData(String s, Complex complex) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkComplexData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public CtagPool requestCtagPoolData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException { + return null; + } + + @Override + public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException { + return null; + } + + @Override + public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException { + return null; + } + + @Override + public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException { + return null; + } + + @Override + public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException { + return null; + } + + @Override + public PServer dataChangeRequestPServerData(URL url) throws AAIServiceException { + return null; + } + + @Override + public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException { + return null; + } + + @Override + public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException { + return null; + } + + @Override + public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException { + return null; + } + + @Override + public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException { + return false; + } + + @Override + public GenericVnf requestGenericVnfData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postGenericVnfData(String s, GenericVnf genericVnf) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteGenericVnfData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public DvsSwitch requestDvsSwitchData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postDvsSwitchData(String s, DvsSwitch dvsSwitch) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteDvsSwitchData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public PInterface requestPInterfaceData(String s, String s1) throws AAIServiceException { + return null; + } + + @Override + public boolean postPInterfaceData(String s, String s1, PInterface pInterface) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePInterfaceData(String s, String s1, String s2) throws AAIServiceException { + return false; + } + + @Override + public PhysicalLink requestPhysicalLinkData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postPhysicalLinkData(String s, PhysicalLink physicalLink) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePhysicalLinkData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public PServer requestPServerData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postPServerData(String s, PServer pServer) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePServerData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public L3Network requestL3NetworkData(String s) throws AAIServiceException { + return null; + } + + @Override + public L3Network requestL3NetworkQueryByName(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postL3NetworkData(String s, L3Network l3Network) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteL3NetworkData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public VpnBinding requestVpnBindingData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean deleteVpnBindingData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public VnfImage requestVnfImageData(String s) throws AAIServiceException { + return null; + } + + @Override + public VnfImage requestVnfImageDataByVendorModel(String s, String s1) throws AAIServiceException { + return null; + } + + @Override + public VnfImage requestVnfImageDataByVendorModelVersion(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean sendNotify(NotifyEvent notifyEvent, String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public SitePairSet requestSitePairSetData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postSitePairSetData(String s, SitePairSet sitePairSet) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteSitePairSetData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Service requestServiceData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postServiceData(String s, Service service) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteServiceData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public QueryResponse requestNodeQuery(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public String requestDataByURL(URL url) throws AAIServiceException { + return null; + } + + @Override + public GenericVnf requestGenericVnfeNodeQuery(String s) throws AAIServiceException { + return null; + } + + @Override + public Tenant requestTenantData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public Tenant requestTenantDataByName(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postTenantData(String s, String s1, String s2, Tenant tenant) throws AAIServiceException { + return false; + } + + @Override + public boolean updateAnAIEntry(Update update) throws AAIServiceException { + return false; + } + + @Override + public QueryStatus backup(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus restore(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus isAvailable(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus exists(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus query(String s, boolean b, String s1, String key, String prefix, String s4, SvcLogicContext ctx) throws SvcLogicException { + if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { + for (Map.Entry entry : mockAAI.entrySet()) { + ctx.setAttribute(prefix + "." + entry.getKey(), entry.getValue()); + } + return QueryStatus.SUCCESS; + + + } else if (key.equals("vnf-id = 'test_VNF1'")){ + return QueryStatus.NOT_FOUND; + } + else if (key.equals("vnf-id = 'test_VNF3'")){ + throw new SvcLogicException(); + } + else { + return QueryStatus.FAILURE; + } + + + } + + @Override + public QueryStatus reserve(String s, String s1, String s2, String s3, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus save(String s, boolean b, boolean b1, String s1, Map map, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus release(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus delete(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus notify(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus update(String s, String key, Map data, String prefix, SvcLogicContext ctx) throws SvcLogicException { + if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { + for (Map.Entry entry : data.entrySet()) { + mockAAI.put(entry.getKey(), entry.getValue()); + } + return QueryStatus.SUCCESS; + + + } else if (key.equals("vnf-id = 'test_VNF1'")){ + return QueryStatus.NOT_FOUND; + } + else if (key.equals("vnf-id = 'test_VNF3'")){ + throw new SvcLogicException(); + } + else { + return QueryStatus.FAILURE; + } + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java new file mode 100644 index 000000000..d2f08597e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java @@ -0,0 +1,259 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + +import org.junit.runner.RunWith; +import org.onap.appc.dg.aai.Constants; +import org.onap.appc.dg.aai.impl.AAIPluginImpl; +import org.onap.appc.dg.common.dao.DAOService; +import org.onap.appc.dg.common.impl.LicenseManagerImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AAIPluginImpl.class, FrameworkUtil.class}) +public class AAIPluginImplTest { + private AAIPluginImpl aaiPlugin; + private AAIClientMock aaiClient; + + private final BundleContext bundleContext= Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + String prefix = "aai.input.data"; + String vnfId = "test_VNF"; + String vnfId1 = "test_VNF1"; + String vnfId2 = "test_VNF2"; + String vnfId3 = "test_VNF3"; + + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + aaiClient = new AAIClientMock(); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiClient); + aaiPlugin = new AAIPluginImpl(); + + + } + + + + + @Test + public void testPostGenericVnfData() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId); + ctx.setAttribute("aai.prefix", prefix); + + aaiPlugin.postGenericVnfData(params, ctx); + + Assert.assertEquals("wrong license-key-uuid","123", mockAAI.get("license-key-uuid")); + Assert.assertEquals("wrong license-assignment-group-uuid","1234", mockAAI.get("license-assignment-group-uuid")); + Assert.assertEquals("wrong data.license-key","12345", mockAAI.get("data.license-key")); + } + + + @Test + public void testPostGenericVnfDataNegativeVnfNotFound() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId1); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + + @Test + public void testPostGenericVnfDataNegativeFailure() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId2); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + + @Test + public void testPostGenericVnfDataNegativeSvcLogicException() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId3); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + @Test + public void testGetGenericVnfData() throws Exception { + String vnfNameKey = "vnf-name"; + String vnfType = "VSCP"; + String vnfTypeKey = "vnf-type"; + String provStatus = "Active"; + String provStatusKey = "prov-status"; + String orchestrationStatus = "Running"; + String orchestrationStatusKey = "orchestration-status"; + + Map params = new HashMap<>(); + HashMap mockAAI = new HashMap<>(); + mockAAI.put(vnfNameKey,vnfId); + mockAAI.put(vnfTypeKey,vnfType); + mockAAI.put(provStatusKey, provStatus); + mockAAI.put(orchestrationStatusKey, orchestrationStatus); + aaiClient.setMockAAI(mockAAI); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId); + ctx.setAttribute("aai.prefix", prefix); + + + aaiPlugin.getGenericVnfData(params, ctx); + + Assert.assertEquals("wrong "+vnfNameKey,vnfId, ctx.getAttribute(prefix + "." + vnfNameKey)); + Assert.assertEquals("wrong "+orchestrationStatusKey,orchestrationStatus, ctx.getAttribute(prefix + "." + orchestrationStatusKey)); + Assert.assertEquals("wrong "+vnfTypeKey,vnfType, ctx.getAttribute(prefix + "." + vnfTypeKey)); + Assert.assertEquals("wrong "+provStatusKey,provStatus, ctx.getAttribute(prefix + "." + provStatusKey )); + } + + + + + @Test + public void testGetGenericVnfDataNegativeVnfNotFound() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId1); + ctx.setAttribute("aai.prefix", prefix); + + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + + @Test + public void testGetGenericVnfDataNegativeFailure() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId2); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + + @Test + public void testGetGenericVnfDataNegativeSvcLogicException() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId3); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java deleted file mode 100644 index 3de308392..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java +++ /dev/null @@ -1,547 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException; -import org.onap.ccsdk.sli.adaptors.aai.data.*; -import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent; -import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer; -import org.onap.ccsdk.sli.adaptors.aai.update.Update; - - -public class AAIClientMock implements AAIClient { - - Map mockAAI = new HashMap<>(); - - public void setMockAAI(Map mockAAI) { - this.mockAAI = mockAAI; - } - - @Override - public AAIResponse requestSdnZoneQuery(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVceData(String s, Vce vce) throws AAIServiceException { - return false; - } - - @Override - public Vce requestNetworkVceData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean deleteNetworkVceData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public ServiceInstance requestServiceInterfaceData(String s) throws AAIServiceException { - return null; - } - - @Override - public ServiceInstance requestServiceInterfaceData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postServiceInterfaceData(String s, String s1, String s2, ServiceInstance serviceInstance) throws AAIServiceException { - return false; - } - - @Override - public SearchResults requestServiceInstanceURL(String s) throws AAIServiceException { - return null; - } - - @Override - public Vpe requestNetworkVpeData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVpeData(String s, Vpe vpe) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkVpeData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Vserver requestVServerData(String s, String s1, String s2, String s3) throws AAIServiceException { - return null; - } - - @Override - public boolean postVServerData(String s, String s1, String s2, String s3, Vserver vserver) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteVServerData(String s, String s1, String s2, String s3, String s4) throws AAIServiceException { - return false; - } - - @Override - public URL requestVserverURLNodeQuery(String s) throws AAIServiceException { - return null; - } - - @Override - public String getTenantIdFromVserverUrl(URL url) { - return null; - } - - @Override - public String getCloudOwnerFromVserverUrl(URL url) { - return null; - } - - @Override - public String getCloudRegionFromVserverUrl(URL url) { - return null; - } - - @Override - public String getVServerIdFromVserverUrl(URL url, String s) { - return null; - } - - @Override - public Vserver requestVServerDataByURL(URL url) throws AAIServiceException { - return null; - } - - @Override - public VplsPe requestNetworkVplsPeData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVplsPeData(String s, VplsPe vplsPe) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkVplsPeData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Complex requestNetworkComplexData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkComplexData(String s, Complex complex) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkComplexData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public CtagPool requestCtagPoolData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException { - return null; - } - - @Override - public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException { - return null; - } - - @Override - public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException { - return null; - } - - @Override - public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException { - return null; - } - - @Override - public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException { - return null; - } - - @Override - public PServer dataChangeRequestPServerData(URL url) throws AAIServiceException { - return null; - } - - @Override - public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException { - return null; - } - - @Override - public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException { - return null; - } - - @Override - public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException { - return null; - } - - @Override - public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException { - return false; - } - - @Override - public GenericVnf requestGenericVnfData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postGenericVnfData(String s, GenericVnf genericVnf) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteGenericVnfData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public DvsSwitch requestDvsSwitchData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postDvsSwitchData(String s, DvsSwitch dvsSwitch) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteDvsSwitchData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public PInterface requestPInterfaceData(String s, String s1) throws AAIServiceException { - return null; - } - - @Override - public boolean postPInterfaceData(String s, String s1, PInterface pInterface) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePInterfaceData(String s, String s1, String s2) throws AAIServiceException { - return false; - } - - @Override - public PhysicalLink requestPhysicalLinkData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postPhysicalLinkData(String s, PhysicalLink physicalLink) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePhysicalLinkData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public PServer requestPServerData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postPServerData(String s, PServer pServer) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePServerData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public L3Network requestL3NetworkData(String s) throws AAIServiceException { - return null; - } - - @Override - public L3Network requestL3NetworkQueryByName(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postL3NetworkData(String s, L3Network l3Network) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteL3NetworkData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public VpnBinding requestVpnBindingData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean deleteVpnBindingData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public VnfImage requestVnfImageData(String s) throws AAIServiceException { - return null; - } - - @Override - public VnfImage requestVnfImageDataByVendorModel(String s, String s1) throws AAIServiceException { - return null; - } - - @Override - public VnfImage requestVnfImageDataByVendorModelVersion(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean sendNotify(NotifyEvent notifyEvent, String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public SitePairSet requestSitePairSetData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postSitePairSetData(String s, SitePairSet sitePairSet) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteSitePairSetData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Service requestServiceData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postServiceData(String s, Service service) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteServiceData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public QueryResponse requestNodeQuery(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public String requestDataByURL(URL url) throws AAIServiceException { - return null; - } - - @Override - public GenericVnf requestGenericVnfeNodeQuery(String s) throws AAIServiceException { - return null; - } - - @Override - public Tenant requestTenantData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public Tenant requestTenantDataByName(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postTenantData(String s, String s1, String s2, Tenant tenant) throws AAIServiceException { - return false; - } - - @Override - public boolean updateAnAIEntry(Update update) throws AAIServiceException { - return false; - } - - @Override - public QueryStatus backup(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus restore(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus isAvailable(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus exists(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus query(String s, boolean b, String s1, String key, String prefix, String s4, SvcLogicContext ctx) throws SvcLogicException { - if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { - for (Map.Entry entry : mockAAI.entrySet()) { - ctx.setAttribute(prefix + "." + entry.getKey(), entry.getValue()); - } - return QueryStatus.SUCCESS; - - - } else if (key.equals("vnf-id = 'test_VNF1'")){ - return QueryStatus.NOT_FOUND; - } - else if (key.equals("vnf-id = 'test_VNF3'")){ - throw new SvcLogicException(); - } - else { - return QueryStatus.FAILURE; - } - - - } - - @Override - public QueryStatus reserve(String s, String s1, String s2, String s3, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus save(String s, boolean b, boolean b1, String s1, Map map, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus release(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus delete(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus notify(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus update(String s, String key, Map data, String prefix, SvcLogicContext ctx) throws SvcLogicException { - if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { - for (Map.Entry entry : data.entrySet()) { - mockAAI.put(entry.getKey(), entry.getValue()); - } - return QueryStatus.SUCCESS; - - - } else if (key.equals("vnf-id = 'test_VNF1'")){ - return QueryStatus.NOT_FOUND; - } - else if (key.equals("vnf-id = 'test_VNF3'")){ - throw new SvcLogicException(); - } - else { - return QueryStatus.FAILURE; - } - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java deleted file mode 100644 index d2f08597e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - -import org.junit.runner.RunWith; -import org.onap.appc.dg.aai.Constants; -import org.onap.appc.dg.aai.impl.AAIPluginImpl; -import org.onap.appc.dg.common.dao.DAOService; -import org.onap.appc.dg.common.impl.LicenseManagerImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.*; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({AAIPluginImpl.class, FrameworkUtil.class}) -public class AAIPluginImplTest { - private AAIPluginImpl aaiPlugin; - private AAIClientMock aaiClient; - - private final BundleContext bundleContext= Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - String prefix = "aai.input.data"; - String vnfId = "test_VNF"; - String vnfId1 = "test_VNF1"; - String vnfId2 = "test_VNF2"; - String vnfId3 = "test_VNF3"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - aaiClient = new AAIClientMock(); - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiClient); - aaiPlugin = new AAIPluginImpl(); - - - } - - - - - @Test - public void testPostGenericVnfData() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId); - ctx.setAttribute("aai.prefix", prefix); - - aaiPlugin.postGenericVnfData(params, ctx); - - Assert.assertEquals("wrong license-key-uuid","123", mockAAI.get("license-key-uuid")); - Assert.assertEquals("wrong license-assignment-group-uuid","1234", mockAAI.get("license-assignment-group-uuid")); - Assert.assertEquals("wrong data.license-key","12345", mockAAI.get("data.license-key")); - } - - - @Test - public void testPostGenericVnfDataNegativeVnfNotFound() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId1); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - - @Test - public void testPostGenericVnfDataNegativeFailure() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId2); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - - @Test - public void testPostGenericVnfDataNegativeSvcLogicException() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId3); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - @Test - public void testGetGenericVnfData() throws Exception { - String vnfNameKey = "vnf-name"; - String vnfType = "VSCP"; - String vnfTypeKey = "vnf-type"; - String provStatus = "Active"; - String provStatusKey = "prov-status"; - String orchestrationStatus = "Running"; - String orchestrationStatusKey = "orchestration-status"; - - Map params = new HashMap<>(); - HashMap mockAAI = new HashMap<>(); - mockAAI.put(vnfNameKey,vnfId); - mockAAI.put(vnfTypeKey,vnfType); - mockAAI.put(provStatusKey, provStatus); - mockAAI.put(orchestrationStatusKey, orchestrationStatus); - aaiClient.setMockAAI(mockAAI); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId); - ctx.setAttribute("aai.prefix", prefix); - - - aaiPlugin.getGenericVnfData(params, ctx); - - Assert.assertEquals("wrong "+vnfNameKey,vnfId, ctx.getAttribute(prefix + "." + vnfNameKey)); - Assert.assertEquals("wrong "+orchestrationStatusKey,orchestrationStatus, ctx.getAttribute(prefix + "." + orchestrationStatusKey)); - Assert.assertEquals("wrong "+vnfTypeKey,vnfType, ctx.getAttribute(prefix + "." + vnfTypeKey)); - Assert.assertEquals("wrong "+provStatusKey,provStatus, ctx.getAttribute(prefix + "." + provStatusKey )); - } - - - - - @Test - public void testGetGenericVnfDataNegativeVnfNotFound() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId1); - ctx.setAttribute("aai.prefix", prefix); - - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - - @Test - public void testGetGenericVnfDataNegativeFailure() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId2); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - - @Test - public void testGetGenericVnfDataNegativeSvcLogicException() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId3); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java new file mode 100644 index 000000000..17bb56f66 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface DCAEReporterPlugin extends SvcLogicJavaPlugin { + void report(Map params, SvcLogicContext ctx) throws APPCException; + void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java new file mode 100644 index 000000000..b0ee4a5c9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +public interface DgResolverPlugin extends SvcLogicJavaPlugin { + void resolveDg(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java new file mode 100644 index 000000000..3e03c2ff7 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +/** + * This interface provides api for sending intermediate messages from DG to initiator + */ +public interface IntermediateMessageSender extends SvcLogicJavaPlugin{ + + /** + * DG plugin which sends intermediate messages generated from DG to the initiator + * @param params expects 1. code, (mandatory) + * 2. message, (mandatory) + * 3. payload, + * 4. prefix + * @param context expects 1. input.common-header.timestamp, + * 2. input.common-header.api-ver, + * 3. input.common-header.originator-id, + * 4. input.common-header.request-id, (mandatory) + * 5. input.common-header.sub-request-id, + * 6. input.action + */ + void sendMessage(Map params, SvcLogicContext context); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java new file mode 100644 index 000000000..95143e145 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface JsonDgUtil extends SvcLogicJavaPlugin { + void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException; + + void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Creates filename and content in Json format. + * @param params + * @param ctx + * @throws APPCException + */ + void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Checks if a file is created. + * @param params + * @param ctx + * @throws APPCException + */ + void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java new file mode 100644 index 000000000..54456b385 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public interface LegacyUtil extends SvcLogicJavaPlugin { + + void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException; + + void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException; + + void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java new file mode 100644 index 000000000..935aa877d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; + +public interface OutputMessagePlugin extends SvcLogicJavaPlugin { + + void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java new file mode 100644 index 000000000..06036c225 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; + + +public interface VNFCDgResolverPlugin extends SvcLogicJavaPlugin { + void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java new file mode 100644 index 000000000..4ce0a9150 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; +/** + * DG plugin created for VNF configuration operation to store data in MD-SAL store + **/ +public interface VNFConfigurator extends SvcLogicJavaPlugin{ + /** + * it is invoked from the DG, and it performs following operations + * 1. checks whether given yang module is present in the MD-SAL store + * 2. if it is absent, loads it into MD-SAL store + * 3. Stores the VNF configuration into MD-SAL store + * @param params should have 1. uniqueId, 2. yang, 3.configJSON, 4.requestId + * @param context - DG context + * @throws APPCException + */ + void storeConfig(Map params, SvcLogicContext context) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java new file mode 100644 index 000000000..b25eaf10f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +public interface VnfExecutionFlow extends SvcLogicJavaPlugin { + void getVnfExecutionFlowData(Map params, SvcLogicContext context); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java new file mode 100644 index 000000000..3c70bab84 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesResolver; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.locks.ReentrantLock; + +abstract class AbstractResolver { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractResolver.class); + + private long interval; + + private volatile long lastUpdate = 0l; + private volatile boolean isUpdateInProgress = false; + private volatile RankedAttributesResolver dgResolver; + + private final ReentrantLock INIT_LOCK = new ReentrantLock(); + + AbstractResolver(int interval) { + this.interval = interval * 1000; + } + + private RankedAttributesResolver createResolver(String resolverType) { + AbstractResolverDataReader reader = ResolverDataReaderFactory.createResolverDataReader(resolverType); + return reader.read(); + } + + private boolean isExpired() { + return (System.currentTimeMillis() - lastUpdate) > interval; + } + + protected RankedAttributesResolver resolver(String resolverType) { + + /* + * In general case, the method implementation is non-blocking. The first + * thread that identifies data expiration will be used to refresh it. In + * meanwhile, any other thread will get the old instance without waiting + * for the updated one. The only exception is the very first time when + * previous instance doesn't exist - in such a cases all the threads + * will be waiting on INIT_LOCK while one of them initializes the + * resolver instance. NOTE: The initialization is intentionally + * implemented in lazy manner to make sure the bundle is initialized + * properly on startup regardless whether or not the data is correct. + * Afterwards, the resolver may be instantiated as many times as needed. + */ + + try { + + if (dgResolver == null) { + INIT_LOCK.lock(); + if (dgResolver != null) { + INIT_LOCK.unlock(); + } + } + + if (!isUpdateInProgress && isExpired()) { + + boolean doUpgrade = false; + + synchronized (this) { + if (!isUpdateInProgress) { + isUpdateInProgress = true; + doUpgrade = true; + } + } + + if (doUpgrade) { + + logger.info("DG resolver configuration data has expired - initiating refresh"); + + try { + RankedAttributesResolver temp = createResolver(resolverType); + dgResolver = temp; + lastUpdate = System.currentTimeMillis(); + + logger.info("DG resolver configuration data has been refreshed successfully"); + } finally { + isUpdateInProgress = false; + } + } + } + } finally { + if (INIT_LOCK.isHeldByCurrentThread()) { + INIT_LOCK.unlock(); + } + } + + return dgResolver; + } + protected abstract FlowKey resolve(final String...args); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java new file mode 100644 index 000000000..c5fe87c77 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.dao.util.DBUtils; +import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; +import org.onap.appc.rankingframework.ConfigurationEntry; +import org.onap.appc.rankingframework.ConfigurationSet; +import org.onap.appc.rankingframework.RankedAttributesResolver; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; +import java.util.Iterator; + +abstract class AbstractResolverDataReader { + + private class ConfigurationSetAdaptor implements ConfigurationSet { + + private final ResultSet resultSet; + + private class ResultSetIterator implements Iterator>, ConfigurationEntry { + @Override + public boolean hasNext() { + try { + return resultSet.next(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public ConfigurationEntry next() { + return this; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public Object getAttributeValue(String name) { + try { + return resultSet.getObject(name); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public FlowKey getResult() { + try { + return new FlowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + } + + ConfigurationSetAdaptor(ResultSet resultSet) { + this.resultSet = resultSet; + } + + @Override + public Iterable> getEntries() { + return new Iterable>() { + + @Override + public Iterator> iterator() { + return new ResultSetIterator(); + } + }; + } + + @Override + public Collection getRankedAttributeNames() { + return getAttributeNames(); + } + } + + protected abstract Collection getAttributeNames(); + protected abstract String getQueryStmt(); + + + + RankedAttributesResolver read() { + try { + try (Connection conn = DBUtils.getConnection("sdnctl")) { + try (PreparedStatement stmt = conn.prepareStatement(getQueryStmt())) { + try (ResultSet res = stmt.executeQuery()) { + if (res.next()) { + res.beforeFirst(); + ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); + return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); + } else { + throw new IllegalStateException(); + } + } + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java new file mode 100644 index 000000000..603b65a19 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + + + +class Constants { + + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + public static final String EVENT_MESSAGE = "event-message"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; + public static final String DG_ERROR_CODE = "output.status.dgerror.code"; + public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; + public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; + public static final String PAYLOAD = "payload"; + public static final String OUTPUT_PAYLOAD = "output.payload"; + + //Added for VnfExecution Flow + public static final String FLOW_STRATEGY = "FlowStrategy" ; + public static final String DEPENDENCY_TYPE = "DependencyType"; + public static final String VNF_TYPE = "vnfType"; + public static final String VNF_VERION = "vnfVersion"; + + + public static final String APPC_INSTANCE_ID= "appc-instance-id"; + + //Added for Cvaas + public static final String CVAAS_DIRECTORY_PATH = "cvaas-directory-path"; + public static final String CVAAS_FILE_NAME = "cvaas-file-name"; + public static final String CVAAS_FILE_CONTENT = "cvaas-file-content"; + + enum LegacyAttributes { + Action("org.onap.appc.action"), + VMID("org.onap.appc.vmid"), + IdentityURL("org.onap.appc.identity.url"), + TenantID("org.onap.appc.tenant.id"), + SkipHypervisorCheck("org.onap.appc.skiphypervisorcheck"); + + private String value; + LegacyAttributes(String value) {this.value = value;} + String getValue() {return value;} + }; + + enum LCMAttributes { + Action("input.action"), + Payload("input.payload"), + VMID("vm-id"), + IdentityURL("identity-url"), + TenantID("tenant.id"), + SkipHypervisorCheck("skip-hypervisor-check"); + + private String value; + LCMAttributes(String value) {this.value = value;} + String getValue() {return value;} + }; + + // DG Resolver Constants + public static final String IN_PARAM_VNF_TYPE = "vnfType"; + public static final String IN_PARAM_VNFC_TYPE = "vnfcType"; + public static final String IN_PARAM_ACTION = "action"; + public static final String IN_PARAM_API_VERSION = "api-ver"; + + public static final String OUT_PARAM_DG_NAME = "dg_name"; + public static final String OUT_PARAM_DG_VERSION= "dg_version"; + public static final String OUT_PARAM_DG_MODULE = "dg_module"; + + public static final String TABLE_NAME = "VNFC_DG_MAPPING"; + public static final String TABLE_COLUMN_VNF_TYPE = "VNF_TYPE"; + public static final String TABLE_COLUMN_VNFC_TYPE = "VNFC_TYPE"; + public static final String TABLE_COLUMN_ACTION = "ACTION"; + public static final String TABLE_COLUMN_API_VERSION = "API_VERSION"; + public static final String TABLE_COLUMN_DG_NAME = "DG_NAME"; + public static final String TABLE_COLUMN_DG_VERSION= "DG_VERSION"; + public static final String TABLE_COLUMN_DG_MODULE = "DG_MODULE"; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java new file mode 100644 index 000000000..68f3cdc68 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventHeader; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.adapter.message.event.EventStatus; +import org.onap.appc.dg.common.DCAEReporterPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +public class DCAEReporterPluginImpl implements DCAEReporterPlugin { + + private EventSender eventSender; + + public DCAEReporterPluginImpl() { + // do nothing + } + + /** + * Injected by blueprint + * + * @param eventSender to be set + */ + public void setEventSender(EventSender eventSender) { + this.eventSender = eventSender; + } + + @Override + public void report(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription,apiVersion,eventId ; + + Integer errorCode = readErrorCode(params,ctx); + errorDescription = params.get(Constants.EVENT_MESSAGE); + + if(StringUtils.isEmpty(errorDescription)) { + reportLegacy(params , ctx); + }else{ + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(errorCode, errorDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + } + + private Integer readErrorCode(Map params, SvcLogicContext ctx) { + Integer errorReportCode = 501; + String errorCodeStr = params.get(Constants.DG_ERROR_CODE); + errorCodeStr = StringUtils.isEmpty(errorCodeStr)? + ctx.getAttribute(Constants.DG_ERROR_CODE):errorCodeStr; + try{ + errorReportCode = Integer.parseInt(errorCodeStr); + } + catch (NumberFormatException e){ + // Ignore Exception + } + return errorReportCode; + } + + @Override + public void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException { + Integer successReportCode = 500; + String successDescription, apiVersion, eventId; + successDescription = params.get(Constants.EVENT_MESSAGE); + + if(StringUtils.isEmpty(successDescription)) { + successDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); + } + + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + if (null == successDescription) { + successDescription = "Success"; + } + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(successReportCode, successDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + + private void reportLegacy(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription,apiVersion,eventId ; + + Integer errorCode = readErrorCode(params,ctx); + errorDescription = getErrorDescriptionAndAddToCtx(params,ctx); + + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(errorCode, errorDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + + private String getErrorDescriptionAndAddToCtx(Map params, SvcLogicContext ctx) { + String errorDescription; + errorDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); + if(StringUtils.isEmpty(errorDescription)) { + errorDescription = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); + } + if(StringUtils.isEmpty(errorDescription)) { + errorDescription = "Unknown"; + } + addToContextIfNotContains(errorDescription,ctx); + return errorDescription; + } + + private void addToContextIfNotContains(String errorDescription, SvcLogicContext ctx) { + String errorDescriptionFromCtx; + errorDescriptionFromCtx = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); + if(StringUtils.isEmpty(errorDescriptionFromCtx)){ + errorDescriptionFromCtx = ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE); + } + if(StringUtils.isEmpty(errorDescriptionFromCtx)){ + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); + }else if (!errorDescriptionFromCtx.contains(errorDescription)){ + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescriptionFromCtx+ " | "+ errorDescription); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java new file mode 100644 index 000000000..c68fde5a2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +import org.onap.appc.dg.common.DgResolverPlugin; + +public class DgResolverPluginImpl implements DgResolverPlugin { + + @Override + public void resolveDg(Map params, SvcLogicContext ctx) throws APPCException { + + String DGName, DGVersion, DGModule = null; + String prefix = params.containsKey("prefix") ? params.get("prefix") + "." : ""; + AbstractResolver resolver = ResolverFactory.createResolver(params.get("DGResolutionType")); + FlowKey flowKey = null; + try { + + if(params.get("DGResolutionType").equalsIgnoreCase("VNFC")) { + flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get(Constants.IN_PARAM_VNFC_TYPE), params.get(Constants.IN_PARAM_API_VERSION)); + }else if(params.get("DGResolutionType").equalsIgnoreCase("VNF")){ + flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get("vnfVersion"), params.get(Constants.IN_PARAM_API_VERSION)); + } + if (flowKey != null) { + DGName = flowKey.name(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_NAME, DGName); + DGVersion = flowKey.version(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_VERSION, DGVersion); + DGModule = flowKey.module(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_MODULE, DGModule); + } else { + throw new RuntimeException(params.get("DGResolutionType")+ " DG not found for vnf type :" + params.get(Constants.IN_PARAM_VNF_TYPE) + + " vnfc type : " + params.get(Constants.IN_PARAM_VNFC_TYPE) + + " action : " + params.get(Constants.IN_PARAM_ACTION) + + " api version : " + params.get(Constants.IN_PARAM_API_VERSION)); + } + } catch (Exception e) { + String msg = EELFResourceManager.format(Msg.FAILURE_RETRIEVE_VNFC_DG,params.get(Constants.IN_PARAM_VNFC_TYPE), e.getMessage()); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw new RuntimeException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java new file mode 100644 index 000000000..68f596f5d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +class FlowKey { + private final String name; + private final String version; + private final String module; + + FlowKey(String name, String version, String module) { + this.name = name; + this.version = version; + this.module = module; + } + + String name() { + return name; + } + + String version() { + return version; + } + + String module() { + return module; + } + + @Override + public String toString() { + StringBuilder buff = new StringBuilder(128); + buff.append("{"); + buff.append("module = ").append(module); + buff.append(", "); + buff.append("name = ").append(name); + buff.append(", "); + buff.append("version = ").append(version); + buff.append("}"); + return buff.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java new file mode 100644 index 000000000..026fa2841 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.dg.common.IntermediateMessageSender; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +public class IntermediateMessageSenderImpl implements IntermediateMessageSender { + + + private Producer producer; + + private Configuration configuration; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(IntermediateMessageSenderImpl.class); + + private static final String STATUS = "STATUS"; + private static final String FAILURE = "FAILURE"; + private static final String SUCCESS = "SUCCESS"; + private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; + + private static final String RESPONSE = "response"; + private static final String MSO = "MSO"; + + public void init(){ + configuration = ConfigurationFactory.getConfiguration(); + Properties properties=configuration.getProperties(); + + String writeTopic = properties.getProperty("appc.LCM.topic.write"); + String apiKey = properties.getProperty("appc.LCM.client.key"); + String apiSecret = properties.getProperty("appc.LCM.client.secret"); + String hostNames = properties.getProperty("appc.LCM.poolMembers"); + + logger.debug("Configuration Read : writeTopic = " + writeTopic +", " + + "hostNames = " + hostNames); + + Set pool = new HashSet<>(); + if (!StringUtils.isEmpty(hostNames)) { + for (String name : hostNames.split(",")) { + pool.add(name); + } + } + + BundleContext ctx = FrameworkUtil.getBundle(IntermediateMessageSenderImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); + } + } + } + + @Override + public void sendMessage(Map params, SvcLogicContext context) { + String prefix = params.get("prefix"); + prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; + try{ + validateInputs(params,context); + String jsonMessage = getJsonMessage(params, context); + logger.debug("Constructed JSON Message : " + jsonMessage); + producer.post("",jsonMessage); + context.setAttribute(prefix + STATUS, SUCCESS); + } + catch(Exception e){ + String errorMessage = "Error sending intermediate message to initiator " + e.getMessage(); + context.setAttribute(prefix + STATUS, FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + logger.error(errorMessage,e); + } + } + + private void validateInputs(Map params, SvcLogicContext context) throws APPCException { + String code = params.get("code"); + String message = params.get("message"); + if(StringUtils.isEmpty(code) || StringUtils.isEmpty(message)){ + throw new APPCException("code or message is empty"); + } + String requestId = context.getAttribute("input.common-header.request-id"); + if(StringUtils.isEmpty(requestId)){ + throw new APPCException("requestId is empty"); + } + } + + private String getJsonMessage(Map params, SvcLogicContext context) { + ObjectMapper objectMapper = new ObjectMapper(); + + ObjectNode commonHeader = getCommonHeader(context); + ObjectNode status = getStatus(params); + + ObjectNode output = objectMapper.createObjectNode(); + output.put("common-header",commonHeader); + output.put("status",status); + + ObjectNode body = objectMapper.createObjectNode(); + body.put("output",output); + + ObjectNode root = objectMapper.createObjectNode(); + root.put("type", RESPONSE); + root.put("rpc-name",context.getAttribute("input.action")); + root.put("cambria.partition", MSO); + root.put("correlation-id",getCorrelationId(context)); + root.put("body",body); + + return root.toString(); + } + + private String getCorrelationId(SvcLogicContext context) { + String requestId = context.getAttribute("input.common-header.request-id"); + String subRequestId = context.getAttribute("input.common-header.sub-request-id"); + return requestId + (StringUtils.isEmpty(subRequestId)?"":("-"+subRequestId)); + } + + private ObjectNode getStatus(Map params) { + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode status = objectMapper.createObjectNode(); + status.put("code",params.get("code")); + status.put("message",params.get("message")); + return status; + } + + private ObjectNode getCommonHeader(SvcLogicContext context) { + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode commonHeader = objectMapper.createObjectNode(); + commonHeader.put("api-ver",context.getAttribute("input.common-header.api-ver")); + commonHeader.put("timestamp",context.getAttribute("input.common-header.timestamp")); + commonHeader.put("originator-id",context.getAttribute("input.common-header.originator-id")); + commonHeader.put("request-id",context.getAttribute("input.common-header.request-id")); + commonHeader.put("sub-request-id",context.getAttribute("input.common-header.sub-request-id")); + return commonHeader; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java new file mode 100644 index 000000000..fff43cbf5 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.common.JsonDgUtil; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.util.JsonUtil; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public class JsonDgUtilImpl implements JsonDgUtil { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class); + + private static final ThreadLocal DATE_TIME_PARSER_THREAD_LOCAL = new ThreadLocal() { + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + } + }; + + @Override + public void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to flatAndAddToContext with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + try { + String paramName = Constants.PAYLOAD; + String payload = params.get(paramName); + if (payload == "") + payload = ctx.getAttribute("input.payload"); + if (!StringUtils.isEmpty(payload)) { + Map flatMap = JsonUtil.convertJsonStringToFlatMap(payload); + if (flatMap != null && flatMap.size() > 0) { + for (Map.Entry entry : flatMap.entrySet()) { + ctx.setAttribute(entry.getKey(), entry.getValue()); + } + } + } else { + logger.warn("input payload param value is empty (\"\") or null"); + } + } catch (Exception e) { + logger.error(e.toString()); + String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED,params.get(Constants.PAYLOAD)); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(e); + } + } + + @Override + public void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException{ + if (logger.isTraceEnabled()) { + logger.trace("Entering to generateOutputPayloadFromContext with SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + + try { + Set keys = ctx.getAttributeKeySet(); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode JsonNode = objectMapper.createObjectNode(); + for (String key : keys) { + if(key.startsWith(Constants.OUTPUT_PAYLOAD+".")){ + String objkey= key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", ""); + if(objkey.contains("[") && objkey.contains("]")){ + ArrayNode arrayNode; + String arrayKey = objkey.substring(0,objkey.indexOf('[')); + int arrayIndex = Integer.parseInt(objkey.substring(objkey.indexOf('[')+1,objkey.indexOf(']'))); + if(JsonNode.has(arrayKey)){ + arrayNode = (ArrayNode)JsonNode.get(arrayKey); + arrayNode.insert(arrayIndex,ctx.getAttribute(key)); + }else { + arrayNode = objectMapper.createArrayNode(); + arrayNode.insert(arrayIndex,ctx.getAttribute(key)); + JsonNode.put(arrayKey,arrayNode); + } + }else { + JsonNode.put(objkey, ctx.getAttribute(key)); + } + } + } + if(JsonNode.size()>0) { + ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(JsonNode)); + } + } catch (Exception e) { + logger.error(e.toString()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw new APPCException(e); + } + + } + + @Override + public void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) + throws APPCException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = " + + ObjectUtils.toString(ctx)); + } + + String vnfId = null; + try { + String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH); + String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID); + + /* + * File name + */ + vnfId = params.get("vnf-id"); + long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis(); + + ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_" + + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json"); + + /* + * File content + */ + + String uploadDate = ctx.getAttribute("running-config.upload-date"); + long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime(); + + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode jsonNode = objectMapper.createObjectNode(); + jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id")); + jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id")); + jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id")); + jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description")); + jsonNode.put("ACTION", ctx.getAttribute("running-config.action")); + jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp); + jsonNode.put("UPLOAD_DATE", uploadDate); + jsonNode.put("VNF_ID", vnfId); + jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name")); + jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name")); + jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type")); + jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type")); + jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address")); + jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator")); + jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete")); + jsonNode.put("CONTENT", ctx.getAttribute("running-config.content")); + + ctx.setAttribute(Constants.CVAAS_FILE_CONTENT, + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)); + + } catch (Exception e) { + String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId; + logger.error(errorMessage, e); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); + throw new APPCException(e); + } + } + + @Override + public void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException { + String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME); + File file = new File(filePath); + + if (!file.exists()) { + String vnfId = params.get("vnf-id"); + String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId; + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); + throw new APPCException(errorMessage); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java new file mode 100644 index 000000000..ad0884b94 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Map; + +import org.onap.appc.dg.common.LegacyUtil; +import org.onap.appc.dg.common.utils.JSONUtil; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class LegacyUtilImpl implements LegacyUtil { + + @Override public void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException { + ctx.setAttribute(Constants.LegacyAttributes.Action.getValue(), ctx.getAttribute(Constants.LCMAttributes.Action.getValue()).toLowerCase()); + + String payloadStr = ctx.getAttribute(Constants.LCMAttributes.Payload.getValue()); + Map payloads = JSONUtil.extractPlainValues(payloadStr, + Constants.LCMAttributes.VMID.getValue(), Constants.LCMAttributes.IdentityURL.getValue(), Constants.LCMAttributes.TenantID.getValue(), + Constants.LCMAttributes.SkipHypervisorCheck.getValue()); + + ctx.setAttribute(Constants.LegacyAttributes.VMID.getValue(), payloads.get(Constants.LCMAttributes.VMID.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.IdentityURL.getValue(), payloads.get(Constants.LCMAttributes.IdentityURL.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.TenantID.getValue(), payloads.get(Constants.LCMAttributes.TenantID.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.SkipHypervisorCheck.getValue(), payloads.get(Constants.LCMAttributes.SkipHypervisorCheck.getValue())); + + } + + @Override + public void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException { + } + + @Override + public void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException { + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java new file mode 100644 index 000000000..66ac82fcb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +import org.onap.appc.dg.common.OutputMessagePlugin; +import org.onap.appc.exceptions.APPCException; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +public class OutputMessagePluginImpl implements OutputMessagePlugin { + + @Override + public void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription, eventDescription; + + //making output.status.message + errorDescription = params.get(Constants.ATTRIBUTE_ERROR_MESSAGE); + eventDescription = params.get(Constants.EVENT_MESSAGE); + + addToContextIfNotContains(errorDescription , eventDescription, ctx); + + //making event-message + + if (!isEmpty(eventDescription)) { + ctx.setAttribute(Constants.EVENT_MESSAGE, eventDescription); + } else { + ctx.setAttribute(Constants.EVENT_MESSAGE, ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + public static void addToContextIfNotContains(String errorDescription, String eventDescription, SvcLogicContext ctx) { + if (!isEmpty(errorDescription)){ + if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); + }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(errorDescription)) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + errorDescription); + } + } + if (!isEmpty(eventDescription)){ + if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, eventDescription); + }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(eventDescription)) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + eventDescription); + } + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java new file mode 100644 index 000000000..790547f37 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class ResolverDataReaderFactory { + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private static class ReferenceHolder{ + private static final AbstractResolverDataReader VNFC_RESOLVER_DATA_READER = new VNFCResolverDataReader(); + + private static final AbstractResolverDataReader VNF_RESOLVER_DATA_READER = new VNFResolverDataReader(); + } + + public static AbstractResolverDataReader createResolverDataReader(String resolverType){ + if(resolverType.equalsIgnoreCase("VNF")){ + return ReferenceHolder.VNF_RESOLVER_DATA_READER; + }else if(resolverType.equalsIgnoreCase("VNFC")){ + return ReferenceHolder.VNFC_RESOLVER_DATA_READER; + }else { + return null; + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java new file mode 100644 index 000000000..e39546846 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class ResolverFactory { + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private static class ReferenceHolder{ + private static final AbstractResolver VNFC_RESOLVER = new VNFCResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); + private static final AbstractResolver VNF_RESOLVER = new VNFResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); + } + + public static AbstractResolver createResolver(String resolverType){ + if(resolverType.equalsIgnoreCase("VNF")){ + return ReferenceHolder.VNF_RESOLVER; + }else if(resolverType.equalsIgnoreCase("VNFC")){ + return ReferenceHolder.VNFC_RESOLVER; + }else { + return null; + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java new file mode 100644 index 000000000..304bdf882 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +public class VNFCDgResolverPluginImpl implements org.onap.appc.dg.common.VNFCDgResolverPlugin { + @Override + public void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException { + DgResolverPluginImpl dgResolverPlugin = new DgResolverPluginImpl(); + params.put("DGResolutionType" , "VNFC"); + dgResolverPlugin.resolveDg(params,ctx); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java new file mode 100644 index 000000000..e2893951b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesContext; + + +public class VNFCResolver extends AbstractResolver { + VNFCResolver(int interval) { + super(interval); + } + + @Override + protected FlowKey resolve(String... args) { + if(args.length !=4){ + throw new IllegalStateException(args.toString()); + } + return resolve(args[0],args[1],args[2],args[3]); + } + + protected FlowKey resolve(final String action, final String vnfType, final String vnfcType, final String apiVersion) { + RankedAttributesContext context = new RankedAttributesContext() { + @Override + public Object getAttributeValue(String name) { + switch (name) { + case "action": + return action; + case "api_version": + return apiVersion; + case "vnf_type": + return vnfType; + case "vnfc_type": + return vnfcType; + default: + throw new IllegalStateException(name); + } + } + }; + + FlowKey wfKey = resolver("VNFC").resolve(context); + + return wfKey; + } +} + diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java new file mode 100644 index 000000000..c78da685c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Arrays; +import java.util.Collection; + +public class VNFCResolverDataReader extends AbstractResolverDataReader { + @Override + protected Collection getAttributeNames() { + return Arrays.asList("action","api_version", "vnf_type", "vnfc_type"); + } + + @Override + protected String getQueryStmt() { + return "select vnf_type,vnfc_type,api_version,action,dg_name,dg_version,dg_module FROM VNFC_DG_MAPPING"; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java new file mode 100644 index 000000000..c46a9c227 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.Constants; +import org.onap.appc.dg.common.VNFConfigurator; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.impl.MDSALStoreFactory; +import org.onap.appc.mdsal.objects.BundleInfo; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.apache.commons.lang3.StringUtils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + + +public class VNFConfiguratorImpl implements VNFConfigurator { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(VNFConfiguratorImpl.class); + private static final String STATUS = "STATUS"; + private static final String FAILURE = "FAILURE"; + private static final String SUCCESS = "SUCCESS"; + private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; + + @Override + public void storeConfig(Map params, SvcLogicContext context) throws APPCException { + String uniqueId = params.get("uniqueId"); + String yang = params.get("yang"); + String configJSON = params.get("configJSON"); + String requestId = params.get("requestId"); + String prefix = params.get("prefix"); + prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; + + MDSALStore store = MDSALStoreFactory.createMDSALStore(); + + logger.debug("Inputs Received : uniqueId = " + uniqueId + + " , yang = " + yang + + " , configJSON = " + configJSON + + " , requestId = " + requestId + + " , prefix = " +prefix); + + try { + + if(StringUtils.isEmpty(uniqueId) + ||StringUtils.isEmpty(yang) + || StringUtils.isEmpty(configJSON) + || StringUtils.isEmpty(requestId)){ + throw new APPCException("One or more input parameters are empty : uniqueId = " + uniqueId + " " + + ", yang = " + yang + + " , configJSON = " + configJSON + + " , requestId = " + requestId); + } + + Date revision = new SimpleDateFormat(Constants.YANG_REVISION_FORMAT).parse(Constants.YANG_REVISION); + + boolean isYangAlreadyLoaded = store.isModulePresent(uniqueId,revision); + + if(!isYangAlreadyLoaded){ + BundleInfo bundleInfo = getBundleInfo(uniqueId); + store.storeYangModule(yang,bundleInfo); + } + store.storeJson(uniqueId, requestId , configJSON); + context.setAttribute(prefix + STATUS, SUCCESS); + } catch (ParseException e) { + String errorMessage ="Error parsing the date : " + Constants.YANG_REVISION + " into format " + Constants.YANG_REVISION_FORMAT; + logger.error(errorMessage,e); + context.setAttribute(prefix + STATUS, FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + throw new APPCException(e.getMessage()); + }catch (MDSALStoreException e){ + String errorMessage = "Error while adding yang to MD-SAL store." + e.getMessage(); + logger.error(errorMessage,e); + context.setAttribute(prefix + STATUS,FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + throw new APPCException(e.getMessage()); + } + + } + + private BundleInfo getBundleInfo(String uniqueId) { + BundleInfo bundleInfo = new BundleInfo(); + bundleInfo.setDescription(uniqueId); + bundleInfo.setName(uniqueId); + bundleInfo.setLocation(uniqueId); + return bundleInfo; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java new file mode 100644 index 000000000..501ad0713 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesContext; + +public class VNFResolver extends AbstractResolver { + VNFResolver(int interval) { + super(interval); + } + + @Override + protected FlowKey resolve(String... args) { + return resolve(args[0],args[1],args[2],args[3]); + } + + + protected FlowKey resolve(final String action, final String vnfType, final String vnfVersion, final String apiVersion) { + RankedAttributesContext context = new RankedAttributesContext() { + @Override + public Object getAttributeValue(String name) { + switch (name) { + case "action": + return action; + case "api_version": + return apiVersion; + case "vnf_type": + return vnfType; + case "vnf_version": + return vnfVersion; + default: + throw new IllegalStateException(name); + } + } + }; + + FlowKey wfKey = resolver("VNF").resolve(context); + + return wfKey; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java new file mode 100644 index 000000000..3c4cf837e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Arrays; +import java.util.Collection; + +/** + * @since January 19,2017 + */ +public class VNFResolverDataReader extends AbstractResolverDataReader { + @Override + protected Collection getAttributeNames() { + return Arrays.asList("action","api_version", "vnf_type", "vnf_version"); + } + + @Override + protected String getQueryStmt() { + return "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java new file mode 100644 index 000000000..65b364f62 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java @@ -0,0 +1,271 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.*; + +import org.onap.appc.dg.common.VnfExecutionFlow; +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.i18n.Msg; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public class VnfExecutionFlowImpl implements VnfExecutionFlow { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(VnfExecutionFlowImpl.class); + + public VnfExecutionFlowImpl(){ + + } + + @Override + public void getVnfExecutionFlowData(Map params, SvcLogicContext context) { + String dependencyType = params.get(Constants.DEPENDENCY_TYPE); + String flowStrategy = params.get(Constants.FLOW_STRATEGY); + DependencyModelIdentifier modelIdentifier = readDependencyModelIdentifier(params); + VnfcDependencyModel dependencyModel = null; + try { + validateInput(dependencyType, flowStrategy, params); + + if (logger.isTraceEnabled()) { + logger.trace("Input received from DG Node : dependencyType = " + dependencyType + + " , flowStrategy = " + flowStrategy + + ", DependencyModelIdentifier = " + modelIdentifier.toString()); + } + + DependencyManager dependencyManager = DependencyModelFactory.createDependencyManager(); + + + dependencyModel = dependencyManager.getVnfcDependencyModel( + modelIdentifier, DependencyTypes.findByString(dependencyType)); + } catch (DependencyModelNotFound e) { + String msg = EELFResourceManager.format(Msg.DEPENDENCY_MODEL_NOT_FOUND,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + context.setAttribute("dependencyModelFound","false"); + return; + } catch (InvalidDependencyModel e){ + String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + }catch (RuntimeException e){ + logger.error(e.getMessage()); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); + throw e; + } + + + context.setAttribute("dependencyModelFound","true"); + if(logger.isDebugEnabled()){ + logger.debug("Dependency Model = " +dependencyModel); + } + logger.info("Building Inventory Model from DG context"); + InventoryModel inventoryModel = readInventoryModel(context); + if(logger.isDebugEnabled()){ + logger.debug("Inventory Model = " +inventoryModel); + } + + if(logger.isDebugEnabled()){ + logger.debug("Validating inventory model with dependency model"); + } + try { + validateInventoryModelWithDependencyModel(dependencyModel, inventoryModel); + }catch (RuntimeException e){ + logger.error(e.getMessage()); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); + throw e; + } + logger.info("Creating flow builder"); + FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder( + FlowStrategies.findByString(flowStrategy)); + + logger.info("Building Vnf flow model"); + VnfcFlowModel flowModel = null; + try{ + flowModel = flowBuilder.buildFlowModel(dependencyModel,inventoryModel); + } + catch (InvalidDependencyModel e){ + String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + } + + // remove VNFCs from the flow model where vserver list is empty + reconcileFlowModel(flowModel); + populateContext(flowModel,context); + if(logger.isDebugEnabled()){ + logContext(context); + } + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVnfExecutionFlowData","VNF ID " + params.get(Constants.VNF_TYPE)); + context.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } + + private void validateInput(String dependencyType, String flowStrategy, Map params) { + DependencyTypes dependencyTypes = DependencyTypes.findByString(dependencyType); + if(dependencyTypes == null){ + throw new RuntimeException("Dependency type from the input : " + dependencyType +" is invalid."); + } + FlowStrategies flowStrategies = FlowStrategies.findByString(flowStrategy); + if(flowStrategies == null){ + throw new RuntimeException("Flow Strategy from the input : " + flowStrategy +" is invalid."); + } + String vnfType = params.get(Constants.VNF_TYPE); + if(vnfType ==null || vnfType.length() ==0){ + throw new RuntimeException("Vnf Type is not passed in the input"); + } + String vnfVersion = params.get(Constants.VNF_VERION); + if(vnfVersion == null || vnfVersion.length() ==0){ + throw new RuntimeException("Vnf Version not found"); + } + } + + private void logContext(SvcLogicContext context) { + for(String key:context.getAttributeKeySet()){ + logger.debug(key + " = " + context.getAttribute(key) + "\n" ); + } + } + + private void populateContext(VnfcFlowModel flowModel, SvcLogicContext context) { + int flowIndex=0; + Iterator> iterator = flowModel.getModelIterator(); + while (iterator.hasNext()){ + for(Vnfc vnfc:iterator.next()){ + context.setAttribute("vnfcFlow["+flowIndex+"].vnfcName",vnfc.getVnfcName()); + context.setAttribute("vnfcFlow["+flowIndex+"].vnfcType",vnfc.getVnfcType()); + context.setAttribute("vnfcFlow["+flowIndex+"].resilienceType",vnfc.getResilienceType()); + context.setAttribute("vnfcFlow["+flowIndex+"].vmCount",Integer.toString(vnfc.getVserverList().size())); + int vmIndex =0; + for(Vserver vm :vnfc.getVserverList()){ + context.setAttribute("vnfcFlow["+flowIndex+"].vm["+vmIndex+"].url",vm.getUrl()); + vmIndex++; + } + flowIndex++; + } + } + context.setAttribute("vnfcFlowCount",Integer.toString(flowIndex)); + } + + private InventoryModel readInventoryModel(SvcLogicContext context) { + String vnfId = context.getAttribute("input.action-identifiers.vnf-id"); + String vnfType = context.getAttribute("vnf.type"); + String vnfVersion = context.getAttribute("vnf.version"); + String vnfcCountStr = context.getAttribute("vnf.vnfcCount"); + Integer vnfcCount = Integer.parseInt(vnfcCountStr); + + Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); + + for(Integer i=0;i params) { + String vnfType = params.get(Constants.VNF_TYPE); + String catalogVersion = params.get(Constants.VNF_VERION); + return new DependencyModelIdentifier(vnfType,catalogVersion); + } + + private void validateInventoryModelWithDependencyModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + Set dependencyModelVnfcSet = new HashSet(); + Set dependencyModelMandatoryVnfcSet = new HashSet(); + Set inventoryModelVnfcsSet = new HashSet(); + + for (Node node : dependencyModel.getDependencies()) { + dependencyModelVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); + if (node.getChild().isMandatory()) { + dependencyModelMandatoryVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); + } + } + + for (Vnfc vnfc : inventoryModel.getVnf().getVnfcs()) { + inventoryModelVnfcsSet.add(vnfc.getVnfcType().toLowerCase()); + } + + // if dependency model and inventory model contains same set of VNFCs, validation succeed and hence return + if (dependencyModelVnfcSet.equals(inventoryModelVnfcsSet)) { + return; + } + + if (inventoryModelVnfcsSet.size() >= dependencyModelVnfcSet.size()) { + Set difference = new HashSet(inventoryModelVnfcsSet); + difference.removeAll(dependencyModelVnfcSet); + logger.error("Dependency model is missing following vnfc type(s): " + difference); + throw new RuntimeException("Dependency model is missing following vnfc type(s): " + difference); + } else { + Set difference = new HashSet(dependencyModelVnfcSet); + difference.removeAll(inventoryModelVnfcsSet); + difference.retainAll(dependencyModelMandatoryVnfcSet); + if (difference.size() > 0) { + logger.error("Inventory model is missing following mandatory vnfc type(s): " + difference); + throw new RuntimeException("Inventory model is missing following mandatory vnfc type(s): " + difference); + } + } + } + + private void reconcileFlowModel(VnfcFlowModel flowModel) { + Iterator> flowIterator = flowModel.getModelIterator(); + while (flowIterator.hasNext()) { + Iterator vnfcIterator = flowIterator.next().iterator(); + while (vnfcIterator.hasNext()) { + Vnfc vnfc = vnfcIterator.next(); + if (vnfc.getVserverList().size() == 0) { + if (logger.isDebugEnabled()) { + logger.debug("No vservers present for Vnfc type: " + vnfc.getVnfcType() + ". Hence, removing it from the flow model."); + } + vnfcIterator.remove(); + } + } + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java new file mode 100644 index 000000000..1572e726b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.objects; + + + +public class ConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java new file mode 100644 index 000000000..38012b1bd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.utils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; + + + +public class JAXBUtil { + + public static T toObject(String xml, Class type) throws JAXBException { + + //create JAXB context + JAXBContext context = JAXBContext.newInstance(type); + + //Create Unmarshaller using JAXB context + Unmarshaller unmarshaller = context.createUnmarshaller(); + + InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes()); + BufferedReader reader = new BufferedReader(new InputStreamReader(xmlInputStream)); + + return type.cast(unmarshaller.unmarshal(reader)); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java new file mode 100644 index 000000000..388295a7d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.utils; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.Reader; +import java.util.*; + + +public class JSONUtil { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + public static T fromJson(String json, Class clazz) { + + try { + return OBJECT_MAPPER.readValue(json, clazz); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static T fromJson(Reader reader, Class clazz) { + + try { + return OBJECT_MAPPER.readValue(reader, clazz); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static String toJson(Object object) { + + try { + return OBJECT_MAPPER.writeValueAsString(object); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static Map extractPlainValues(String json, String ... names) { + if (null == names) return Collections.emptyMap(); + Map values = new HashMap<>(); + try { + final JsonNode jsonNode = OBJECT_MAPPER.readTree(json); + for (String name : names) { + values.put(name, jsonNode.path(name).asText()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return values; + } + + + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java deleted file mode 100644 index 17bb56f66..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface DCAEReporterPlugin extends SvcLogicJavaPlugin { - void report(Map params, SvcLogicContext ctx) throws APPCException; - void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java deleted file mode 100644 index b0ee4a5c9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -public interface DgResolverPlugin extends SvcLogicJavaPlugin { - void resolveDg(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java deleted file mode 100644 index 3e03c2ff7..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -/** - * This interface provides api for sending intermediate messages from DG to initiator - */ -public interface IntermediateMessageSender extends SvcLogicJavaPlugin{ - - /** - * DG plugin which sends intermediate messages generated from DG to the initiator - * @param params expects 1. code, (mandatory) - * 2. message, (mandatory) - * 3. payload, - * 4. prefix - * @param context expects 1. input.common-header.timestamp, - * 2. input.common-header.api-ver, - * 3. input.common-header.originator-id, - * 4. input.common-header.request-id, (mandatory) - * 5. input.common-header.sub-request-id, - * 6. input.action - */ - void sendMessage(Map params, SvcLogicContext context); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java deleted file mode 100644 index 95143e145..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface JsonDgUtil extends SvcLogicJavaPlugin { - void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException; - - void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Creates filename and content in Json format. - * @param params - * @param ctx - * @throws APPCException - */ - void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Checks if a file is created. - * @param params - * @param ctx - * @throws APPCException - */ - void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java deleted file mode 100644 index 54456b385..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - - -public interface LegacyUtil extends SvcLogicJavaPlugin { - - void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException; - - void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException; - - void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java deleted file mode 100644 index 935aa877d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; - -public interface OutputMessagePlugin extends SvcLogicJavaPlugin { - - void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java deleted file mode 100644 index 06036c225..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; - - -public interface VNFCDgResolverPlugin extends SvcLogicJavaPlugin { - void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java deleted file mode 100644 index 4ce0a9150..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; -/** - * DG plugin created for VNF configuration operation to store data in MD-SAL store - **/ -public interface VNFConfigurator extends SvcLogicJavaPlugin{ - /** - * it is invoked from the DG, and it performs following operations - * 1. checks whether given yang module is present in the MD-SAL store - * 2. if it is absent, loads it into MD-SAL store - * 3. Stores the VNF configuration into MD-SAL store - * @param params should have 1. uniqueId, 2. yang, 3.configJSON, 4.requestId - * @param context - DG context - * @throws APPCException - */ - void storeConfig(Map params, SvcLogicContext context) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java deleted file mode 100644 index b25eaf10f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -public interface VnfExecutionFlow extends SvcLogicJavaPlugin { - void getVnfExecutionFlowData(Map params, SvcLogicContext context); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java deleted file mode 100644 index 3c70bab84..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesResolver; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.locks.ReentrantLock; - -abstract class AbstractResolver { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractResolver.class); - - private long interval; - - private volatile long lastUpdate = 0l; - private volatile boolean isUpdateInProgress = false; - private volatile RankedAttributesResolver dgResolver; - - private final ReentrantLock INIT_LOCK = new ReentrantLock(); - - AbstractResolver(int interval) { - this.interval = interval * 1000; - } - - private RankedAttributesResolver createResolver(String resolverType) { - AbstractResolverDataReader reader = ResolverDataReaderFactory.createResolverDataReader(resolverType); - return reader.read(); - } - - private boolean isExpired() { - return (System.currentTimeMillis() - lastUpdate) > interval; - } - - protected RankedAttributesResolver resolver(String resolverType) { - - /* - * In general case, the method implementation is non-blocking. The first - * thread that identifies data expiration will be used to refresh it. In - * meanwhile, any other thread will get the old instance without waiting - * for the updated one. The only exception is the very first time when - * previous instance doesn't exist - in such a cases all the threads - * will be waiting on INIT_LOCK while one of them initializes the - * resolver instance. NOTE: The initialization is intentionally - * implemented in lazy manner to make sure the bundle is initialized - * properly on startup regardless whether or not the data is correct. - * Afterwards, the resolver may be instantiated as many times as needed. - */ - - try { - - if (dgResolver == null) { - INIT_LOCK.lock(); - if (dgResolver != null) { - INIT_LOCK.unlock(); - } - } - - if (!isUpdateInProgress && isExpired()) { - - boolean doUpgrade = false; - - synchronized (this) { - if (!isUpdateInProgress) { - isUpdateInProgress = true; - doUpgrade = true; - } - } - - if (doUpgrade) { - - logger.info("DG resolver configuration data has expired - initiating refresh"); - - try { - RankedAttributesResolver temp = createResolver(resolverType); - dgResolver = temp; - lastUpdate = System.currentTimeMillis(); - - logger.info("DG resolver configuration data has been refreshed successfully"); - } finally { - isUpdateInProgress = false; - } - } - } - } finally { - if (INIT_LOCK.isHeldByCurrentThread()) { - INIT_LOCK.unlock(); - } - } - - return dgResolver; - } - protected abstract FlowKey resolve(final String...args); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java deleted file mode 100644 index c5fe87c77..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.dao.util.DBUtils; -import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; -import org.onap.appc.rankingframework.ConfigurationEntry; -import org.onap.appc.rankingframework.ConfigurationSet; -import org.onap.appc.rankingframework.RankedAttributesResolver; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Iterator; - -abstract class AbstractResolverDataReader { - - private class ConfigurationSetAdaptor implements ConfigurationSet { - - private final ResultSet resultSet; - - private class ResultSetIterator implements Iterator>, ConfigurationEntry { - @Override - public boolean hasNext() { - try { - return resultSet.next(); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public ConfigurationEntry next() { - return this; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Object getAttributeValue(String name) { - try { - return resultSet.getObject(name); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public FlowKey getResult() { - try { - return new FlowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - } - - ConfigurationSetAdaptor(ResultSet resultSet) { - this.resultSet = resultSet; - } - - @Override - public Iterable> getEntries() { - return new Iterable>() { - - @Override - public Iterator> iterator() { - return new ResultSetIterator(); - } - }; - } - - @Override - public Collection getRankedAttributeNames() { - return getAttributeNames(); - } - } - - protected abstract Collection getAttributeNames(); - protected abstract String getQueryStmt(); - - - - RankedAttributesResolver read() { - try { - try (Connection conn = DBUtils.getConnection("sdnctl")) { - try (PreparedStatement stmt = conn.prepareStatement(getQueryStmt())) { - try (ResultSet res = stmt.executeQuery()) { - if (res.next()) { - res.beforeFirst(); - ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); - return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); - } else { - throw new IllegalStateException(); - } - } - } - } - } catch (SQLException e) { - throw new RuntimeException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java deleted file mode 100644 index 603b65a19..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - - - -class Constants { - - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - public static final String EVENT_MESSAGE = "event-message"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; - public static final String DG_ERROR_CODE = "output.status.dgerror.code"; - public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; - public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; - public static final String PAYLOAD = "payload"; - public static final String OUTPUT_PAYLOAD = "output.payload"; - - //Added for VnfExecution Flow - public static final String FLOW_STRATEGY = "FlowStrategy" ; - public static final String DEPENDENCY_TYPE = "DependencyType"; - public static final String VNF_TYPE = "vnfType"; - public static final String VNF_VERION = "vnfVersion"; - - - public static final String APPC_INSTANCE_ID= "appc-instance-id"; - - //Added for Cvaas - public static final String CVAAS_DIRECTORY_PATH = "cvaas-directory-path"; - public static final String CVAAS_FILE_NAME = "cvaas-file-name"; - public static final String CVAAS_FILE_CONTENT = "cvaas-file-content"; - - enum LegacyAttributes { - Action("org.onap.appc.action"), - VMID("org.onap.appc.vmid"), - IdentityURL("org.onap.appc.identity.url"), - TenantID("org.onap.appc.tenant.id"), - SkipHypervisorCheck("org.onap.appc.skiphypervisorcheck"); - - private String value; - LegacyAttributes(String value) {this.value = value;} - String getValue() {return value;} - }; - - enum LCMAttributes { - Action("input.action"), - Payload("input.payload"), - VMID("vm-id"), - IdentityURL("identity-url"), - TenantID("tenant.id"), - SkipHypervisorCheck("skip-hypervisor-check"); - - private String value; - LCMAttributes(String value) {this.value = value;} - String getValue() {return value;} - }; - - // DG Resolver Constants - public static final String IN_PARAM_VNF_TYPE = "vnfType"; - public static final String IN_PARAM_VNFC_TYPE = "vnfcType"; - public static final String IN_PARAM_ACTION = "action"; - public static final String IN_PARAM_API_VERSION = "api-ver"; - - public static final String OUT_PARAM_DG_NAME = "dg_name"; - public static final String OUT_PARAM_DG_VERSION= "dg_version"; - public static final String OUT_PARAM_DG_MODULE = "dg_module"; - - public static final String TABLE_NAME = "VNFC_DG_MAPPING"; - public static final String TABLE_COLUMN_VNF_TYPE = "VNF_TYPE"; - public static final String TABLE_COLUMN_VNFC_TYPE = "VNFC_TYPE"; - public static final String TABLE_COLUMN_ACTION = "ACTION"; - public static final String TABLE_COLUMN_API_VERSION = "API_VERSION"; - public static final String TABLE_COLUMN_DG_NAME = "DG_NAME"; - public static final String TABLE_COLUMN_DG_VERSION= "DG_VERSION"; - public static final String TABLE_COLUMN_DG_MODULE = "DG_MODULE"; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java deleted file mode 100644 index 68f3cdc68..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java +++ /dev/null @@ -1,168 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventHeader; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.adapter.message.event.EventStatus; -import org.onap.appc.dg.common.DCAEReporterPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -public class DCAEReporterPluginImpl implements DCAEReporterPlugin { - - private EventSender eventSender; - - public DCAEReporterPluginImpl() { - // do nothing - } - - /** - * Injected by blueprint - * - * @param eventSender to be set - */ - public void setEventSender(EventSender eventSender) { - this.eventSender = eventSender; - } - - @Override - public void report(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription,apiVersion,eventId ; - - Integer errorCode = readErrorCode(params,ctx); - errorDescription = params.get(Constants.EVENT_MESSAGE); - - if(StringUtils.isEmpty(errorDescription)) { - reportLegacy(params , ctx); - }else{ - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(errorCode, errorDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - } - - private Integer readErrorCode(Map params, SvcLogicContext ctx) { - Integer errorReportCode = 501; - String errorCodeStr = params.get(Constants.DG_ERROR_CODE); - errorCodeStr = StringUtils.isEmpty(errorCodeStr)? - ctx.getAttribute(Constants.DG_ERROR_CODE):errorCodeStr; - try{ - errorReportCode = Integer.parseInt(errorCodeStr); - } - catch (NumberFormatException e){ - // Ignore Exception - } - return errorReportCode; - } - - @Override - public void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException { - Integer successReportCode = 500; - String successDescription, apiVersion, eventId; - successDescription = params.get(Constants.EVENT_MESSAGE); - - if(StringUtils.isEmpty(successDescription)) { - successDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); - } - - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - if (null == successDescription) { - successDescription = "Success"; - } - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(successReportCode, successDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - - private void reportLegacy(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription,apiVersion,eventId ; - - Integer errorCode = readErrorCode(params,ctx); - errorDescription = getErrorDescriptionAndAddToCtx(params,ctx); - - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(errorCode, errorDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - - private String getErrorDescriptionAndAddToCtx(Map params, SvcLogicContext ctx) { - String errorDescription; - errorDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); - if(StringUtils.isEmpty(errorDescription)) { - errorDescription = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); - } - if(StringUtils.isEmpty(errorDescription)) { - errorDescription = "Unknown"; - } - addToContextIfNotContains(errorDescription,ctx); - return errorDescription; - } - - private void addToContextIfNotContains(String errorDescription, SvcLogicContext ctx) { - String errorDescriptionFromCtx; - errorDescriptionFromCtx = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); - if(StringUtils.isEmpty(errorDescriptionFromCtx)){ - errorDescriptionFromCtx = ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE); - } - if(StringUtils.isEmpty(errorDescriptionFromCtx)){ - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); - }else if (!errorDescriptionFromCtx.contains(errorDescription)){ - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescriptionFromCtx+ " | "+ errorDescription); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java deleted file mode 100644 index c68fde5a2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -import org.onap.appc.dg.common.DgResolverPlugin; - -public class DgResolverPluginImpl implements DgResolverPlugin { - - @Override - public void resolveDg(Map params, SvcLogicContext ctx) throws APPCException { - - String DGName, DGVersion, DGModule = null; - String prefix = params.containsKey("prefix") ? params.get("prefix") + "." : ""; - AbstractResolver resolver = ResolverFactory.createResolver(params.get("DGResolutionType")); - FlowKey flowKey = null; - try { - - if(params.get("DGResolutionType").equalsIgnoreCase("VNFC")) { - flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get(Constants.IN_PARAM_VNFC_TYPE), params.get(Constants.IN_PARAM_API_VERSION)); - }else if(params.get("DGResolutionType").equalsIgnoreCase("VNF")){ - flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get("vnfVersion"), params.get(Constants.IN_PARAM_API_VERSION)); - } - if (flowKey != null) { - DGName = flowKey.name(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_NAME, DGName); - DGVersion = flowKey.version(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_VERSION, DGVersion); - DGModule = flowKey.module(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_MODULE, DGModule); - } else { - throw new RuntimeException(params.get("DGResolutionType")+ " DG not found for vnf type :" + params.get(Constants.IN_PARAM_VNF_TYPE) - + " vnfc type : " + params.get(Constants.IN_PARAM_VNFC_TYPE) - + " action : " + params.get(Constants.IN_PARAM_ACTION) - + " api version : " + params.get(Constants.IN_PARAM_API_VERSION)); - } - } catch (Exception e) { - String msg = EELFResourceManager.format(Msg.FAILURE_RETRIEVE_VNFC_DG,params.get(Constants.IN_PARAM_VNFC_TYPE), e.getMessage()); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw new RuntimeException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java deleted file mode 100644 index 68f596f5d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -class FlowKey { - private final String name; - private final String version; - private final String module; - - FlowKey(String name, String version, String module) { - this.name = name; - this.version = version; - this.module = module; - } - - String name() { - return name; - } - - String version() { - return version; - } - - String module() { - return module; - } - - @Override - public String toString() { - StringBuilder buff = new StringBuilder(128); - buff.append("{"); - buff.append("module = ").append(module); - buff.append(", "); - buff.append("name = ").append(name); - buff.append(", "); - buff.append("version = ").append(version); - buff.append("}"); - return buff.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java deleted file mode 100644 index 026fa2841..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.dg.common.IntermediateMessageSender; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -public class IntermediateMessageSenderImpl implements IntermediateMessageSender { - - - private Producer producer; - - private Configuration configuration; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(IntermediateMessageSenderImpl.class); - - private static final String STATUS = "STATUS"; - private static final String FAILURE = "FAILURE"; - private static final String SUCCESS = "SUCCESS"; - private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; - - private static final String RESPONSE = "response"; - private static final String MSO = "MSO"; - - public void init(){ - configuration = ConfigurationFactory.getConfiguration(); - Properties properties=configuration.getProperties(); - - String writeTopic = properties.getProperty("appc.LCM.topic.write"); - String apiKey = properties.getProperty("appc.LCM.client.key"); - String apiSecret = properties.getProperty("appc.LCM.client.secret"); - String hostNames = properties.getProperty("appc.LCM.poolMembers"); - - logger.debug("Configuration Read : writeTopic = " + writeTopic +", " + - "hostNames = " + hostNames); - - Set pool = new HashSet<>(); - if (!StringUtils.isEmpty(hostNames)) { - for (String name : hostNames.split(",")) { - pool.add(name); - } - } - - BundleContext ctx = FrameworkUtil.getBundle(IntermediateMessageSenderImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); - } - } - } - - @Override - public void sendMessage(Map params, SvcLogicContext context) { - String prefix = params.get("prefix"); - prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; - try{ - validateInputs(params,context); - String jsonMessage = getJsonMessage(params, context); - logger.debug("Constructed JSON Message : " + jsonMessage); - producer.post("",jsonMessage); - context.setAttribute(prefix + STATUS, SUCCESS); - } - catch(Exception e){ - String errorMessage = "Error sending intermediate message to initiator " + e.getMessage(); - context.setAttribute(prefix + STATUS, FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - logger.error(errorMessage,e); - } - } - - private void validateInputs(Map params, SvcLogicContext context) throws APPCException { - String code = params.get("code"); - String message = params.get("message"); - if(StringUtils.isEmpty(code) || StringUtils.isEmpty(message)){ - throw new APPCException("code or message is empty"); - } - String requestId = context.getAttribute("input.common-header.request-id"); - if(StringUtils.isEmpty(requestId)){ - throw new APPCException("requestId is empty"); - } - } - - private String getJsonMessage(Map params, SvcLogicContext context) { - ObjectMapper objectMapper = new ObjectMapper(); - - ObjectNode commonHeader = getCommonHeader(context); - ObjectNode status = getStatus(params); - - ObjectNode output = objectMapper.createObjectNode(); - output.put("common-header",commonHeader); - output.put("status",status); - - ObjectNode body = objectMapper.createObjectNode(); - body.put("output",output); - - ObjectNode root = objectMapper.createObjectNode(); - root.put("type", RESPONSE); - root.put("rpc-name",context.getAttribute("input.action")); - root.put("cambria.partition", MSO); - root.put("correlation-id",getCorrelationId(context)); - root.put("body",body); - - return root.toString(); - } - - private String getCorrelationId(SvcLogicContext context) { - String requestId = context.getAttribute("input.common-header.request-id"); - String subRequestId = context.getAttribute("input.common-header.sub-request-id"); - return requestId + (StringUtils.isEmpty(subRequestId)?"":("-"+subRequestId)); - } - - private ObjectNode getStatus(Map params) { - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode status = objectMapper.createObjectNode(); - status.put("code",params.get("code")); - status.put("message",params.get("message")); - return status; - } - - private ObjectNode getCommonHeader(SvcLogicContext context) { - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode commonHeader = objectMapper.createObjectNode(); - commonHeader.put("api-ver",context.getAttribute("input.common-header.api-ver")); - commonHeader.put("timestamp",context.getAttribute("input.common-header.timestamp")); - commonHeader.put("originator-id",context.getAttribute("input.common-header.originator-id")); - commonHeader.put("request-id",context.getAttribute("input.common-header.request-id")); - commonHeader.put("sub-request-id",context.getAttribute("input.common-header.sub-request-id")); - return commonHeader; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java deleted file mode 100644 index fff43cbf5..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.common.JsonDgUtil; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.util.JsonUtil; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - - -public class JsonDgUtilImpl implements JsonDgUtil { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class); - - private static final ThreadLocal DATE_TIME_PARSER_THREAD_LOCAL = new ThreadLocal() { - protected SimpleDateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; - - @Override - public void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to flatAndAddToContext with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - try { - String paramName = Constants.PAYLOAD; - String payload = params.get(paramName); - if (payload == "") - payload = ctx.getAttribute("input.payload"); - if (!StringUtils.isEmpty(payload)) { - Map flatMap = JsonUtil.convertJsonStringToFlatMap(payload); - if (flatMap != null && flatMap.size() > 0) { - for (Map.Entry entry : flatMap.entrySet()) { - ctx.setAttribute(entry.getKey(), entry.getValue()); - } - } - } else { - logger.warn("input payload param value is empty (\"\") or null"); - } - } catch (Exception e) { - logger.error(e.toString()); - String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED,params.get(Constants.PAYLOAD)); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(e); - } - } - - @Override - public void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException{ - if (logger.isTraceEnabled()) { - logger.trace("Entering to generateOutputPayloadFromContext with SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - - try { - Set keys = ctx.getAttributeKeySet(); - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode JsonNode = objectMapper.createObjectNode(); - for (String key : keys) { - if(key.startsWith(Constants.OUTPUT_PAYLOAD+".")){ - String objkey= key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", ""); - if(objkey.contains("[") && objkey.contains("]")){ - ArrayNode arrayNode; - String arrayKey = objkey.substring(0,objkey.indexOf('[')); - int arrayIndex = Integer.parseInt(objkey.substring(objkey.indexOf('[')+1,objkey.indexOf(']'))); - if(JsonNode.has(arrayKey)){ - arrayNode = (ArrayNode)JsonNode.get(arrayKey); - arrayNode.insert(arrayIndex,ctx.getAttribute(key)); - }else { - arrayNode = objectMapper.createArrayNode(); - arrayNode.insert(arrayIndex,ctx.getAttribute(key)); - JsonNode.put(arrayKey,arrayNode); - } - }else { - JsonNode.put(objkey, ctx.getAttribute(key)); - } - } - } - if(JsonNode.size()>0) { - ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(JsonNode)); - } - } catch (Exception e) { - logger.error(e.toString()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw new APPCException(e); - } - - } - - @Override - public void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) - throws APPCException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = " - + ObjectUtils.toString(ctx)); - } - - String vnfId = null; - try { - String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH); - String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID); - - /* - * File name - */ - vnfId = params.get("vnf-id"); - long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis(); - - ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_" - + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json"); - - /* - * File content - */ - - String uploadDate = ctx.getAttribute("running-config.upload-date"); - long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime(); - - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode jsonNode = objectMapper.createObjectNode(); - jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id")); - jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id")); - jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id")); - jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description")); - jsonNode.put("ACTION", ctx.getAttribute("running-config.action")); - jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp); - jsonNode.put("UPLOAD_DATE", uploadDate); - jsonNode.put("VNF_ID", vnfId); - jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name")); - jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name")); - jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type")); - jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type")); - jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address")); - jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator")); - jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete")); - jsonNode.put("CONTENT", ctx.getAttribute("running-config.content")); - - ctx.setAttribute(Constants.CVAAS_FILE_CONTENT, - objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)); - - } catch (Exception e) { - String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId; - logger.error(errorMessage, e); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); - throw new APPCException(e); - } - } - - @Override - public void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException { - String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME); - File file = new File(filePath); - - if (!file.exists()) { - String vnfId = params.get("vnf-id"); - String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId; - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); - throw new APPCException(errorMessage); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java deleted file mode 100644 index ad0884b94..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Map; - -import org.onap.appc.dg.common.LegacyUtil; -import org.onap.appc.dg.common.utils.JSONUtil; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class LegacyUtilImpl implements LegacyUtil { - - @Override public void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException { - ctx.setAttribute(Constants.LegacyAttributes.Action.getValue(), ctx.getAttribute(Constants.LCMAttributes.Action.getValue()).toLowerCase()); - - String payloadStr = ctx.getAttribute(Constants.LCMAttributes.Payload.getValue()); - Map payloads = JSONUtil.extractPlainValues(payloadStr, - Constants.LCMAttributes.VMID.getValue(), Constants.LCMAttributes.IdentityURL.getValue(), Constants.LCMAttributes.TenantID.getValue(), - Constants.LCMAttributes.SkipHypervisorCheck.getValue()); - - ctx.setAttribute(Constants.LegacyAttributes.VMID.getValue(), payloads.get(Constants.LCMAttributes.VMID.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.IdentityURL.getValue(), payloads.get(Constants.LCMAttributes.IdentityURL.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.TenantID.getValue(), payloads.get(Constants.LCMAttributes.TenantID.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.SkipHypervisorCheck.getValue(), payloads.get(Constants.LCMAttributes.SkipHypervisorCheck.getValue())); - - } - - @Override - public void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException { - } - - @Override - public void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException { - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java deleted file mode 100644 index 66ac82fcb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -import org.onap.appc.dg.common.OutputMessagePlugin; -import org.onap.appc.exceptions.APPCException; - -import static org.apache.commons.lang3.StringUtils.isEmpty; - -public class OutputMessagePluginImpl implements OutputMessagePlugin { - - @Override - public void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription, eventDescription; - - //making output.status.message - errorDescription = params.get(Constants.ATTRIBUTE_ERROR_MESSAGE); - eventDescription = params.get(Constants.EVENT_MESSAGE); - - addToContextIfNotContains(errorDescription , eventDescription, ctx); - - //making event-message - - if (!isEmpty(eventDescription)) { - ctx.setAttribute(Constants.EVENT_MESSAGE, eventDescription); - } else { - ctx.setAttribute(Constants.EVENT_MESSAGE, ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - public static void addToContextIfNotContains(String errorDescription, String eventDescription, SvcLogicContext ctx) { - if (!isEmpty(errorDescription)){ - if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); - }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(errorDescription)) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + errorDescription); - } - } - if (!isEmpty(eventDescription)){ - if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, eventDescription); - }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(eventDescription)) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + eventDescription); - } - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java deleted file mode 100644 index 790547f37..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class ResolverDataReaderFactory { - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - private static class ReferenceHolder{ - private static final AbstractResolverDataReader VNFC_RESOLVER_DATA_READER = new VNFCResolverDataReader(); - - private static final AbstractResolverDataReader VNF_RESOLVER_DATA_READER = new VNFResolverDataReader(); - } - - public static AbstractResolverDataReader createResolverDataReader(String resolverType){ - if(resolverType.equalsIgnoreCase("VNF")){ - return ReferenceHolder.VNF_RESOLVER_DATA_READER; - }else if(resolverType.equalsIgnoreCase("VNFC")){ - return ReferenceHolder.VNFC_RESOLVER_DATA_READER; - }else { - return null; - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java deleted file mode 100644 index e39546846..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class ResolverFactory { - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - private static class ReferenceHolder{ - private static final AbstractResolver VNFC_RESOLVER = new VNFCResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); - private static final AbstractResolver VNF_RESOLVER = new VNFResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); - } - - public static AbstractResolver createResolver(String resolverType){ - if(resolverType.equalsIgnoreCase("VNF")){ - return ReferenceHolder.VNF_RESOLVER; - }else if(resolverType.equalsIgnoreCase("VNFC")){ - return ReferenceHolder.VNFC_RESOLVER; - }else { - return null; - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java deleted file mode 100644 index 304bdf882..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -public class VNFCDgResolverPluginImpl implements org.onap.appc.dg.common.VNFCDgResolverPlugin { - @Override - public void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException { - DgResolverPluginImpl dgResolverPlugin = new DgResolverPluginImpl(); - params.put("DGResolutionType" , "VNFC"); - dgResolverPlugin.resolveDg(params,ctx); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java deleted file mode 100644 index e2893951b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesContext; - - -public class VNFCResolver extends AbstractResolver { - VNFCResolver(int interval) { - super(interval); - } - - @Override - protected FlowKey resolve(String... args) { - if(args.length !=4){ - throw new IllegalStateException(args.toString()); - } - return resolve(args[0],args[1],args[2],args[3]); - } - - protected FlowKey resolve(final String action, final String vnfType, final String vnfcType, final String apiVersion) { - RankedAttributesContext context = new RankedAttributesContext() { - @Override - public Object getAttributeValue(String name) { - switch (name) { - case "action": - return action; - case "api_version": - return apiVersion; - case "vnf_type": - return vnfType; - case "vnfc_type": - return vnfcType; - default: - throw new IllegalStateException(name); - } - } - }; - - FlowKey wfKey = resolver("VNFC").resolve(context); - - return wfKey; - } -} - diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java deleted file mode 100644 index c78da685c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Arrays; -import java.util.Collection; - -public class VNFCResolverDataReader extends AbstractResolverDataReader { - @Override - protected Collection getAttributeNames() { - return Arrays.asList("action","api_version", "vnf_type", "vnfc_type"); - } - - @Override - protected String getQueryStmt() { - return "select vnf_type,vnfc_type,api_version,action,dg_name,dg_version,dg_module FROM VNFC_DG_MAPPING"; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java deleted file mode 100644 index c46a9c227..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.Constants; -import org.onap.appc.dg.common.VNFConfigurator; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.impl.MDSALStoreFactory; -import org.onap.appc.mdsal.objects.BundleInfo; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.apache.commons.lang3.StringUtils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; - - -public class VNFConfiguratorImpl implements VNFConfigurator { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(VNFConfiguratorImpl.class); - private static final String STATUS = "STATUS"; - private static final String FAILURE = "FAILURE"; - private static final String SUCCESS = "SUCCESS"; - private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; - - @Override - public void storeConfig(Map params, SvcLogicContext context) throws APPCException { - String uniqueId = params.get("uniqueId"); - String yang = params.get("yang"); - String configJSON = params.get("configJSON"); - String requestId = params.get("requestId"); - String prefix = params.get("prefix"); - prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; - - MDSALStore store = MDSALStoreFactory.createMDSALStore(); - - logger.debug("Inputs Received : uniqueId = " + uniqueId + - " , yang = " + yang + - " , configJSON = " + configJSON + - " , requestId = " + requestId + - " , prefix = " +prefix); - - try { - - if(StringUtils.isEmpty(uniqueId) - ||StringUtils.isEmpty(yang) - || StringUtils.isEmpty(configJSON) - || StringUtils.isEmpty(requestId)){ - throw new APPCException("One or more input parameters are empty : uniqueId = " + uniqueId + " " + - ", yang = " + yang + - " , configJSON = " + configJSON + - " , requestId = " + requestId); - } - - Date revision = new SimpleDateFormat(Constants.YANG_REVISION_FORMAT).parse(Constants.YANG_REVISION); - - boolean isYangAlreadyLoaded = store.isModulePresent(uniqueId,revision); - - if(!isYangAlreadyLoaded){ - BundleInfo bundleInfo = getBundleInfo(uniqueId); - store.storeYangModule(yang,bundleInfo); - } - store.storeJson(uniqueId, requestId , configJSON); - context.setAttribute(prefix + STATUS, SUCCESS); - } catch (ParseException e) { - String errorMessage ="Error parsing the date : " + Constants.YANG_REVISION + " into format " + Constants.YANG_REVISION_FORMAT; - logger.error(errorMessage,e); - context.setAttribute(prefix + STATUS, FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - throw new APPCException(e.getMessage()); - }catch (MDSALStoreException e){ - String errorMessage = "Error while adding yang to MD-SAL store." + e.getMessage(); - logger.error(errorMessage,e); - context.setAttribute(prefix + STATUS,FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - throw new APPCException(e.getMessage()); - } - - } - - private BundleInfo getBundleInfo(String uniqueId) { - BundleInfo bundleInfo = new BundleInfo(); - bundleInfo.setDescription(uniqueId); - bundleInfo.setName(uniqueId); - bundleInfo.setLocation(uniqueId); - return bundleInfo; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java deleted file mode 100644 index 501ad0713..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesContext; - -public class VNFResolver extends AbstractResolver { - VNFResolver(int interval) { - super(interval); - } - - @Override - protected FlowKey resolve(String... args) { - return resolve(args[0],args[1],args[2],args[3]); - } - - - protected FlowKey resolve(final String action, final String vnfType, final String vnfVersion, final String apiVersion) { - RankedAttributesContext context = new RankedAttributesContext() { - @Override - public Object getAttributeValue(String name) { - switch (name) { - case "action": - return action; - case "api_version": - return apiVersion; - case "vnf_type": - return vnfType; - case "vnf_version": - return vnfVersion; - default: - throw new IllegalStateException(name); - } - } - }; - - FlowKey wfKey = resolver("VNF").resolve(context); - - return wfKey; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java deleted file mode 100644 index 3c4cf837e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Arrays; -import java.util.Collection; - -/** - * @since January 19,2017 - */ -public class VNFResolverDataReader extends AbstractResolverDataReader { - @Override - protected Collection getAttributeNames() { - return Arrays.asList("action","api_version", "vnf_type", "vnf_version"); - } - - @Override - protected String getQueryStmt() { - return "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java deleted file mode 100644 index 65b364f62..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java +++ /dev/null @@ -1,271 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.*; - -import org.onap.appc.dg.common.VnfExecutionFlow; -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.i18n.Msg; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public class VnfExecutionFlowImpl implements VnfExecutionFlow { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(VnfExecutionFlowImpl.class); - - public VnfExecutionFlowImpl(){ - - } - - @Override - public void getVnfExecutionFlowData(Map params, SvcLogicContext context) { - String dependencyType = params.get(Constants.DEPENDENCY_TYPE); - String flowStrategy = params.get(Constants.FLOW_STRATEGY); - DependencyModelIdentifier modelIdentifier = readDependencyModelIdentifier(params); - VnfcDependencyModel dependencyModel = null; - try { - validateInput(dependencyType, flowStrategy, params); - - if (logger.isTraceEnabled()) { - logger.trace("Input received from DG Node : dependencyType = " + dependencyType + - " , flowStrategy = " + flowStrategy + - ", DependencyModelIdentifier = " + modelIdentifier.toString()); - } - - DependencyManager dependencyManager = DependencyModelFactory.createDependencyManager(); - - - dependencyModel = dependencyManager.getVnfcDependencyModel( - modelIdentifier, DependencyTypes.findByString(dependencyType)); - } catch (DependencyModelNotFound e) { - String msg = EELFResourceManager.format(Msg.DEPENDENCY_MODEL_NOT_FOUND,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - context.setAttribute("dependencyModelFound","false"); - return; - } catch (InvalidDependencyModel e){ - String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - }catch (RuntimeException e){ - logger.error(e.getMessage()); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); - throw e; - } - - - context.setAttribute("dependencyModelFound","true"); - if(logger.isDebugEnabled()){ - logger.debug("Dependency Model = " +dependencyModel); - } - logger.info("Building Inventory Model from DG context"); - InventoryModel inventoryModel = readInventoryModel(context); - if(logger.isDebugEnabled()){ - logger.debug("Inventory Model = " +inventoryModel); - } - - if(logger.isDebugEnabled()){ - logger.debug("Validating inventory model with dependency model"); - } - try { - validateInventoryModelWithDependencyModel(dependencyModel, inventoryModel); - }catch (RuntimeException e){ - logger.error(e.getMessage()); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); - throw e; - } - logger.info("Creating flow builder"); - FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder( - FlowStrategies.findByString(flowStrategy)); - - logger.info("Building Vnf flow model"); - VnfcFlowModel flowModel = null; - try{ - flowModel = flowBuilder.buildFlowModel(dependencyModel,inventoryModel); - } - catch (InvalidDependencyModel e){ - String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - } - - // remove VNFCs from the flow model where vserver list is empty - reconcileFlowModel(flowModel); - populateContext(flowModel,context); - if(logger.isDebugEnabled()){ - logContext(context); - } - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVnfExecutionFlowData","VNF ID " + params.get(Constants.VNF_TYPE)); - context.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - } - - private void validateInput(String dependencyType, String flowStrategy, Map params) { - DependencyTypes dependencyTypes = DependencyTypes.findByString(dependencyType); - if(dependencyTypes == null){ - throw new RuntimeException("Dependency type from the input : " + dependencyType +" is invalid."); - } - FlowStrategies flowStrategies = FlowStrategies.findByString(flowStrategy); - if(flowStrategies == null){ - throw new RuntimeException("Flow Strategy from the input : " + flowStrategy +" is invalid."); - } - String vnfType = params.get(Constants.VNF_TYPE); - if(vnfType ==null || vnfType.length() ==0){ - throw new RuntimeException("Vnf Type is not passed in the input"); - } - String vnfVersion = params.get(Constants.VNF_VERION); - if(vnfVersion == null || vnfVersion.length() ==0){ - throw new RuntimeException("Vnf Version not found"); - } - } - - private void logContext(SvcLogicContext context) { - for(String key:context.getAttributeKeySet()){ - logger.debug(key + " = " + context.getAttribute(key) + "\n" ); - } - } - - private void populateContext(VnfcFlowModel flowModel, SvcLogicContext context) { - int flowIndex=0; - Iterator> iterator = flowModel.getModelIterator(); - while (iterator.hasNext()){ - for(Vnfc vnfc:iterator.next()){ - context.setAttribute("vnfcFlow["+flowIndex+"].vnfcName",vnfc.getVnfcName()); - context.setAttribute("vnfcFlow["+flowIndex+"].vnfcType",vnfc.getVnfcType()); - context.setAttribute("vnfcFlow["+flowIndex+"].resilienceType",vnfc.getResilienceType()); - context.setAttribute("vnfcFlow["+flowIndex+"].vmCount",Integer.toString(vnfc.getVserverList().size())); - int vmIndex =0; - for(Vserver vm :vnfc.getVserverList()){ - context.setAttribute("vnfcFlow["+flowIndex+"].vm["+vmIndex+"].url",vm.getUrl()); - vmIndex++; - } - flowIndex++; - } - } - context.setAttribute("vnfcFlowCount",Integer.toString(flowIndex)); - } - - private InventoryModel readInventoryModel(SvcLogicContext context) { - String vnfId = context.getAttribute("input.action-identifiers.vnf-id"); - String vnfType = context.getAttribute("vnf.type"); - String vnfVersion = context.getAttribute("vnf.version"); - String vnfcCountStr = context.getAttribute("vnf.vnfcCount"); - Integer vnfcCount = Integer.parseInt(vnfcCountStr); - - Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); - - for(Integer i=0;i params) { - String vnfType = params.get(Constants.VNF_TYPE); - String catalogVersion = params.get(Constants.VNF_VERION); - return new DependencyModelIdentifier(vnfType,catalogVersion); - } - - private void validateInventoryModelWithDependencyModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - Set dependencyModelVnfcSet = new HashSet(); - Set dependencyModelMandatoryVnfcSet = new HashSet(); - Set inventoryModelVnfcsSet = new HashSet(); - - for (Node node : dependencyModel.getDependencies()) { - dependencyModelVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); - if (node.getChild().isMandatory()) { - dependencyModelMandatoryVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); - } - } - - for (Vnfc vnfc : inventoryModel.getVnf().getVnfcs()) { - inventoryModelVnfcsSet.add(vnfc.getVnfcType().toLowerCase()); - } - - // if dependency model and inventory model contains same set of VNFCs, validation succeed and hence return - if (dependencyModelVnfcSet.equals(inventoryModelVnfcsSet)) { - return; - } - - if (inventoryModelVnfcsSet.size() >= dependencyModelVnfcSet.size()) { - Set difference = new HashSet(inventoryModelVnfcsSet); - difference.removeAll(dependencyModelVnfcSet); - logger.error("Dependency model is missing following vnfc type(s): " + difference); - throw new RuntimeException("Dependency model is missing following vnfc type(s): " + difference); - } else { - Set difference = new HashSet(dependencyModelVnfcSet); - difference.removeAll(inventoryModelVnfcsSet); - difference.retainAll(dependencyModelMandatoryVnfcSet); - if (difference.size() > 0) { - logger.error("Inventory model is missing following mandatory vnfc type(s): " + difference); - throw new RuntimeException("Inventory model is missing following mandatory vnfc type(s): " + difference); - } - } - } - - private void reconcileFlowModel(VnfcFlowModel flowModel) { - Iterator> flowIterator = flowModel.getModelIterator(); - while (flowIterator.hasNext()) { - Iterator vnfcIterator = flowIterator.next().iterator(); - while (vnfcIterator.hasNext()) { - Vnfc vnfc = vnfcIterator.next(); - if (vnfc.getVserverList().size() == 0) { - if (logger.isDebugEnabled()) { - logger.debug("No vservers present for Vnfc type: " + vnfc.getVnfcType() + ". Hence, removing it from the flow model."); - } - vnfcIterator.remove(); - } - } - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java deleted file mode 100644 index 1572e726b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.objects; - - - -public class ConnectionDetails { - - private String host; - private int port; - private String username; - private String password; - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java deleted file mode 100644 index 38012b1bd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.utils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; - - - -public class JAXBUtil { - - public static T toObject(String xml, Class type) throws JAXBException { - - //create JAXB context - JAXBContext context = JAXBContext.newInstance(type); - - //Create Unmarshaller using JAXB context - Unmarshaller unmarshaller = context.createUnmarshaller(); - - InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes()); - BufferedReader reader = new BufferedReader(new InputStreamReader(xmlInputStream)); - - return type.cast(unmarshaller.unmarshal(reader)); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java deleted file mode 100644 index 388295a7d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.utils; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.Reader; -import java.util.*; - - -public class JSONUtil { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - public static T fromJson(String json, Class clazz) { - - try { - return OBJECT_MAPPER.readValue(json, clazz); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static T fromJson(Reader reader, Class clazz) { - - try { - return OBJECT_MAPPER.readValue(reader, clazz); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static String toJson(Object object) { - - try { - return OBJECT_MAPPER.writeValueAsString(object); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static Map extractPlainValues(String json, String ... names) { - if (null == names) return Collections.emptyMap(); - Map values = new HashMap<>(); - try { - final JsonNode jsonNode = OBJECT_MAPPER.readTree(json); - for (String name : names) { - values.put(name, jsonNode.path(name).asText()); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - return values; - } - - - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..ec2a2b709 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,50 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.netconfctl=test +org.onap.appc.netconf.db.pass.netconfctl=123456 + +org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +org.onap.appc.netconf.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.sdnctl=test +org.onap.appc.netconf.db.pass.sdnctl=123456 + +### ### +### Properties commented out below provided in appc.properties ### +### ### +#event.pool.members= +event.topic.write=APPC-TEST1 +event.client.key=VIlbtVl6YLhNUrtU +event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT +#restconf.user= +#restconf.pass= + +org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index ec2a2b709..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,50 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.netconf.db.user.netconfctl=test -org.onap.appc.netconf.db.pass.netconfctl=123456 - -org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -org.onap.appc.netconf.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.netconf.db.user.sdnctl=test -org.onap.appc.netconf.db.pass.sdnctl=123456 - -### ### -### Properties commented out below provided in appc.properties ### -### ### -#event.pool.members= -event.topic.write=APPC-TEST1 -event.client.key=VIlbtVl6YLhNUrtU -event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT -#restconf.user= -#restconf.pass= - -org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java new file mode 100644 index 000000000..7c36360f8 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import java.util.HashMap; +import java.util.Map; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DCAEReporterPluginImpl.class, FrameworkUtil.class}) +public class DCAEReporterPluginImplTest { + private SvcLogicContext ctx; + private Map params; + + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref = Mockito.mock(ServiceReference.class); + + @InjectMocks + private DCAEReporterPluginImpl dcaeReporterPlugin; + @Spy + private EventSenderMock eventSender = new EventSenderMock(); + + private String apiVer = "2.0.0"; + private String requestId = "123"; + private String error = "test-error"; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(eventSender); + } + + @Test + public void testReportErrorDescriptionNullBwcModeFalse() throws Exception { + ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("output.status.message", null); + ctx.setAttribute("input.common-header.api-ver", apiVer); + ctx.setAttribute("input.common-header.request-id", requestId); + + errorReasonNullAssert(); + } + + @Test + public void testReportBwcFalse() throws Exception { + ctx = new SvcLogicContext(); + params = new HashMap<>(); + ctx.setAttribute("isBwcMode", "false"); + params.put("output.status.message", error); + ctx.setAttribute("input.common-header.api-ver", apiVer); + ctx.setAttribute("input.common-header.request-id", requestId); + + positiveAssert(); + } + + private void errorReasonNullAssert() throws APPCException { + dcaeReporterPlugin.report(params, ctx); + MessageDestination destination = eventSender.getDestination(); + EventMessage msg = eventSender.getMsg(); + Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); + Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); + Assert.assertEquals("wrong error message", "Unknown", msg.getEventStatus().getReason()); + Assert.assertEquals("wrong destination", destination.name(), "DCAE"); + } + + private void positiveAssert() throws APPCException { + dcaeReporterPlugin.report(params, ctx); + MessageDestination destination = eventSender.getDestination(); + EventMessage msg = eventSender.getMsg(); + Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); + Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); + Assert.assertEquals("wrong error message", error, msg.getEventStatus().getReason()); + Assert.assertEquals("wrong destination", destination.name(), "DCAE"); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java new file mode 100644 index 000000000..cc30d3aea --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Map; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class EventSenderMock implements EventSender { + EventMessage msg; + MessageDestination destination; + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg) { + if (destination != null && msg != null){ + this.msg = msg; + this.destination = destination; + return true; + } + else{ + return false; + } + } + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { + return false; + } + + @Override + public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { + return false; + } + + public EventMessage getMsg() { + return msg; + } + + public MessageDestination getDestination() { + return destination; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java new file mode 100644 index 000000000..6f5a0f13d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import ch.qos.logback.core.Appender; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.dg.common.impl.JsonDgUtilImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; + +public class JsonDgUtilImplTest { + + private final Appender appender = mock(Appender.class); + + + @Test + public void testFlatAndAddToContext() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, payload); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); + Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); + + + + } + + + @Test + public void testFlatAndAddToContextNegativeWrongPayload() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, payload); + try { + jsonDgUtil.flatAndAddToContext(params, ctx); + + } catch (APPCException e) { + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + Assert.assertNotNull(ctx.getAttribute("error-message")); + } + + + } + + + @Test + public void testFlatAndAddToContextPayloadFromContext() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, ""); + ctx.setAttribute("input.payload", payload); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); + Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); + } + + @Test + public void testFlatAndAddToContextNegativeNullPayload() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String testValueKey = "test-key"; + String testValueKey2 = "test-key2"; + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + } + + + @Test + public void testFlatAndAddToContextNegativeEmptyPayload() throws Exception { + + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueKey2 = "test-key2"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, ""); + jsonDgUtil.flatAndAddToContext(params, ctx); + + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + } + + + @Test + public void testGenerateOutputPayloadFromContext() throws Exception { + + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "output.payload"; + String key1 = "output.payload.test-key[0]"; + String key2 = "output.payload.test-key[1]"; + String testValueKey1 = "value1"; + String testValueKey2 = "value2"; + + String key3 = "output.payload.test-key3"; + String testValueKey3 = "value3"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + ctx.setAttribute(key1, testValueKey1); + ctx.setAttribute(key2, testValueKey2); + ctx.setAttribute(key3, testValueKey3); + jsonDgUtil.generateOutputPayloadFromContext(params, ctx); + + Assert.assertNotNull(ctx.getAttribute(key)); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java new file mode 100644 index 000000000..ca3e7f5e2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.dg.common.VNFConfigurator; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.impl.MDSALStoreFactory; +import org.onap.appc.mdsal.impl.MDSALStoreImpl; +import org.onap.appc.mdsal.objects.BundleInfo; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MDSALStoreImpl.class,MDSALStoreFactory.class}) +public class TestVNFConfiguratorImpl { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVNFConfiguratorImpl.class); + + @Before + public void setUp() { + logger.setLevel(EELFLogger.Level.DEBUG); + } + + @Test(expected = APPCException.class) + public void testValidations() throws APPCException { + VNFConfigurator configurator = new VNFConfiguratorImpl(); + Map params = new HashMap(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + configurator.storeConfig(params,new SvcLogicContext()); + } + + @Test + public void testYangPresentScenario() throws APPCException { + + VNFConfigurator configurator = new VNFConfiguratorImpl(); + PowerMockito.mockStatic(MDSALStoreFactory.class); + MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); + PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); + PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(true); + + Map params = new HashMap(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + params.put("requestId","requestId"); + configurator.storeConfig(params,new SvcLogicContext()); + } + + @Test + public void testYangAbsentScenario() throws Exception { + + VNFConfigurator configurator = new VNFConfiguratorImpl(); + PowerMockito.mockStatic(MDSALStoreFactory.class); + + MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); + + PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); + + PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(false); + + PowerMockito.doNothing().when(mdsalStore).storeYangModule(Matchers.anyString(),(BundleInfo)Matchers.anyObject()); + + Map params = new HashMap<>(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + params.put("requestId","requestId"); + configurator.storeConfig(params,new SvcLogicContext()); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java new file mode 100644 index 000000000..bad862030 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java @@ -0,0 +1,420 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.onap.appc.dg.common.VnfExecutionFlow; +import org.onap.appc.dg.common.impl.Constants; +import org.onap.appc.dg.common.impl.VnfExecutionFlowImpl; +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({TestVnfExecutionFlowImpl.class, FrameworkUtil.class,DependencyManager.class,DependencyModelFactory.class}) +public class TestVnfExecutionFlowImpl { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVnfExecutionFlowImpl.class); + + @Before + public void setUp() { + logger.setLevel(EELFLogger.Level.DEBUG); + } + + @Test + public void testPositiveFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testComplexFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContextForComplexDependency(); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test(expected = InvalidDependencyModel.class) + public void testCycleFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContextForComplexDependency(); + VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + private VnfcDependencyModel readCyclicDependencyModel() { + + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + cNode.addParent(b); + + bNode.addParent(d); + dNode.addParent(c); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + + } + + private SvcLogicContext prepareContextForComplexDependency() { + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("input.action-identifiers.vnf-id","1"); + context.setAttribute("vnf.type","vSCP"); + context.setAttribute("vnf.vnfcCount","7"); + + context.setAttribute("vnf.vnfc[0].name","A"); + context.setAttribute("vnf.vnfc[0].type","A"); + context.setAttribute("vnf.vnfc[0].vm_count","2"); + context.setAttribute("vnf.vnfc[0].vm[0].url","A1"); + context.setAttribute("vnf.vnfc[0].vm[1].url","A2"); + + context.setAttribute("vnf.vnfc[1].name","B"); + context.setAttribute("vnf.vnfc[1].type","B"); + context.setAttribute("vnf.vnfc[1].vm_count","5"); + context.setAttribute("vnf.vnfc[1].vm[0].url","B1"); + context.setAttribute("vnf.vnfc[1].vm[1].url","B2"); + context.setAttribute("vnf.vnfc[1].vm[2].url","B3"); + context.setAttribute("vnf.vnfc[1].vm[3].url","B4"); + context.setAttribute("vnf.vnfc[1].vm[4].url","B5"); + + context.setAttribute("vnf.vnfc[2].name","C"); + context.setAttribute("vnf.vnfc[2].type","C"); + context.setAttribute("vnf.vnfc[2].vm_count","4"); + context.setAttribute("vnf.vnfc[2].vm[0].url","C1"); + context.setAttribute("vnf.vnfc[2].vm[1].url","C2"); + context.setAttribute("vnf.vnfc[2].vm[2].url","C3"); + context.setAttribute("vnf.vnfc[2].vm[3].url","C4"); + + context.setAttribute("vnf.vnfc[3].name","D"); + context.setAttribute("vnf.vnfc[3].type","D"); + context.setAttribute("vnf.vnfc[3].vm_count","3"); + context.setAttribute("vnf.vnfc[3].vm[0].url","D1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","D2"); + context.setAttribute("vnf.vnfc[3].vm[2].url","D3"); + + context.setAttribute("vnf.vnfc[4].name","E"); + context.setAttribute("vnf.vnfc[4].type","E"); + context.setAttribute("vnf.vnfc[4].vm_count","2"); + context.setAttribute("vnf.vnfc[4].vm[0].url","E1"); + context.setAttribute("vnf.vnfc[4].vm[1].url","E2"); + + context.setAttribute("vnf.vnfc[5].name","F"); + context.setAttribute("vnf.vnfc[5].type","F"); + context.setAttribute("vnf.vnfc[5].vm_count","1"); + context.setAttribute("vnf.vnfc[5].vm[0].url","F1"); + + context.setAttribute("vnf.vnfc[6].name","G"); + context.setAttribute("vnf.vnfc[6].type","G"); + context.setAttribute("vnf.vnfc[6].vm_count","1"); + context.setAttribute("vnf.vnfc[6].vm[0].url","G1"); + + + return context; + } + + private VnfcDependencyModel readComplexDependencyModel() { + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + + dNode.addParent(b); + eNode.addParent(b); + gNode.addParent(b); + + fNode.addParent(c); + + gNode.addParent(f); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + } + + private VnfcDependencyModel readDependencyModel() { + + Vnfc smp = new Vnfc("SMP","Active-Passive",null); + Vnfc be = new Vnfc("BE","Active-Active",null); + Vnfc fe = new Vnfc("FE","Active-Active",null); + + + Node smpNode = new Node(smp); + Node beNode = new Node(be); + Node feNode = new Node(fe); + + beNode.addParent(smp); + feNode.addParent(be); +// smpNode.addParent(fe); + + Set> dependencies = new HashSet<>(); + dependencies.add(smpNode); + dependencies.add(feNode); + dependencies.add(beNode); + + return new VnfcDependencyModel(dependencies); + } + + private Map prepareParams() { + Map params = new HashMap<>(); + params.put(Constants.DEPENDENCY_TYPE,"RESOURCE"); + params.put(Constants.FLOW_STRATEGY,"FORWARD"); + + params.put(Constants.VNF_TYPE,"vSCP"); + params.put(Constants.VNF_VERION,"1.00"); + return params; + } + + private SvcLogicContext prepareContext() { + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("input.action-identifiers.vnf-id","1"); + context.setAttribute("vnf.type","vSCP"); + context.setAttribute("vnf.vnfcCount","3"); + + context.setAttribute("vnf.vnfc[0].name","SMPname"); + context.setAttribute("vnf.vnfc[0].type","SMP"); + context.setAttribute("vnf.vnfc[0].vm_count","2"); + context.setAttribute("vnf.vnfc[0].vm[0].url","SMP_URL1"); + context.setAttribute("vnf.vnfc[0].vm[1].url","SMP_URL2"); + + context.setAttribute("vnf.vnfc[1].name","BEname"); + context.setAttribute("vnf.vnfc[1].type","BE"); + context.setAttribute("vnf.vnfc[1].vm_count","5"); + context.setAttribute("vnf.vnfc[1].vm[0].url","BE_URL1"); + context.setAttribute("vnf.vnfc[1].vm[1].url","BE_URL2"); + context.setAttribute("vnf.vnfc[1].vm[2].url","BE_URL3"); + context.setAttribute("vnf.vnfc[1].vm[3].url","BE_URL4"); + context.setAttribute("vnf.vnfc[1].vm[4].url","BE_URL5"); + + context.setAttribute("vnf.vnfc[2].name","FEname"); + context.setAttribute("vnf.vnfc[2].type","FE"); + context.setAttribute("vnf.vnfc[2].vm_count","2"); + context.setAttribute("vnf.vnfc[2].vm[0].url","FE_URL1"); + context.setAttribute("vnf.vnfc[2].vm[1].url","FE_URL2"); + + return context; + } + + @Test(expected = RuntimeException.class) + public void testMissingVnfcTypeInDependencyModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + context.setAttribute("vnf.vnfc[3].name","XEname"); + context.setAttribute("vnf.vnfc[3].type","XE"); + context.setAttribute("vnf.vnfc[3].vm_count","2"); + context.setAttribute("vnf.vnfc[3].vm[0].url","XE_URL1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","XE_URL2"); + context.setAttribute("vnf.vnfcCount","4"); + + VnfcDependencyModel dependencyModel = readDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test(expected = RuntimeException.class) + public void testMissingMandatoryVnfcTypeInInventoryModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, true); + Node xeNode = new Node(xe); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testMissingOptionalVnfcTypeInInventoryModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, false); + Node xeNode = new Node(xe); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + context.setAttribute("vnf.vnfc[3].name","YEname"); + context.setAttribute("vnf.vnfc[3].type","YE"); + context.setAttribute("vnf.vnfc[3].vm_count","2"); + context.setAttribute("vnf.vnfc[3].vm[0].url","YE_URL1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","YE_URL2"); + context.setAttribute("vnf.vnfcCount","4"); + + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, false); + Vnfc ye = new Vnfc("YE","Active-Active",null, true); + Node xeNode = new Node(xe); + Node yeNode = new Node(ye); + yeNode.addParent(xe); + + dependencyModel.getDependencies().add(yeNode); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java deleted file mode 100644 index 7c36360f8..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.*; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.util.HashMap; -import java.util.Map; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({DCAEReporterPluginImpl.class, FrameworkUtil.class}) -public class DCAEReporterPluginImplTest { - private SvcLogicContext ctx; - private Map params; - - private final BundleContext bundleContext = Mockito.mock(BundleContext.class); - private final Bundle bundleService = Mockito.mock(Bundle.class); - private final ServiceReference sref = Mockito.mock(ServiceReference.class); - - @InjectMocks - private DCAEReporterPluginImpl dcaeReporterPlugin; - @Spy - private EventSenderMock eventSender = new EventSenderMock(); - - private String apiVer = "2.0.0"; - private String requestId = "123"; - private String error = "test-error"; - - @SuppressWarnings("unchecked") - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(eventSender); - } - - @Test - public void testReportErrorDescriptionNullBwcModeFalse() throws Exception { - ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("output.status.message", null); - ctx.setAttribute("input.common-header.api-ver", apiVer); - ctx.setAttribute("input.common-header.request-id", requestId); - - errorReasonNullAssert(); - } - - @Test - public void testReportBwcFalse() throws Exception { - ctx = new SvcLogicContext(); - params = new HashMap<>(); - ctx.setAttribute("isBwcMode", "false"); - params.put("output.status.message", error); - ctx.setAttribute("input.common-header.api-ver", apiVer); - ctx.setAttribute("input.common-header.request-id", requestId); - - positiveAssert(); - } - - private void errorReasonNullAssert() throws APPCException { - dcaeReporterPlugin.report(params, ctx); - MessageDestination destination = eventSender.getDestination(); - EventMessage msg = eventSender.getMsg(); - Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); - Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); - Assert.assertEquals("wrong error message", "Unknown", msg.getEventStatus().getReason()); - Assert.assertEquals("wrong destination", destination.name(), "DCAE"); - } - - private void positiveAssert() throws APPCException { - dcaeReporterPlugin.report(params, ctx); - MessageDestination destination = eventSender.getDestination(); - EventMessage msg = eventSender.getMsg(); - Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); - Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); - Assert.assertEquals("wrong error message", error, msg.getEventStatus().getReason()); - Assert.assertEquals("wrong destination", destination.name(), "DCAE"); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java deleted file mode 100644 index cc30d3aea..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Map; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class EventSenderMock implements EventSender { - EventMessage msg; - MessageDestination destination; - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg) { - if (destination != null && msg != null){ - this.msg = msg; - this.destination = destination; - return true; - } - else{ - return false; - } - } - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { - return false; - } - - @Override - public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { - return false; - } - - public EventMessage getMsg() { - return msg; - } - - public MessageDestination getDestination() { - return destination; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java deleted file mode 100644 index 6f5a0f13d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import ch.qos.logback.core.Appender; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.dg.common.impl.JsonDgUtilImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.mock; - -public class JsonDgUtilImplTest { - - private final Appender appender = mock(Appender.class); - - - @Test - public void testFlatAndAddToContext() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, payload); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); - Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); - - - - } - - - @Test - public void testFlatAndAddToContextNegativeWrongPayload() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, payload); - try { - jsonDgUtil.flatAndAddToContext(params, ctx); - - } catch (APPCException e) { - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - Assert.assertNotNull(ctx.getAttribute("error-message")); - } - - - } - - - @Test - public void testFlatAndAddToContextPayloadFromContext() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, ""); - ctx.setAttribute("input.payload", payload); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); - Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); - } - - @Test - public void testFlatAndAddToContextNegativeNullPayload() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String testValueKey = "test-key"; - String testValueKey2 = "test-key2"; - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - } - - - @Test - public void testFlatAndAddToContextNegativeEmptyPayload() throws Exception { - - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueKey2 = "test-key2"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, ""); - jsonDgUtil.flatAndAddToContext(params, ctx); - - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - } - - - @Test - public void testGenerateOutputPayloadFromContext() throws Exception { - - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "output.payload"; - String key1 = "output.payload.test-key[0]"; - String key2 = "output.payload.test-key[1]"; - String testValueKey1 = "value1"; - String testValueKey2 = "value2"; - - String key3 = "output.payload.test-key3"; - String testValueKey3 = "value3"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - ctx.setAttribute(key1, testValueKey1); - ctx.setAttribute(key2, testValueKey2); - ctx.setAttribute(key3, testValueKey3); - jsonDgUtil.generateOutputPayloadFromContext(params, ctx); - - Assert.assertNotNull(ctx.getAttribute(key)); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java deleted file mode 100644 index ca3e7f5e2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.dg.common.VNFConfigurator; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.impl.MDSALStoreFactory; -import org.onap.appc.mdsal.impl.MDSALStoreImpl; -import org.onap.appc.mdsal.objects.BundleInfo; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MDSALStoreImpl.class,MDSALStoreFactory.class}) -public class TestVNFConfiguratorImpl { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVNFConfiguratorImpl.class); - - @Before - public void setUp() { - logger.setLevel(EELFLogger.Level.DEBUG); - } - - @Test(expected = APPCException.class) - public void testValidations() throws APPCException { - VNFConfigurator configurator = new VNFConfiguratorImpl(); - Map params = new HashMap(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - configurator.storeConfig(params,new SvcLogicContext()); - } - - @Test - public void testYangPresentScenario() throws APPCException { - - VNFConfigurator configurator = new VNFConfiguratorImpl(); - PowerMockito.mockStatic(MDSALStoreFactory.class); - MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); - PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); - PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(true); - - Map params = new HashMap(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - params.put("requestId","requestId"); - configurator.storeConfig(params,new SvcLogicContext()); - } - - @Test - public void testYangAbsentScenario() throws Exception { - - VNFConfigurator configurator = new VNFConfiguratorImpl(); - PowerMockito.mockStatic(MDSALStoreFactory.class); - - MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); - - PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); - - PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(false); - - PowerMockito.doNothing().when(mdsalStore).storeYangModule(Matchers.anyString(),(BundleInfo)Matchers.anyObject()); - - Map params = new HashMap<>(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - params.put("requestId","requestId"); - configurator.storeConfig(params,new SvcLogicContext()); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java deleted file mode 100644 index bad862030..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java +++ /dev/null @@ -1,420 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.onap.appc.dg.common.VnfExecutionFlow; -import org.onap.appc.dg.common.impl.Constants; -import org.onap.appc.dg.common.impl.VnfExecutionFlowImpl; -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({TestVnfExecutionFlowImpl.class, FrameworkUtil.class,DependencyManager.class,DependencyModelFactory.class}) -public class TestVnfExecutionFlowImpl { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVnfExecutionFlowImpl.class); - - @Before - public void setUp() { - logger.setLevel(EELFLogger.Level.DEBUG); - } - - @Test - public void testPositiveFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testComplexFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContextForComplexDependency(); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test(expected = InvalidDependencyModel.class) - public void testCycleFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContextForComplexDependency(); - VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - private VnfcDependencyModel readCyclicDependencyModel() { - - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - cNode.addParent(b); - - bNode.addParent(d); - dNode.addParent(c); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - - } - - private SvcLogicContext prepareContextForComplexDependency() { - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("input.action-identifiers.vnf-id","1"); - context.setAttribute("vnf.type","vSCP"); - context.setAttribute("vnf.vnfcCount","7"); - - context.setAttribute("vnf.vnfc[0].name","A"); - context.setAttribute("vnf.vnfc[0].type","A"); - context.setAttribute("vnf.vnfc[0].vm_count","2"); - context.setAttribute("vnf.vnfc[0].vm[0].url","A1"); - context.setAttribute("vnf.vnfc[0].vm[1].url","A2"); - - context.setAttribute("vnf.vnfc[1].name","B"); - context.setAttribute("vnf.vnfc[1].type","B"); - context.setAttribute("vnf.vnfc[1].vm_count","5"); - context.setAttribute("vnf.vnfc[1].vm[0].url","B1"); - context.setAttribute("vnf.vnfc[1].vm[1].url","B2"); - context.setAttribute("vnf.vnfc[1].vm[2].url","B3"); - context.setAttribute("vnf.vnfc[1].vm[3].url","B4"); - context.setAttribute("vnf.vnfc[1].vm[4].url","B5"); - - context.setAttribute("vnf.vnfc[2].name","C"); - context.setAttribute("vnf.vnfc[2].type","C"); - context.setAttribute("vnf.vnfc[2].vm_count","4"); - context.setAttribute("vnf.vnfc[2].vm[0].url","C1"); - context.setAttribute("vnf.vnfc[2].vm[1].url","C2"); - context.setAttribute("vnf.vnfc[2].vm[2].url","C3"); - context.setAttribute("vnf.vnfc[2].vm[3].url","C4"); - - context.setAttribute("vnf.vnfc[3].name","D"); - context.setAttribute("vnf.vnfc[3].type","D"); - context.setAttribute("vnf.vnfc[3].vm_count","3"); - context.setAttribute("vnf.vnfc[3].vm[0].url","D1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","D2"); - context.setAttribute("vnf.vnfc[3].vm[2].url","D3"); - - context.setAttribute("vnf.vnfc[4].name","E"); - context.setAttribute("vnf.vnfc[4].type","E"); - context.setAttribute("vnf.vnfc[4].vm_count","2"); - context.setAttribute("vnf.vnfc[4].vm[0].url","E1"); - context.setAttribute("vnf.vnfc[4].vm[1].url","E2"); - - context.setAttribute("vnf.vnfc[5].name","F"); - context.setAttribute("vnf.vnfc[5].type","F"); - context.setAttribute("vnf.vnfc[5].vm_count","1"); - context.setAttribute("vnf.vnfc[5].vm[0].url","F1"); - - context.setAttribute("vnf.vnfc[6].name","G"); - context.setAttribute("vnf.vnfc[6].type","G"); - context.setAttribute("vnf.vnfc[6].vm_count","1"); - context.setAttribute("vnf.vnfc[6].vm[0].url","G1"); - - - return context; - } - - private VnfcDependencyModel readComplexDependencyModel() { - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - - dNode.addParent(b); - eNode.addParent(b); - gNode.addParent(b); - - fNode.addParent(c); - - gNode.addParent(f); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - } - - private VnfcDependencyModel readDependencyModel() { - - Vnfc smp = new Vnfc("SMP","Active-Passive",null); - Vnfc be = new Vnfc("BE","Active-Active",null); - Vnfc fe = new Vnfc("FE","Active-Active",null); - - - Node smpNode = new Node(smp); - Node beNode = new Node(be); - Node feNode = new Node(fe); - - beNode.addParent(smp); - feNode.addParent(be); -// smpNode.addParent(fe); - - Set> dependencies = new HashSet<>(); - dependencies.add(smpNode); - dependencies.add(feNode); - dependencies.add(beNode); - - return new VnfcDependencyModel(dependencies); - } - - private Map prepareParams() { - Map params = new HashMap<>(); - params.put(Constants.DEPENDENCY_TYPE,"RESOURCE"); - params.put(Constants.FLOW_STRATEGY,"FORWARD"); - - params.put(Constants.VNF_TYPE,"vSCP"); - params.put(Constants.VNF_VERION,"1.00"); - return params; - } - - private SvcLogicContext prepareContext() { - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("input.action-identifiers.vnf-id","1"); - context.setAttribute("vnf.type","vSCP"); - context.setAttribute("vnf.vnfcCount","3"); - - context.setAttribute("vnf.vnfc[0].name","SMPname"); - context.setAttribute("vnf.vnfc[0].type","SMP"); - context.setAttribute("vnf.vnfc[0].vm_count","2"); - context.setAttribute("vnf.vnfc[0].vm[0].url","SMP_URL1"); - context.setAttribute("vnf.vnfc[0].vm[1].url","SMP_URL2"); - - context.setAttribute("vnf.vnfc[1].name","BEname"); - context.setAttribute("vnf.vnfc[1].type","BE"); - context.setAttribute("vnf.vnfc[1].vm_count","5"); - context.setAttribute("vnf.vnfc[1].vm[0].url","BE_URL1"); - context.setAttribute("vnf.vnfc[1].vm[1].url","BE_URL2"); - context.setAttribute("vnf.vnfc[1].vm[2].url","BE_URL3"); - context.setAttribute("vnf.vnfc[1].vm[3].url","BE_URL4"); - context.setAttribute("vnf.vnfc[1].vm[4].url","BE_URL5"); - - context.setAttribute("vnf.vnfc[2].name","FEname"); - context.setAttribute("vnf.vnfc[2].type","FE"); - context.setAttribute("vnf.vnfc[2].vm_count","2"); - context.setAttribute("vnf.vnfc[2].vm[0].url","FE_URL1"); - context.setAttribute("vnf.vnfc[2].vm[1].url","FE_URL2"); - - return context; - } - - @Test(expected = RuntimeException.class) - public void testMissingVnfcTypeInDependencyModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - context.setAttribute("vnf.vnfc[3].name","XEname"); - context.setAttribute("vnf.vnfc[3].type","XE"); - context.setAttribute("vnf.vnfc[3].vm_count","2"); - context.setAttribute("vnf.vnfc[3].vm[0].url","XE_URL1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","XE_URL2"); - context.setAttribute("vnf.vnfcCount","4"); - - VnfcDependencyModel dependencyModel = readDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test(expected = RuntimeException.class) - public void testMissingMandatoryVnfcTypeInInventoryModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, true); - Node xeNode = new Node(xe); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testMissingOptionalVnfcTypeInInventoryModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, false); - Node xeNode = new Node(xe); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - context.setAttribute("vnf.vnfc[3].name","YEname"); - context.setAttribute("vnf.vnfc[3].type","YE"); - context.setAttribute("vnf.vnfc[3].vm_count","2"); - context.setAttribute("vnf.vnfc[3].vm[0].url","YE_URL1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","YE_URL2"); - context.setAttribute("vnf.vnfcCount","4"); - - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, false); - Vnfc ye = new Vnfc("YE","Active-Active",null, true); - Node xeNode = new Node(xe); - Node yeNode = new Node(ye); - yeNode.addParent(xe); - - dependencyModel.getDependencies().add(yeNode); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java new file mode 100644 index 000000000..8d04cea11 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager; + +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public interface DependencyManager { + VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier, DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java new file mode 100644 index 000000000..15717f06b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager; + +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public interface DependencyType { + VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java new file mode 100644 index 000000000..ffb6182cd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.exception; + + +public class DependencyModelNotFound extends Exception { + public DependencyModelNotFound(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java new file mode 100644 index 000000000..187020028 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.helper; + +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.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + +import java.io.IOException; +import java.util.*; + + +public class DependencyModelParser { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelParser.class); + private static Map dependencyMap; + private static final String PROPERTIES = "properties"; + private static final String ACTIVE_ACTIVE = "Active-Active"; + private static final String ACTIVE_PASSIVE = "Active-Passive"; + private static final String HIGH_AVAILABLITY = "high_availablity"; + private static final String MANDATORY = "mandatory"; + private static final String TOPOLOGY_TEMPLATE = "topology_template"; + + static { + Map dependencyTypeMappingMap =new HashMap<>(); + dependencyTypeMappingMap.put("geo-activeactive", ACTIVE_ACTIVE); + dependencyTypeMappingMap.put("geo-activestandby", ACTIVE_PASSIVE); + dependencyTypeMappingMap.put("local-activeactive", ACTIVE_ACTIVE); + dependencyTypeMappingMap.put("local-activestandby", ACTIVE_PASSIVE); + dependencyMap = Collections.unmodifiableMap(dependencyTypeMappingMap); + } + + public VnfcDependencyModel generateDependencyModel(String vnfModel,String vnfType) { + Set> dependencies = new HashSet<>(); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + boolean mandatory; + String resilienceType; + String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes."; + try { + ObjectNode root = (ObjectNode) mapper.readTree(vnfModel); + + if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) { + throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or 'node_templates' elements"); + } + + JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE); + JsonNode nodeTemplateNode = topologyTemplateNode.get("node_templates"); + Iterator> itretor = nodeTemplateNode.fields(); + for (JsonNode yamlNode : nodeTemplateNode) { + logger.debug("Processing node: " + yamlNode); + String fullvnfcType = itretor.next().getValue().get("type").textValue(); + String vnfcType= getQualifiedVnfcType(fullvnfcType); + String type = yamlNode.get("type").textValue(); + type = type.substring(0,type.lastIndexOf(".")+1); + if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) { + + if(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null || yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) { + resilienceType = ACTIVE_ACTIVE; + }else { + resilienceType = dependencyMap.get(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).textValue()); + } + + if(yamlNode.get(PROPERTIES).findValue(MANDATORY) == null || yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty()) { + mandatory = false; + }else { + mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue(); + } + String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode); + Node vnfcNode = getNode(dependencies, vnfcType); + if (vnfcNode != null) { + logger.debug("Dependency node already exists for vnfc Type: " + vnfcType); + if (StringUtils.isEmpty(vnfcNode.getChild().getResilienceType())) { + logger.debug("Updating resilience type, dependencies and mandatory attribute for VNFC type: " + vnfcType); + vnfcNode.getChild().setResilienceType(resilienceType); + if (parentList != null && parentList.length > 0) { + addDependencies(dependencies, vnfcNode, parentList); + } + vnfcNode.getChild().setMandatory(mandatory); + } + + } else { + logger.debug("Creating dependency node for : " + vnfcType); + vnfcNode = new Node<>(new Vnfc(vnfcType, resilienceType, null, mandatory)); + if (parentList != null && parentList.length > 0) + addDependencies(dependencies, vnfcNode, parentList); + logger.debug("Adding VNFC to dependency model : " + vnfcNode); + dependencies.add(vnfcNode); + } + } + } + } catch (IOException e) { + logger.error("Error parsing dependency model : " + vnfModel); + logger.error("Error message : " + e); + throw new InvalidDependencyModel("Error parsing dependency model. " + e.getMessage()); + } + return new VnfcDependencyModel(dependencies); + } + + private String getQualifiedVnfcType(String fullvnfcType) { + return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length()); + } + + private void addDependencies(Set> nodes, Node node, String[] parentList) { + for (String type : parentList) { + String parentType = getVnfcType(type); + Node parentNode = getNode(nodes, parentType); + if (parentNode != null) { + logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list "); + node.addParent(parentNode.getChild()); + } else { + logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC "); + parentNode = new Node<>(new Vnfc(parentType, null)); + node.addParent(parentNode.getChild()); + logger.debug("Adding VNFC to dependency model : " + parentNode); + nodes.add(parentNode); + } + } + } + + private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) { + JsonNode requirementsNode = node.get("requirements"); + List dependencyList = new ArrayList(); + if(requirementsNode!=null) { + for (JsonNode internalNode : requirementsNode) { + //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team + if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) + && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) { + if(internalNode.findValue("node") != null) { + String nodeName = internalNode.findValue("node").asText(); + String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText(); + dependencyList.add(getQualifiedVnfcType(fullVnfcName)); + }else{ + throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type")); + } + } + } + return dependencyList.toArray(new String[0]); + }else{ + return new String[0]; + } + } + + private boolean nodeNullCheck(JsonNode internalNode) { + return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null; + } + + private Node getNode(Set> nodes, String vnfcType) { + Iterator itr = nodes.iterator(); + Node node; + while (itr.hasNext()) { + node = (Node) itr.next(); + if (node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)) { + return node; + } + } + return null; + } + + private String getVnfcType(String type) { + return type.substring(type.lastIndexOf('.') + 1, type.length()); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java new file mode 100644 index 000000000..31ea46cc6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.DependencyType; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.cache.MetadataCache; +import org.onap.appc.cache.impl.MetadataCacheFactory; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DependencyManagerImpl implements DependencyManager { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyManagerImpl.class); + + MetadataCache cache; + + DependencyManagerImpl(){ + cache = MetadataCacheFactory.getInstance().getMetadataCache(); + } + + public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier + + " , DependencyTypes = " + dependencyType); + } + VnfcDependencyModel dependencyModel = cache.getObject(modelIdentifier); + if(dependencyModel == null){ + logger.debug("Dependency model not found in cache, creating strategy for reading it"); + DependencyType strategy = getStrategy(dependencyType); + dependencyModel = strategy.getVnfcDependencyModel(modelIdentifier); + } + if (logger.isTraceEnabled()) { + logger.trace("Returning getVnfcDependencyModel with dependency model = "+ dependencyModel); + } + return dependencyModel; + } + + private DependencyType getStrategy(DependencyTypes dependencyType) { + switch (dependencyType){ + case RESOURCE: + return new ResourceDependency(); + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java new file mode 100644 index 000000000..a3fd36937 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.dg.dependencymanager.DependencyManager; + + +public class DependencyModelFactory { + + private static class ReferenceHolder{ + private static final DependencyManagerImpl INSTANCE = new DependencyManagerImpl(); + } + + public static DependencyManager createDependencyManager(){ + return ReferenceHolder.INSTANCE; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java new file mode 100644 index 000000000..73792d3ad --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.metadata.MetadataService; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.appc.dg.dependencymanager.DependencyType; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + + +public class ResourceDependency implements DependencyType{ + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDependency.class); + + + private MetadataService metadataService; + + public ResourceDependency(){ + getMetadataServiceRef(); + } + + private void getMetadataServiceRef() { + BundleContext bctx = FrameworkUtil.getBundle(MetadataService.class).getBundleContext(); + // Get MetadataService reference + ServiceReference sref = bctx.getServiceReference(MetadataService.class.getName()); + if (sref != null) { + logger.info("MetadataService from bundlecontext"); + metadataService = (MetadataService) bctx.getService(sref); + + } else { + logger.info("MetadataService error from bundlecontext"); + logger.warn("Cannot find service reference for org.onap.appc.metadata.MetadataService"); + } + } + + public void setMetadataService(MetadataService metadataService) { + this.metadataService = metadataService; + } + + public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier); + } + String vnfModel = metadataService.getVnfModel(modelIdentifier); + if(vnfModel ==null){ + logger.debug("Vnf model not found from metadata service"); + throw new DependencyModelNotFound("Invalid or Empty VNF Model"); + } + if (logger.isTraceEnabled()) { + logger.trace("Building dependency model for Vnf Model : " + vnfModel); + } + DependencyModelParser modelParser = new DependencyModelParser(); + return modelParser.generateDependencyModel(vnfModel,modelIdentifier.getVnfType()); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java new file mode 100644 index 000000000..78dacd105 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + + +public interface FlowBuilder { + VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel,InventoryModel inventoryModel); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java new file mode 100644 index 000000000..e2c292776 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + + +public interface FlowStrategy { + + VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java new file mode 100644 index 000000000..9f4cfed93 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.exception; + + +public class InvalidDependencyModel extends RuntimeException { + public InvalidDependencyModel(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java new file mode 100644 index 000000000..95e0b6675 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.helper; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; + + +public class Graph { + private int size; + private List vertexList; + + private int[][] dependencyMatrix; + + public Graph(int size){ + this.size =size; + vertexList = new ArrayList<>(); + dependencyMatrix = new int[size][size]; + } + + public void addVertex(T vertex){ + vertexList.add(vertex); + } + + public int getIndex(T vertex){ + return vertexList.indexOf(vertex); + } + + public void addEdge(T vertex1,T vertex2){ + dependencyMatrix[vertexList.indexOf(vertex1)][vertexList.indexOf(vertex2)] = 1; + } + + public int[][] getDependencyMatrix() { + return dependencyMatrix; + } + + public int getSize() { + return size; + } + + public List getVertexList() { + return vertexList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java new file mode 100644 index 000000000..fbb2d5d67 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.onap.appc.dg.flowbuilder.FlowStrategy; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.helper.Graph; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnfc; + + +public abstract class AbstractFlowStrategy implements FlowStrategy { + + protected Graph graph; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractFlowStrategy.class); + + public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + if(logger.isTraceEnabled()){ + logger.trace("Entering into buildFlowModel with dependency model = " + dependencyModel + + "inventory model = " +inventoryModel); + } + + if(dependencyModel == null + || dependencyModel.getDependencies() ==null + || dependencyModel.getDependencies().size() ==0){ + logger.debug("Dependency model not available, building flow model with sequence"); + throw new InvalidDependencyModel("Dependency model either null or does not contain any dependency"); + } + + VnfcFlowModel flowModel = buildFlowModel(dependencyModel); + if(logger.isDebugEnabled()){ + logger.debug("Flow Model without instance data: \n" + flowModel); + } + + logger.info("Populating flow model with A&AI data"); + populateFlowModel(flowModel,inventoryModel); + if(logger.isDebugEnabled()){ + logger.debug("Flow Model with instance data: \n" + flowModel); + } + + return flowModel; + } + + private void populateFlowModel(VnfcFlowModel flowModel, InventoryModel inventoryModel) { + Iterator> flowIterator = null; + + for(Vnfc vnfcFromInventory:inventoryModel.getVnf().getVnfcs()){ + flowIterator = flowModel.getModelIterator(); + String vnfcType = vnfcFromInventory.getVnfcType(); + while (flowIterator.hasNext()){ + for(Vnfc vnfcFromFlowModel:flowIterator.next() ){ + if(vnfcType.equalsIgnoreCase(vnfcFromFlowModel.getVnfcType())){ + vnfcFromFlowModel.setVnfcName(vnfcFromInventory.getVnfcName()); + vnfcFromFlowModel.addVms(vnfcFromInventory.getVserverList()); + } + } + } + + } + + } + + private VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel) throws InvalidDependencyModel { + Set> dependencies = dependencyModel.getDependencies(); + graph = new Graph(dependencies.size()); + + for(Node node:dependencies){ + graph.addVertex(node.getChild()); + } + + for(Node node:dependencies){ + Vnfc child = (Vnfc)node.getChild(); + List parents = node.getParents(); + for(Vnfc parent:parents){ + graph.addEdge(child,parent); + } + } + List> dependencyList = orderDependencies(); + + VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); + int count=0; + int flowModelSize = 0; + for(List vnfcList:dependencyList){ + builder.addMetadata(count,vnfcList); + flowModelSize += vnfcList.size(); + count++; + } + if(flowModelSize != dependencies.size()){ + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + + return builder.build(); + } + + protected abstract List> orderDependencies(); + + /*private VnfcFlowModel buildFlowModelWithoutSequence(InventoryModel inventoryModel) { + VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); + + for(Vnfc vnfc:inventoryModel.getVnf().getVnfcs()){ + builder = builder.addMetadata(0,vnfc); + } + + return builder.build(); + }*/ +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java new file mode 100644 index 000000000..ac5e35b89 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.objects.FlowStrategies; + + +public class FlowBuilderFactory { + private static class ReferenceHolder{ + private static final FlowBuilderFactory FACTORY = new FlowBuilderFactory(); + } + + public static FlowBuilderFactory getInstance(){ + return ReferenceHolder.FACTORY; + } + + public FlowBuilder getFlowBuilder(FlowStrategies flowStrategy){ + + switch (flowStrategy){ + case FORWARD: + return new FlowBuilderImpl(new ForwardFlowStrategy()); + case REVERSE: + return new FlowBuilderImpl(new ReverseFlowStrategy()); + } + return null; + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java new file mode 100644 index 000000000..59d1e4bf9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.FlowStrategy; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class FlowBuilderImpl implements FlowBuilder { + + + + private FlowStrategy strategy; + + FlowBuilderImpl(FlowStrategy strategy){ + this.strategy = strategy; + } + + public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + return strategy.buildFlowModel(dependencyModel, inventoryModel); + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java new file mode 100644 index 000000000..9c5aae64f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + + +public class ForwardFlowStrategy extends AbstractFlowStrategy { + @Override + protected List> orderDependencies() { + ArrayList> arrayList = new ArrayList<>(); + + Queue queue1 = new LinkedList(); + Set queue2 = new LinkedHashSet<>(); + + Set uniqueElementSet = new HashSet<>(); + Set duplicateElementSet = new HashSet<>(); + + // identifying independent nodes in queue1 + for(int rowIndex=0;rowIndex)queue1); + queue1 = new LinkedList<>(queue1); + + boolean flag = true; + + while(flag){ + // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 + while(!queue1.isEmpty()){ + Vnfc listItem = queue1.remove(); + Integer colIndex = graph.getIndex(listItem); + for(Integer index =0;index(queue2)); + if(arrayList.size()>graph.getSize()){ + // dependency list cannot be larger than total number of nodes + // if it happens indicates cycle in the dependency + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + queue1.addAll(queue2); + queue2 = new LinkedHashSet<>(); + } + } + // If any node depends on multiple nodes present in different execution sequence, + // its execution should happen on the higher order, removing its presence on lower execution sequence + if(!duplicateElementSet.isEmpty()){ + for(Vnfc vnfc:duplicateElementSet){ + boolean firstOccurrence= true; + for(int i=arrayList.size()-1;i>=0;i--){ + List list = arrayList.get(i); + if(list.contains(vnfc)){ + if(firstOccurrence){ + firstOccurrence =false; + continue; + } + else{ + list.remove(vnfc); + } + } + + } + } + } + return arrayList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java new file mode 100644 index 000000000..79cd4420c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + + +public class ReverseFlowStrategy extends AbstractFlowStrategy { + + @Override + protected List> orderDependencies() { + ArrayList> arrayList = new ArrayList<>(); + + Queue queue1 = new LinkedList(); + Set queue2 = new LinkedHashSet<>(); + + Set uniqueElementSet = new HashSet<>(); + Set duplicateElementSet = new HashSet<>(); + + // identifying independent nodes in queue1 + for(int colIndex=0;colIndex)queue1); + queue1 = new LinkedList<>(queue1); + + boolean flag = true; + + while(flag){ + // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 + while(!queue1.isEmpty()){ + Vnfc listItem = queue1.remove(); + Integer rowIndex = graph.getIndex(listItem); + for(Integer index =0;index(queue2)); + if(arrayList.size()>graph.getSize()){ + // dependency list cannot be larger than total number of nodes + // if it happens indicates cycle in the dependency + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + queue1.addAll(queue2); + queue2 = new LinkedHashSet<>(); + } + } + // If any node depends on multiple nodes present in different execution sequence, + // its execution should happen on the higher order, removing its presence on lower execution sequence + if(!duplicateElementSet.isEmpty()){ + for(Vnfc vnfc:duplicateElementSet){ + boolean firstOccurrence= true; + for(int i=0;i list = arrayList.get(i); + if(list.contains(vnfc)){ + if(firstOccurrence){ + firstOccurrence =false; + list.remove(vnfc); + } + else{ + continue; + } + } + + } + } + } + return arrayList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java new file mode 100644 index 000000000..b74ea7965 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + + +public enum DependencyTypes { + RESOURCE; + + public static DependencyTypes findByString(String dependencyTypeStr){ + for(DependencyTypes dependencyType : DependencyTypes.values()){ + if(dependencyType.name().equalsIgnoreCase(dependencyTypeStr)){ + return dependencyType; + } + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java new file mode 100644 index 000000000..857d802c2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + + +public enum FlowStrategies { + FORWARD,REVERSE; + + public static FlowStrategies findByString(String flowStrategyStr){ + for(FlowStrategies flowStrategy:FlowStrategies.values()){ + if(flowStrategy.name().equalsIgnoreCase(flowStrategyStr)){ + return flowStrategy; + } + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java new file mode 100644 index 000000000..e9156a8d9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import org.onap.appc.domainmodel.Vnf; + + +public class InventoryModel { + + private Vnf vnf; + + public InventoryModel(Vnf vnf){ + this.vnf= vnf; + } + + public Vnf getVnf() { + return vnf; + } + + @Override + public String toString() { + return "InventoryModel = " + vnf.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java new file mode 100644 index 000000000..586ce7deb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.LinkedList; +import java.util.List; + + +public class Node { + T child; + List parents; + + @Override + public int hashCode(){ + return child.hashCode(); + } + + @Override + public boolean equals(Object object){ + if(object == null){ + return false; + } + if(!(object instanceof Node)){ + return false; + } + Node node = (Node)object; + return this.child.equals(node.getChild()); + } + + public Node(T child){ + this.child = child; + this.parents = new LinkedList<>(); + } + + public T getChild() { + return child; + } + + public List getParents() { + return parents; + } + + public void addParent(T parent){ + this.parents.add(parent); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Node : child = " + child + " , parents = "); + for(T parent:parents){ + stringBuilder.append(parent).append(","); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java new file mode 100644 index 000000000..278d6fcaa --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.Set; + +import org.onap.appc.domainmodel.Vnfc; + + +public class VnfcDependencyModel { + private Set> dependencies; + + public VnfcDependencyModel(Set> dependencies){ + this.dependencies = dependencies; + } + + public Set> getDependencies() { + return dependencies; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("dependencies = "); + for(Node node:dependencies){ + stringBuilder.append(node.toString()).append(", "); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java new file mode 100644 index 000000000..1100e42cb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.*; + +import org.onap.appc.domainmodel.Vnfc; + + +public class VnfcFlowModel { + private Map> flowModelMap; + + private VnfcFlowModel(VnfcFlowModelBuilder builder){ + this.flowModelMap = builder.map; + + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Flow Model : "); + Iterator> iterator = getModelIterator(); + while(iterator.hasNext()){ + for(Vnfc vnfc:iterator.next()){ + stringBuilder.append(vnfc.toString()).append(", \n"); + } + } + + return stringBuilder.toString(); + } + + public Iterator> getModelIterator(){ + return flowModelMap.values().iterator(); + } + + public static class VnfcFlowModelBuilder{ + + Map> map; + + public VnfcFlowModelBuilder(){ + map = new HashMap<>(); + } + + public VnfcFlowModelBuilder addMetadata(Integer index,Vnfc vnfc){ + List vnfcList = this.map.get(index); + if(vnfcList == null){ + vnfcList = new LinkedList<>(); + map.put(index,vnfcList); + } + vnfcList.add(vnfc); + return this; + } + + public VnfcFlowModelBuilder addMetadata(Integer index,List vnfcs){ + List vnfcList = this.map.get(index); + if(vnfcList == null){ + vnfcList = new LinkedList<>(); + map.put(index,vnfcList); + } + vnfcList.addAll(vnfcs); + return this; + } + + public VnfcFlowModel build(){ + return new VnfcFlowModel(this); + } + + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java deleted file mode 100644 index 8d04cea11..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager; - -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public interface DependencyManager { - VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier, DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java deleted file mode 100644 index 15717f06b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager; - -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public interface DependencyType { - VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java deleted file mode 100644 index ffb6182cd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.exception; - - -public class DependencyModelNotFound extends Exception { - public DependencyModelNotFound(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java deleted file mode 100644 index 187020028..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.helper; - -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.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - -import java.io.IOException; -import java.util.*; - - -public class DependencyModelParser { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelParser.class); - private static Map dependencyMap; - private static final String PROPERTIES = "properties"; - private static final String ACTIVE_ACTIVE = "Active-Active"; - private static final String ACTIVE_PASSIVE = "Active-Passive"; - private static final String HIGH_AVAILABLITY = "high_availablity"; - private static final String MANDATORY = "mandatory"; - private static final String TOPOLOGY_TEMPLATE = "topology_template"; - - static { - Map dependencyTypeMappingMap =new HashMap<>(); - dependencyTypeMappingMap.put("geo-activeactive", ACTIVE_ACTIVE); - dependencyTypeMappingMap.put("geo-activestandby", ACTIVE_PASSIVE); - dependencyTypeMappingMap.put("local-activeactive", ACTIVE_ACTIVE); - dependencyTypeMappingMap.put("local-activestandby", ACTIVE_PASSIVE); - dependencyMap = Collections.unmodifiableMap(dependencyTypeMappingMap); - } - - public VnfcDependencyModel generateDependencyModel(String vnfModel,String vnfType) { - Set> dependencies = new HashSet<>(); - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - boolean mandatory; - String resilienceType; - String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes."; - try { - ObjectNode root = (ObjectNode) mapper.readTree(vnfModel); - - if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) { - throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or 'node_templates' elements"); - } - - JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE); - JsonNode nodeTemplateNode = topologyTemplateNode.get("node_templates"); - Iterator> itretor = nodeTemplateNode.fields(); - for (JsonNode yamlNode : nodeTemplateNode) { - logger.debug("Processing node: " + yamlNode); - String fullvnfcType = itretor.next().getValue().get("type").textValue(); - String vnfcType= getQualifiedVnfcType(fullvnfcType); - String type = yamlNode.get("type").textValue(); - type = type.substring(0,type.lastIndexOf(".")+1); - if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) { - - if(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null || yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) { - resilienceType = ACTIVE_ACTIVE; - }else { - resilienceType = dependencyMap.get(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).textValue()); - } - - if(yamlNode.get(PROPERTIES).findValue(MANDATORY) == null || yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty()) { - mandatory = false; - }else { - mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue(); - } - String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode); - Node vnfcNode = getNode(dependencies, vnfcType); - if (vnfcNode != null) { - logger.debug("Dependency node already exists for vnfc Type: " + vnfcType); - if (StringUtils.isEmpty(vnfcNode.getChild().getResilienceType())) { - logger.debug("Updating resilience type, dependencies and mandatory attribute for VNFC type: " + vnfcType); - vnfcNode.getChild().setResilienceType(resilienceType); - if (parentList != null && parentList.length > 0) { - addDependencies(dependencies, vnfcNode, parentList); - } - vnfcNode.getChild().setMandatory(mandatory); - } - - } else { - logger.debug("Creating dependency node for : " + vnfcType); - vnfcNode = new Node<>(new Vnfc(vnfcType, resilienceType, null, mandatory)); - if (parentList != null && parentList.length > 0) - addDependencies(dependencies, vnfcNode, parentList); - logger.debug("Adding VNFC to dependency model : " + vnfcNode); - dependencies.add(vnfcNode); - } - } - } - } catch (IOException e) { - logger.error("Error parsing dependency model : " + vnfModel); - logger.error("Error message : " + e); - throw new InvalidDependencyModel("Error parsing dependency model. " + e.getMessage()); - } - return new VnfcDependencyModel(dependencies); - } - - private String getQualifiedVnfcType(String fullvnfcType) { - return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length()); - } - - private void addDependencies(Set> nodes, Node node, String[] parentList) { - for (String type : parentList) { - String parentType = getVnfcType(type); - Node parentNode = getNode(nodes, parentType); - if (parentNode != null) { - logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list "); - node.addParent(parentNode.getChild()); - } else { - logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC "); - parentNode = new Node<>(new Vnfc(parentType, null)); - node.addParent(parentNode.getChild()); - logger.debug("Adding VNFC to dependency model : " + parentNode); - nodes.add(parentNode); - } - } - } - - private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) { - JsonNode requirementsNode = node.get("requirements"); - List dependencyList = new ArrayList(); - if(requirementsNode!=null) { - for (JsonNode internalNode : requirementsNode) { - //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team - if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) - && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) { - if(internalNode.findValue("node") != null) { - String nodeName = internalNode.findValue("node").asText(); - String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText(); - dependencyList.add(getQualifiedVnfcType(fullVnfcName)); - }else{ - throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type")); - } - } - } - return dependencyList.toArray(new String[0]); - }else{ - return new String[0]; - } - } - - private boolean nodeNullCheck(JsonNode internalNode) { - return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null; - } - - private Node getNode(Set> nodes, String vnfcType) { - Iterator itr = nodes.iterator(); - Node node; - while (itr.hasNext()) { - node = (Node) itr.next(); - if (node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)) { - return node; - } - } - return null; - } - - private String getVnfcType(String type) { - return type.substring(type.lastIndexOf('.') + 1, type.length()); - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java deleted file mode 100644 index 31ea46cc6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.DependencyType; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.cache.MetadataCache; -import org.onap.appc.cache.impl.MetadataCacheFactory; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DependencyManagerImpl implements DependencyManager { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyManagerImpl.class); - - MetadataCache cache; - - DependencyManagerImpl(){ - cache = MetadataCacheFactory.getInstance().getMetadataCache(); - } - - public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier - + " , DependencyTypes = " + dependencyType); - } - VnfcDependencyModel dependencyModel = cache.getObject(modelIdentifier); - if(dependencyModel == null){ - logger.debug("Dependency model not found in cache, creating strategy for reading it"); - DependencyType strategy = getStrategy(dependencyType); - dependencyModel = strategy.getVnfcDependencyModel(modelIdentifier); - } - if (logger.isTraceEnabled()) { - logger.trace("Returning getVnfcDependencyModel with dependency model = "+ dependencyModel); - } - return dependencyModel; - } - - private DependencyType getStrategy(DependencyTypes dependencyType) { - switch (dependencyType){ - case RESOURCE: - return new ResourceDependency(); - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java deleted file mode 100644 index a3fd36937..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.dg.dependencymanager.DependencyManager; - - -public class DependencyModelFactory { - - private static class ReferenceHolder{ - private static final DependencyManagerImpl INSTANCE = new DependencyManagerImpl(); - } - - public static DependencyManager createDependencyManager(){ - return ReferenceHolder.INSTANCE; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java deleted file mode 100644 index 73792d3ad..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.metadata.MetadataService; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.appc.dg.dependencymanager.DependencyType; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - - -public class ResourceDependency implements DependencyType{ - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDependency.class); - - - private MetadataService metadataService; - - public ResourceDependency(){ - getMetadataServiceRef(); - } - - private void getMetadataServiceRef() { - BundleContext bctx = FrameworkUtil.getBundle(MetadataService.class).getBundleContext(); - // Get MetadataService reference - ServiceReference sref = bctx.getServiceReference(MetadataService.class.getName()); - if (sref != null) { - logger.info("MetadataService from bundlecontext"); - metadataService = (MetadataService) bctx.getService(sref); - - } else { - logger.info("MetadataService error from bundlecontext"); - logger.warn("Cannot find service reference for org.onap.appc.metadata.MetadataService"); - } - } - - public void setMetadataService(MetadataService metadataService) { - this.metadataService = metadataService; - } - - public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier); - } - String vnfModel = metadataService.getVnfModel(modelIdentifier); - if(vnfModel ==null){ - logger.debug("Vnf model not found from metadata service"); - throw new DependencyModelNotFound("Invalid or Empty VNF Model"); - } - if (logger.isTraceEnabled()) { - logger.trace("Building dependency model for Vnf Model : " + vnfModel); - } - DependencyModelParser modelParser = new DependencyModelParser(); - return modelParser.generateDependencyModel(vnfModel,modelIdentifier.getVnfType()); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java deleted file mode 100644 index 78dacd105..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - - -public interface FlowBuilder { - VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel,InventoryModel inventoryModel); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java deleted file mode 100644 index e2c292776..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - - -public interface FlowStrategy { - - VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java deleted file mode 100644 index 9f4cfed93..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.exception; - - -public class InvalidDependencyModel extends RuntimeException { - public InvalidDependencyModel(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java deleted file mode 100644 index 95e0b6675..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.helper; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; - - -public class Graph { - private int size; - private List vertexList; - - private int[][] dependencyMatrix; - - public Graph(int size){ - this.size =size; - vertexList = new ArrayList<>(); - dependencyMatrix = new int[size][size]; - } - - public void addVertex(T vertex){ - vertexList.add(vertex); - } - - public int getIndex(T vertex){ - return vertexList.indexOf(vertex); - } - - public void addEdge(T vertex1,T vertex2){ - dependencyMatrix[vertexList.indexOf(vertex1)][vertexList.indexOf(vertex2)] = 1; - } - - public int[][] getDependencyMatrix() { - return dependencyMatrix; - } - - public int getSize() { - return size; - } - - public List getVertexList() { - return vertexList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java deleted file mode 100644 index fbb2d5d67..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.onap.appc.dg.flowbuilder.FlowStrategy; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.helper.Graph; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnfc; - - -public abstract class AbstractFlowStrategy implements FlowStrategy { - - protected Graph graph; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractFlowStrategy.class); - - public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - if(logger.isTraceEnabled()){ - logger.trace("Entering into buildFlowModel with dependency model = " + dependencyModel - + "inventory model = " +inventoryModel); - } - - if(dependencyModel == null - || dependencyModel.getDependencies() ==null - || dependencyModel.getDependencies().size() ==0){ - logger.debug("Dependency model not available, building flow model with sequence"); - throw new InvalidDependencyModel("Dependency model either null or does not contain any dependency"); - } - - VnfcFlowModel flowModel = buildFlowModel(dependencyModel); - if(logger.isDebugEnabled()){ - logger.debug("Flow Model without instance data: \n" + flowModel); - } - - logger.info("Populating flow model with A&AI data"); - populateFlowModel(flowModel,inventoryModel); - if(logger.isDebugEnabled()){ - logger.debug("Flow Model with instance data: \n" + flowModel); - } - - return flowModel; - } - - private void populateFlowModel(VnfcFlowModel flowModel, InventoryModel inventoryModel) { - Iterator> flowIterator = null; - - for(Vnfc vnfcFromInventory:inventoryModel.getVnf().getVnfcs()){ - flowIterator = flowModel.getModelIterator(); - String vnfcType = vnfcFromInventory.getVnfcType(); - while (flowIterator.hasNext()){ - for(Vnfc vnfcFromFlowModel:flowIterator.next() ){ - if(vnfcType.equalsIgnoreCase(vnfcFromFlowModel.getVnfcType())){ - vnfcFromFlowModel.setVnfcName(vnfcFromInventory.getVnfcName()); - vnfcFromFlowModel.addVms(vnfcFromInventory.getVserverList()); - } - } - } - - } - - } - - private VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel) throws InvalidDependencyModel { - Set> dependencies = dependencyModel.getDependencies(); - graph = new Graph(dependencies.size()); - - for(Node node:dependencies){ - graph.addVertex(node.getChild()); - } - - for(Node node:dependencies){ - Vnfc child = (Vnfc)node.getChild(); - List parents = node.getParents(); - for(Vnfc parent:parents){ - graph.addEdge(child,parent); - } - } - List> dependencyList = orderDependencies(); - - VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); - int count=0; - int flowModelSize = 0; - for(List vnfcList:dependencyList){ - builder.addMetadata(count,vnfcList); - flowModelSize += vnfcList.size(); - count++; - } - if(flowModelSize != dependencies.size()){ - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - - return builder.build(); - } - - protected abstract List> orderDependencies(); - - /*private VnfcFlowModel buildFlowModelWithoutSequence(InventoryModel inventoryModel) { - VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); - - for(Vnfc vnfc:inventoryModel.getVnf().getVnfcs()){ - builder = builder.addMetadata(0,vnfc); - } - - return builder.build(); - }*/ -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java deleted file mode 100644 index ac5e35b89..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.objects.FlowStrategies; - - -public class FlowBuilderFactory { - private static class ReferenceHolder{ - private static final FlowBuilderFactory FACTORY = new FlowBuilderFactory(); - } - - public static FlowBuilderFactory getInstance(){ - return ReferenceHolder.FACTORY; - } - - public FlowBuilder getFlowBuilder(FlowStrategies flowStrategy){ - - switch (flowStrategy){ - case FORWARD: - return new FlowBuilderImpl(new ForwardFlowStrategy()); - case REVERSE: - return new FlowBuilderImpl(new ReverseFlowStrategy()); - } - return null; - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java deleted file mode 100644 index 59d1e4bf9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.FlowStrategy; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class FlowBuilderImpl implements FlowBuilder { - - - - private FlowStrategy strategy; - - FlowBuilderImpl(FlowStrategy strategy){ - this.strategy = strategy; - } - - public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - return strategy.buildFlowModel(dependencyModel, inventoryModel); - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java deleted file mode 100644 index 9c5aae64f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - - -public class ForwardFlowStrategy extends AbstractFlowStrategy { - @Override - protected List> orderDependencies() { - ArrayList> arrayList = new ArrayList<>(); - - Queue queue1 = new LinkedList(); - Set queue2 = new LinkedHashSet<>(); - - Set uniqueElementSet = new HashSet<>(); - Set duplicateElementSet = new HashSet<>(); - - // identifying independent nodes in queue1 - for(int rowIndex=0;rowIndex)queue1); - queue1 = new LinkedList<>(queue1); - - boolean flag = true; - - while(flag){ - // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 - while(!queue1.isEmpty()){ - Vnfc listItem = queue1.remove(); - Integer colIndex = graph.getIndex(listItem); - for(Integer index =0;index(queue2)); - if(arrayList.size()>graph.getSize()){ - // dependency list cannot be larger than total number of nodes - // if it happens indicates cycle in the dependency - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - queue1.addAll(queue2); - queue2 = new LinkedHashSet<>(); - } - } - // If any node depends on multiple nodes present in different execution sequence, - // its execution should happen on the higher order, removing its presence on lower execution sequence - if(!duplicateElementSet.isEmpty()){ - for(Vnfc vnfc:duplicateElementSet){ - boolean firstOccurrence= true; - for(int i=arrayList.size()-1;i>=0;i--){ - List list = arrayList.get(i); - if(list.contains(vnfc)){ - if(firstOccurrence){ - firstOccurrence =false; - continue; - } - else{ - list.remove(vnfc); - } - } - - } - } - } - return arrayList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java deleted file mode 100644 index 79cd4420c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - - -public class ReverseFlowStrategy extends AbstractFlowStrategy { - - @Override - protected List> orderDependencies() { - ArrayList> arrayList = new ArrayList<>(); - - Queue queue1 = new LinkedList(); - Set queue2 = new LinkedHashSet<>(); - - Set uniqueElementSet = new HashSet<>(); - Set duplicateElementSet = new HashSet<>(); - - // identifying independent nodes in queue1 - for(int colIndex=0;colIndex)queue1); - queue1 = new LinkedList<>(queue1); - - boolean flag = true; - - while(flag){ - // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 - while(!queue1.isEmpty()){ - Vnfc listItem = queue1.remove(); - Integer rowIndex = graph.getIndex(listItem); - for(Integer index =0;index(queue2)); - if(arrayList.size()>graph.getSize()){ - // dependency list cannot be larger than total number of nodes - // if it happens indicates cycle in the dependency - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - queue1.addAll(queue2); - queue2 = new LinkedHashSet<>(); - } - } - // If any node depends on multiple nodes present in different execution sequence, - // its execution should happen on the higher order, removing its presence on lower execution sequence - if(!duplicateElementSet.isEmpty()){ - for(Vnfc vnfc:duplicateElementSet){ - boolean firstOccurrence= true; - for(int i=0;i list = arrayList.get(i); - if(list.contains(vnfc)){ - if(firstOccurrence){ - firstOccurrence =false; - list.remove(vnfc); - } - else{ - continue; - } - } - - } - } - } - return arrayList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java deleted file mode 100644 index b74ea7965..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - - -public enum DependencyTypes { - RESOURCE; - - public static DependencyTypes findByString(String dependencyTypeStr){ - for(DependencyTypes dependencyType : DependencyTypes.values()){ - if(dependencyType.name().equalsIgnoreCase(dependencyTypeStr)){ - return dependencyType; - } - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java deleted file mode 100644 index 857d802c2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - - -public enum FlowStrategies { - FORWARD,REVERSE; - - public static FlowStrategies findByString(String flowStrategyStr){ - for(FlowStrategies flowStrategy:FlowStrategies.values()){ - if(flowStrategy.name().equalsIgnoreCase(flowStrategyStr)){ - return flowStrategy; - } - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java deleted file mode 100644 index e9156a8d9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import org.onap.appc.domainmodel.Vnf; - - -public class InventoryModel { - - private Vnf vnf; - - public InventoryModel(Vnf vnf){ - this.vnf= vnf; - } - - public Vnf getVnf() { - return vnf; - } - - @Override - public String toString() { - return "InventoryModel = " + vnf.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java deleted file mode 100644 index 586ce7deb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.LinkedList; -import java.util.List; - - -public class Node { - T child; - List parents; - - @Override - public int hashCode(){ - return child.hashCode(); - } - - @Override - public boolean equals(Object object){ - if(object == null){ - return false; - } - if(!(object instanceof Node)){ - return false; - } - Node node = (Node)object; - return this.child.equals(node.getChild()); - } - - public Node(T child){ - this.child = child; - this.parents = new LinkedList<>(); - } - - public T getChild() { - return child; - } - - public List getParents() { - return parents; - } - - public void addParent(T parent){ - this.parents.add(parent); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Node : child = " + child + " , parents = "); - for(T parent:parents){ - stringBuilder.append(parent).append(","); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java deleted file mode 100644 index 278d6fcaa..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.Set; - -import org.onap.appc.domainmodel.Vnfc; - - -public class VnfcDependencyModel { - private Set> dependencies; - - public VnfcDependencyModel(Set> dependencies){ - this.dependencies = dependencies; - } - - public Set> getDependencies() { - return dependencies; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("dependencies = "); - for(Node node:dependencies){ - stringBuilder.append(node.toString()).append(", "); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java deleted file mode 100644 index 1100e42cb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.*; - -import org.onap.appc.domainmodel.Vnfc; - - -public class VnfcFlowModel { - private Map> flowModelMap; - - private VnfcFlowModel(VnfcFlowModelBuilder builder){ - this.flowModelMap = builder.map; - - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Flow Model : "); - Iterator> iterator = getModelIterator(); - while(iterator.hasNext()){ - for(Vnfc vnfc:iterator.next()){ - stringBuilder.append(vnfc.toString()).append(", \n"); - } - } - - return stringBuilder.toString(); - } - - public Iterator> getModelIterator(){ - return flowModelMap.values().iterator(); - } - - public static class VnfcFlowModelBuilder{ - - Map> map; - - public VnfcFlowModelBuilder(){ - map = new HashMap<>(); - } - - public VnfcFlowModelBuilder addMetadata(Integer index,Vnfc vnfc){ - List vnfcList = this.map.get(index); - if(vnfcList == null){ - vnfcList = new LinkedList<>(); - map.put(index,vnfcList); - } - vnfcList.add(vnfc); - return this; - } - - public VnfcFlowModelBuilder addMetadata(Integer index,List vnfcs){ - List vnfcList = this.map.get(index); - if(vnfcList == null){ - vnfcList = new LinkedList<>(); - map.put(index,vnfcList); - } - vnfcList.addAll(vnfcs); - return this; - } - - public VnfcFlowModel build(){ - return new VnfcFlowModel(this); - } - - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java new file mode 100644 index 000000000..009515378 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + + +public class TestFlowBuilder { + + @Test + public void testForwardFlowBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); + } + + @Test + public void testReverseFlowBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); + VnfcDependencyModel dependencyModel = readDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); + } + + @Test + public void testComplexFlowBuilderForward(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + InventoryModel inventoryModel = readComplexInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); + Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); + Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); + Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); + + } + + @Test + public void testComplexFlowBuilderReverse(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + InventoryModel inventoryModel = readComplexInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); + + Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); + Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); + Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); + + } + + @Test(expected = InvalidDependencyModel.class) + public void testCyclicBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + builder.buildFlowModel(dependencyModel,inventoryModel); + } + + @Test(expected = InvalidDependencyModel.class) + public void testCyclicBuilderWithRootNode(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readCyclicDependencyModelWithRootNode(); + InventoryModel inventoryModel = readInventoryModel(); + builder.buildFlowModel(dependencyModel,inventoryModel); + } + + private VnfcDependencyModel readCyclicDependencyModelWithRootNode() { + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + + bNode.addParent(c); + cNode.addParent(b); + + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + + return new VnfcDependencyModel(dependencies); + } + + private InventoryModel readComplexInventoryModel() { + Vnf vnf = new Vnf("vnf_1","vABCD","1"); + + Vnfc vnfcA = new Vnfc("A","Active-Active","A_Name"); + Vnfc vnfcB = new Vnfc("B","Active-Active","B_Name"); + Vnfc vnfcC = new Vnfc("C","Active-Active","C_Name"); + Vnfc vnfcD = new Vnfc("D","Active-Active","D_Name"); + Vnfc vnfcE = new Vnfc("E","Active-Active","E_Name"); + Vnfc vnfcF = new Vnfc("F","Active-Active","F_Name"); + Vnfc vnfcG = new Vnfc("G","Active-Active","G_Name"); + + vnfcA.addVm(new Vserver("VM_URL_A1")); + vnfcB.addVm(new Vserver("VM_URL_B1")); + vnfcC.addVm(new Vserver("VM_URL_C1")); + vnfcD.addVm(new Vserver("VM_URL_D1")); + vnfcE.addVm(new Vserver("VM_URL_E1")); + vnfcF.addVm(new Vserver("VM_URL_F1")); + vnfcG.addVm(new Vserver("VM_URL_G1")); + + vnf.addVnfc(vnfcA); + vnf.addVnfc(vnfcB); + vnf.addVnfc(vnfcC); + vnf.addVnfc(vnfcD); + vnf.addVnfc(vnfcE); + vnf.addVnfc(vnfcF); + vnf.addVnfc(vnfcG); + + return new InventoryModel(vnf); + } + + private VnfcDependencyModel readComplexDependencyModel() { + Vnfc a = new Vnfc("A","Active-Active",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + + bNode.addParent(e); + cNode.addParent(e); + + dNode.addParent(b); + gNode.addParent(b); + + fNode.addParent(c); + + gNode.addParent(f); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + } + + private VnfcDependencyModel readCyclicDependencyModel() { + + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + + bNode.addParent(a); + + bNode.addParent(d); + dNode.addParent(c); + cNode.addParent(b); + + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + + return new VnfcDependencyModel(dependencies); + + } + + private InventoryModel readInventoryModel() { + Vnf vnf = new Vnf("vnf_1","vSCP","1"); + + Vnfc smp = new Vnfc("SMP",null,"SMP_Name"); + Vserver smpVm1 = new Vserver("SMP_URL1"); + Vserver smpVm2 = new Vserver("SMP_URL2"); + + smp.addVm(smpVm1); + smp.addVm(smpVm2); + + Vnfc be = new Vnfc("BE",null,"BE_Name"); + + Vserver beVm1 = new Vserver("BE_URL1"); + Vserver beVm2 = new Vserver("BE_URL2"); + Vserver beVm3 = new Vserver("BE_URL3"); + Vserver beVm4 = new Vserver("BE_URL4"); + Vserver beVm5 = new Vserver("BE_URL5"); + + be.addVm(beVm1); + be.addVm(beVm2); + be.addVm(beVm3); + be.addVm(beVm4); + be.addVm(beVm5); + + Vnfc fe = new Vnfc("FE",null,"FE_Name"); + + Vserver feVm1 = new Vserver("FE_URL1"); + Vserver feVm2 = new Vserver("FE_URL2"); + + fe.addVm(feVm1); + fe.addVm(feVm2); + + vnf.addVnfc(smp); + vnf.addVnfc(be); + vnf.addVnfc(fe); + + return new InventoryModel(vnf); + } + + private VnfcDependencyModel readDependencyModel() { + Vnfc smp = new Vnfc("SMP","Active-Passive",null); + Vnfc be = new Vnfc("BE","Active-Active",null); + Vnfc fe = new Vnfc("FE","Active-Active",null); + + + Node smpNode = new Node(smp); + Node beNode = new Node(be); + Node feNode = new Node(fe); + + beNode.addParent(smp); + feNode.addParent(be); + + Set> dependencies = new HashSet<>(); + dependencies.add(smpNode); + dependencies.add(feNode); + dependencies.add(beNode); + + return new VnfcDependencyModel(dependencies); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java deleted file mode 100644 index 009515378..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java +++ /dev/null @@ -1,332 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - - -public class TestFlowBuilder { - - @Test - public void testForwardFlowBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); - } - - @Test - public void testReverseFlowBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); - VnfcDependencyModel dependencyModel = readDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); - } - - @Test - public void testComplexFlowBuilderForward(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - InventoryModel inventoryModel = readComplexInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); - Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); - Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); - Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); - - } - - @Test - public void testComplexFlowBuilderReverse(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - InventoryModel inventoryModel = readComplexInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); - - Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); - Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); - Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); - - } - - @Test(expected = InvalidDependencyModel.class) - public void testCyclicBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - builder.buildFlowModel(dependencyModel,inventoryModel); - } - - @Test(expected = InvalidDependencyModel.class) - public void testCyclicBuilderWithRootNode(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readCyclicDependencyModelWithRootNode(); - InventoryModel inventoryModel = readInventoryModel(); - builder.buildFlowModel(dependencyModel,inventoryModel); - } - - private VnfcDependencyModel readCyclicDependencyModelWithRootNode() { - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - - bNode.addParent(c); - cNode.addParent(b); - - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - - return new VnfcDependencyModel(dependencies); - } - - private InventoryModel readComplexInventoryModel() { - Vnf vnf = new Vnf("vnf_1","vABCD","1"); - - Vnfc vnfcA = new Vnfc("A","Active-Active","A_Name"); - Vnfc vnfcB = new Vnfc("B","Active-Active","B_Name"); - Vnfc vnfcC = new Vnfc("C","Active-Active","C_Name"); - Vnfc vnfcD = new Vnfc("D","Active-Active","D_Name"); - Vnfc vnfcE = new Vnfc("E","Active-Active","E_Name"); - Vnfc vnfcF = new Vnfc("F","Active-Active","F_Name"); - Vnfc vnfcG = new Vnfc("G","Active-Active","G_Name"); - - vnfcA.addVm(new Vserver("VM_URL_A1")); - vnfcB.addVm(new Vserver("VM_URL_B1")); - vnfcC.addVm(new Vserver("VM_URL_C1")); - vnfcD.addVm(new Vserver("VM_URL_D1")); - vnfcE.addVm(new Vserver("VM_URL_E1")); - vnfcF.addVm(new Vserver("VM_URL_F1")); - vnfcG.addVm(new Vserver("VM_URL_G1")); - - vnf.addVnfc(vnfcA); - vnf.addVnfc(vnfcB); - vnf.addVnfc(vnfcC); - vnf.addVnfc(vnfcD); - vnf.addVnfc(vnfcE); - vnf.addVnfc(vnfcF); - vnf.addVnfc(vnfcG); - - return new InventoryModel(vnf); - } - - private VnfcDependencyModel readComplexDependencyModel() { - Vnfc a = new Vnfc("A","Active-Active",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - - bNode.addParent(e); - cNode.addParent(e); - - dNode.addParent(b); - gNode.addParent(b); - - fNode.addParent(c); - - gNode.addParent(f); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - } - - private VnfcDependencyModel readCyclicDependencyModel() { - - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - - bNode.addParent(a); - - bNode.addParent(d); - dNode.addParent(c); - cNode.addParent(b); - - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - - return new VnfcDependencyModel(dependencies); - - } - - private InventoryModel readInventoryModel() { - Vnf vnf = new Vnf("vnf_1","vSCP","1"); - - Vnfc smp = new Vnfc("SMP",null,"SMP_Name"); - Vserver smpVm1 = new Vserver("SMP_URL1"); - Vserver smpVm2 = new Vserver("SMP_URL2"); - - smp.addVm(smpVm1); - smp.addVm(smpVm2); - - Vnfc be = new Vnfc("BE",null,"BE_Name"); - - Vserver beVm1 = new Vserver("BE_URL1"); - Vserver beVm2 = new Vserver("BE_URL2"); - Vserver beVm3 = new Vserver("BE_URL3"); - Vserver beVm4 = new Vserver("BE_URL4"); - Vserver beVm5 = new Vserver("BE_URL5"); - - be.addVm(beVm1); - be.addVm(beVm2); - be.addVm(beVm3); - be.addVm(beVm4); - be.addVm(beVm5); - - Vnfc fe = new Vnfc("FE",null,"FE_Name"); - - Vserver feVm1 = new Vserver("FE_URL1"); - Vserver feVm2 = new Vserver("FE_URL2"); - - fe.addVm(feVm1); - fe.addVm(feVm2); - - vnf.addVnfc(smp); - vnf.addVnfc(be); - vnf.addVnfc(fe); - - return new InventoryModel(vnf); - } - - private VnfcDependencyModel readDependencyModel() { - Vnfc smp = new Vnfc("SMP","Active-Passive",null); - Vnfc be = new Vnfc("BE","Active-Active",null); - Vnfc fe = new Vnfc("FE","Active-Active",null); - - - Node smpNode = new Node(smp); - Node beNode = new Node(be); - Node feNode = new Node(fe); - - beNode.addParent(smp); - feNode.addParent(be); - - Set> dependencies = new HashSet<>(); - dependencies.add(smpNode); - dependencies.add(feNode); - dependencies.add(beNode); - - return new VnfcDependencyModel(dependencies); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java new file mode 100644 index 000000000..9f75779cd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + +import java.util.LinkedList; +import java.util.List; + +public class Vnf { + private String vnfId; + private String vnfType; + private String vnfVersion; + + private List vnfcs; + + public Vnf(String vnfId,String vnfType,String vnfVersion){ + this.vnfId = vnfId; + this.vnfType = vnfType; + this.vnfVersion = vnfVersion; + this.vnfcs = new LinkedList<>(); + } + + public String getVnfVersion() { + return vnfVersion; + } + + public String getVnfId() { + return vnfId; + } + + public String getVnfType() { + return vnfType; + } + + public void addVnfc(Vnfc vnfc){ + this.vnfcs.add(vnfc); + } + + public List getVnfcs() { + return vnfcs; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Vnf : vnfId = " + vnfId +" , vnfType = " + vnfType); + for(Vnfc vnfc:vnfcs){ + stringBuilder.append(vnfc.toString()).append(","); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java new file mode 100644 index 000000000..de075f085 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + +import java.util.LinkedList; +import java.util.List; + + +public class Vnfc { + + private String vnfcType; + + public void setResilienceType(String resilienceType) { + this.resilienceType = resilienceType; + } + + private String resilienceType; + private boolean mandatory; + private String vnfcName; + private List vserverList; + + public Vnfc(String vnfcType,String resilienceType){ + this(vnfcType,resilienceType,null, false); + } + + public Vnfc(String vnfcType,String resilienceType,String vnfcName){ + this(vnfcType,resilienceType,vnfcName, false); + } + + public Vnfc(String vnfcType,String resilienceType,String vnfcName, boolean mandatory){ + this.vnfcName = vnfcName; + this.vnfcType = vnfcType; + this.resilienceType = resilienceType; + this.mandatory = mandatory; + this.vserverList = new LinkedList<>(); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Vnfc : vnfcType = " + vnfcType + ", vnfcName = " +vnfcName + ", resilienceType = " + resilienceType+", mandatory = " + mandatory); + for(Vserver vserver:vserverList){ + stringBuilder.append(vserver.toString()).append(", \n"); + } + return stringBuilder.toString(); + } + + @Override + public int hashCode(){ + final int prime = 31; + int result = 1; + result = result * prime + (this.vnfcType == null ? 0 :this.vnfcType.hashCode()); + result = result * prime + (this.resilienceType == null ? 0 :this.resilienceType.hashCode()); + result = result * prime + (this.vnfcName == null ? 0 :this.vnfcName.hashCode()); + result = result * prime + (Boolean.valueOf(this.mandatory).hashCode()); + return result; + } + @Override + public boolean equals(Object object){ + if(object == null){ + return false; + } + if(!(object instanceof Vnfc)){ + return false; + } + Vnfc vnfc = (Vnfc)object; + + if(this.vnfcType == null){ + if(vnfc.vnfcType !=null) + return false; + } + else if(!this.vnfcType.equals(vnfc.vnfcType)) + return false; + + if(this.resilienceType == null){ + if(vnfc.resilienceType !=null) + return false; + } + else if(!this.resilienceType.equals(vnfc.resilienceType)) + return false; + + if(this.vnfcName == null){ + if(vnfc.vnfcName !=null) + return false; + } + else if(!this.vnfcName.equals(vnfc.vnfcName)) + return false; + if (this.mandatory != vnfc.mandatory) + return false; + return true; + } + + public void addVm(Vserver vserver){ + this.vserverList.add(vserver); + } + public void addVms(List vserverList){ + this.vserverList.addAll(vserverList); + } + + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + public String getVnfcType() { + return vnfcType; + } + + public String getResilienceType() { + return resilienceType; + } + + public String getVnfcName() { + return vnfcName; + } + + public List getVserverList() { + return vserverList; + } + + public boolean isMandatory() { + return mandatory; + } + + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java new file mode 100644 index 000000000..0840bd91e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + + +public class Vserver { + + private String url; + + private String tenantId; + private String id; + private String relatedLink; + private String name; + + public Vserver(String url){ + this(url,null,null,null,null); + } + + public Vserver(String url, + String tenantId, + String id, + String relatedLink, + String name){ + this.url = url; + this.tenantId =tenantId; + this.id = id; + this.relatedLink =relatedLink; + this.name = name; + + } + + public String getUrl() { + return url; + } + + @Override + public String toString() { + return "Vserver : url = " +url + ", tenantId = " +tenantId +", id = " +id + " ,relatedLink = " +relatedLink +" , name = "+name; + } + + public String getTenantId() { + return tenantId; + } + + public String getId() { + return id; + } + + public String getRelatedLink() { + return relatedLink; + } + + public String getName() { + return name; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java deleted file mode 100644 index 9f75779cd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - -import java.util.LinkedList; -import java.util.List; - -public class Vnf { - private String vnfId; - private String vnfType; - private String vnfVersion; - - private List vnfcs; - - public Vnf(String vnfId,String vnfType,String vnfVersion){ - this.vnfId = vnfId; - this.vnfType = vnfType; - this.vnfVersion = vnfVersion; - this.vnfcs = new LinkedList<>(); - } - - public String getVnfVersion() { - return vnfVersion; - } - - public String getVnfId() { - return vnfId; - } - - public String getVnfType() { - return vnfType; - } - - public void addVnfc(Vnfc vnfc){ - this.vnfcs.add(vnfc); - } - - public List getVnfcs() { - return vnfcs; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Vnf : vnfId = " + vnfId +" , vnfType = " + vnfType); - for(Vnfc vnfc:vnfcs){ - stringBuilder.append(vnfc.toString()).append(","); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java deleted file mode 100644 index de075f085..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - -import java.util.LinkedList; -import java.util.List; - - -public class Vnfc { - - private String vnfcType; - - public void setResilienceType(String resilienceType) { - this.resilienceType = resilienceType; - } - - private String resilienceType; - private boolean mandatory; - private String vnfcName; - private List vserverList; - - public Vnfc(String vnfcType,String resilienceType){ - this(vnfcType,resilienceType,null, false); - } - - public Vnfc(String vnfcType,String resilienceType,String vnfcName){ - this(vnfcType,resilienceType,vnfcName, false); - } - - public Vnfc(String vnfcType,String resilienceType,String vnfcName, boolean mandatory){ - this.vnfcName = vnfcName; - this.vnfcType = vnfcType; - this.resilienceType = resilienceType; - this.mandatory = mandatory; - this.vserverList = new LinkedList<>(); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Vnfc : vnfcType = " + vnfcType + ", vnfcName = " +vnfcName + ", resilienceType = " + resilienceType+", mandatory = " + mandatory); - for(Vserver vserver:vserverList){ - stringBuilder.append(vserver.toString()).append(", \n"); - } - return stringBuilder.toString(); - } - - @Override - public int hashCode(){ - final int prime = 31; - int result = 1; - result = result * prime + (this.vnfcType == null ? 0 :this.vnfcType.hashCode()); - result = result * prime + (this.resilienceType == null ? 0 :this.resilienceType.hashCode()); - result = result * prime + (this.vnfcName == null ? 0 :this.vnfcName.hashCode()); - result = result * prime + (Boolean.valueOf(this.mandatory).hashCode()); - return result; - } - @Override - public boolean equals(Object object){ - if(object == null){ - return false; - } - if(!(object instanceof Vnfc)){ - return false; - } - Vnfc vnfc = (Vnfc)object; - - if(this.vnfcType == null){ - if(vnfc.vnfcType !=null) - return false; - } - else if(!this.vnfcType.equals(vnfc.vnfcType)) - return false; - - if(this.resilienceType == null){ - if(vnfc.resilienceType !=null) - return false; - } - else if(!this.resilienceType.equals(vnfc.resilienceType)) - return false; - - if(this.vnfcName == null){ - if(vnfc.vnfcName !=null) - return false; - } - else if(!this.vnfcName.equals(vnfc.vnfcName)) - return false; - if (this.mandatory != vnfc.mandatory) - return false; - return true; - } - - public void addVm(Vserver vserver){ - this.vserverList.add(vserver); - } - public void addVms(List vserverList){ - this.vserverList.addAll(vserverList); - } - - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - public String getVnfcType() { - return vnfcType; - } - - public String getResilienceType() { - return resilienceType; - } - - public String getVnfcName() { - return vnfcName; - } - - public List getVserverList() { - return vserverList; - } - - public boolean isMandatory() { - return mandatory; - } - - public void setMandatory(boolean mandatory) { - this.mandatory = mandatory; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java deleted file mode 100644 index 0840bd91e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - - -public class Vserver { - - private String url; - - private String tenantId; - private String id; - private String relatedLink; - private String name; - - public Vserver(String url){ - this(url,null,null,null,null); - } - - public Vserver(String url, - String tenantId, - String id, - String relatedLink, - String name){ - this.url = url; - this.tenantId =tenantId; - this.id = id; - this.relatedLink =relatedLink; - this.name = name; - - } - - public String getUrl() { - return url; - } - - @Override - public String toString() { - return "Vserver : url = " +url + ", tenantId = " +tenantId +", id = " +id + " ,relatedLink = " +relatedLink +" , name = "+name; - } - - public String getTenantId() { - return tenantId; - } - - public String getId() { - return id; - } - - public String getRelatedLink() { - return relatedLink; - } - - public String getName() { - return name; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java new file mode 100644 index 000000000..cfe263ff9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.licmgr; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface LicenseManagerPlugin extends SvcLogicJavaPlugin { + /** + * Retrieves license model from APPC database and populate flags into svc context + * @param params map with parameters: + * org.onap.appc.vftype - the vnf type / service type; + * org.onap.appc.resource-version - the vnf version / service version + * @param ctx service logic context + * 1. supposed properties already in context: + * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI + * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI + * 2. properties and flags stored in context after bean execution: + * model.entitlement.pool.uuid - entitlement-group-uuid from license model + * model.license.key.uuid - license-key-uuid from license model + * is.acquire-entitlement.require + * is.release-entitlement.require + * is.acquire-license.require + * is.release-license.require + * + * @throws APPCException throws in case of any error + */ + void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java new file mode 100644 index 000000000..4a72c2358 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.licmgr.impl; + +import java.util.Map; + +import org.onap.appc.dg.licmgr.LicenseManagerPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.licmgr.Constants; +import org.onap.appc.licmgr.LicenseManager; +import org.onap.appc.licmgr.exception.DataAccessException; +import org.onap.appc.licmgr.objects.LicenseModel; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class LicenseManagerPluginImpl implements LicenseManagerPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + // populated by blueprint framework + private LicenseManager licenseManager; + + public void setLicenseManager(LicenseManager licenseManager) { + this.licenseManager = licenseManager; + } + + /** + * Retrieves license model from APPC database and populate flags into svc context + * @param params map with parameters: + * org.onap.appc.vftype - the vnf type / service type; + * org.onap.appc.resource-version - the vnf version / service version + * @param ctx service logic context + * 1. supposed properties already in context: + * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI + * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI + * 2. properties and flags stored in context after bean execution: + * model.entitlement.pool.uuid - entitlement-group-uuid from license model + * model.license.key.uuid - license-key-uuid from license model + * is.acquire-entitlement.require + * is.release-entitlement.require + * is.acquire-license.require + * is.release-license.require + * is.aai-entitlement-update.require + * is.aai-license-update.require + * + * @throws APPCException throws in case of any error + */ + @Override + public void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException { + + try { + + LicenseModel licenseModel = licenseManager.retrieveLicenseModel(params.get(Constants.VNF_TYPE_FIELD_NAME), params.get(Constants.VNF_RESOURCE_VERSION_FIELD_NAME)); + + String modelEntitlementPoolUuid = licenseModel.getEntitlementPoolUuid(); if (null == modelEntitlementPoolUuid) modelEntitlementPoolUuid = ""; + String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; + boolean isAcquireEntitlementRequire = !modelEntitlementPoolUuid.isEmpty() && !modelEntitlementPoolUuid.equals(aaiEntitlementPoolUuid); + boolean isReleaseEntitlementRequire = !aaiEntitlementPoolUuid.isEmpty() && (isAcquireEntitlementRequire || modelEntitlementPoolUuid.isEmpty()); + boolean isAAIEntitlementUpdateRequire = isAcquireEntitlementRequire || isReleaseEntitlementRequire; + ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, modelEntitlementPoolUuid); + ctx.setAttribute(Constants.IS_ACQUIRE_ENTITLEMENT_REQUIRE, Boolean.toString(isAcquireEntitlementRequire)); + ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(isReleaseEntitlementRequire)); + ctx.setAttribute(Constants.IS_AAI_ENTITLEMENT_UPDATE_REQUIRE, Boolean.toString(isAAIEntitlementUpdateRequire)); + + + String modelLicenseKeyGroupUuid = licenseModel.getLicenseKeyGroupUuid(); if (null == modelLicenseKeyGroupUuid) modelLicenseKeyGroupUuid = ""; + String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; + String aaiLicenseKeyValue = ctx.getAttribute(Constants.AAI_LICENSE_KEY_VALUE); if (null == aaiLicenseKeyValue) aaiLicenseKeyValue = ""; + boolean isAcquireLicenseRequire = !modelLicenseKeyGroupUuid.isEmpty() && !modelLicenseKeyGroupUuid.equals(aaiLicenseKeyGroupUuid); + boolean isReleaseLicenseRequire = !aaiLicenseKeyGroupUuid.isEmpty() && (isAcquireLicenseRequire || modelLicenseKeyGroupUuid.isEmpty()); + boolean isAAILicenseUpdateRequire = isAcquireLicenseRequire || isReleaseLicenseRequire; + ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, modelLicenseKeyGroupUuid); + ctx.setAttribute(Constants.IS_ACQUIRE_LICENSE_REQUIRE, Boolean.toString(isAcquireLicenseRequire)); + ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(isReleaseLicenseRequire)); + ctx.setAttribute(Constants.IS_AAI_LICENSE_UPDATE_REQUIRE, Boolean.toString(isAAILicenseUpdateRequire)); + + ctx.setAttribute("license-key", aaiLicenseKeyValue); + + } catch (DataAccessException le) { + logger.error("Error " + le.getMessage()); + ctx.setAttribute("output.status.message", le.getMessage()); + throw new APPCException(le); + } + + } + + + + //////// code uses jaxb license model, should be fixed + /* + final VfLicenseModel.FeatureGroupList featureGroupList = licenseModel.getFeatureGroupList(); + if (null != featureGroupList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup featureGroup = featureGroupList.getFeatureGroup(); + if (null != featureGroup) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList + entitlementPoolList = featureGroup.getEntitlementPoolList(); + if (null != entitlementPoolList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList.EntitlementPool + entitlementPool = entitlementPoolList.getEntitlementPool(); + if (null != entitlementPool) { + final String entitlementPoolUuid = entitlementPool.getEntitlementPoolUuid(); + // add entitlementPoolUuid into context + ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, entitlementPoolUuid); + } + } + + final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList + licenseKeyGroupList = featureGroup.getLicenseKeyGroupList(); + if (null != licenseKeyGroupList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList.LicenseKeyGroup + licenseKeyGroup = licenseKeyGroupList.getLicenseKeyGroup(); + if (null != licenseKeyGroup) { + final String licenseKeyGroupUuid = licenseKeyGroup.getLicenseKeyGroupUuid(); + // add licenseKeyGroupUuid into context + ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, licenseKeyGroupUuid); + } + } + } + } + */ + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java deleted file mode 100644 index cfe263ff9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.licmgr; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface LicenseManagerPlugin extends SvcLogicJavaPlugin { - /** - * Retrieves license model from APPC database and populate flags into svc context - * @param params map with parameters: - * org.onap.appc.vftype - the vnf type / service type; - * org.onap.appc.resource-version - the vnf version / service version - * @param ctx service logic context - * 1. supposed properties already in context: - * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI - * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI - * 2. properties and flags stored in context after bean execution: - * model.entitlement.pool.uuid - entitlement-group-uuid from license model - * model.license.key.uuid - license-key-uuid from license model - * is.acquire-entitlement.require - * is.release-entitlement.require - * is.acquire-license.require - * is.release-license.require - * - * @throws APPCException throws in case of any error - */ - void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java deleted file mode 100644 index 4a72c2358..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.licmgr.impl; - -import java.util.Map; - -import org.onap.appc.dg.licmgr.LicenseManagerPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.licmgr.Constants; -import org.onap.appc.licmgr.LicenseManager; -import org.onap.appc.licmgr.exception.DataAccessException; -import org.onap.appc.licmgr.objects.LicenseModel; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class LicenseManagerPluginImpl implements LicenseManagerPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - // populated by blueprint framework - private LicenseManager licenseManager; - - public void setLicenseManager(LicenseManager licenseManager) { - this.licenseManager = licenseManager; - } - - /** - * Retrieves license model from APPC database and populate flags into svc context - * @param params map with parameters: - * org.onap.appc.vftype - the vnf type / service type; - * org.onap.appc.resource-version - the vnf version / service version - * @param ctx service logic context - * 1. supposed properties already in context: - * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI - * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI - * 2. properties and flags stored in context after bean execution: - * model.entitlement.pool.uuid - entitlement-group-uuid from license model - * model.license.key.uuid - license-key-uuid from license model - * is.acquire-entitlement.require - * is.release-entitlement.require - * is.acquire-license.require - * is.release-license.require - * is.aai-entitlement-update.require - * is.aai-license-update.require - * - * @throws APPCException throws in case of any error - */ - @Override - public void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException { - - try { - - LicenseModel licenseModel = licenseManager.retrieveLicenseModel(params.get(Constants.VNF_TYPE_FIELD_NAME), params.get(Constants.VNF_RESOURCE_VERSION_FIELD_NAME)); - - String modelEntitlementPoolUuid = licenseModel.getEntitlementPoolUuid(); if (null == modelEntitlementPoolUuid) modelEntitlementPoolUuid = ""; - String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; - boolean isAcquireEntitlementRequire = !modelEntitlementPoolUuid.isEmpty() && !modelEntitlementPoolUuid.equals(aaiEntitlementPoolUuid); - boolean isReleaseEntitlementRequire = !aaiEntitlementPoolUuid.isEmpty() && (isAcquireEntitlementRequire || modelEntitlementPoolUuid.isEmpty()); - boolean isAAIEntitlementUpdateRequire = isAcquireEntitlementRequire || isReleaseEntitlementRequire; - ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, modelEntitlementPoolUuid); - ctx.setAttribute(Constants.IS_ACQUIRE_ENTITLEMENT_REQUIRE, Boolean.toString(isAcquireEntitlementRequire)); - ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(isReleaseEntitlementRequire)); - ctx.setAttribute(Constants.IS_AAI_ENTITLEMENT_UPDATE_REQUIRE, Boolean.toString(isAAIEntitlementUpdateRequire)); - - - String modelLicenseKeyGroupUuid = licenseModel.getLicenseKeyGroupUuid(); if (null == modelLicenseKeyGroupUuid) modelLicenseKeyGroupUuid = ""; - String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; - String aaiLicenseKeyValue = ctx.getAttribute(Constants.AAI_LICENSE_KEY_VALUE); if (null == aaiLicenseKeyValue) aaiLicenseKeyValue = ""; - boolean isAcquireLicenseRequire = !modelLicenseKeyGroupUuid.isEmpty() && !modelLicenseKeyGroupUuid.equals(aaiLicenseKeyGroupUuid); - boolean isReleaseLicenseRequire = !aaiLicenseKeyGroupUuid.isEmpty() && (isAcquireLicenseRequire || modelLicenseKeyGroupUuid.isEmpty()); - boolean isAAILicenseUpdateRequire = isAcquireLicenseRequire || isReleaseLicenseRequire; - ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, modelLicenseKeyGroupUuid); - ctx.setAttribute(Constants.IS_ACQUIRE_LICENSE_REQUIRE, Boolean.toString(isAcquireLicenseRequire)); - ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(isReleaseLicenseRequire)); - ctx.setAttribute(Constants.IS_AAI_LICENSE_UPDATE_REQUIRE, Boolean.toString(isAAILicenseUpdateRequire)); - - ctx.setAttribute("license-key", aaiLicenseKeyValue); - - } catch (DataAccessException le) { - logger.error("Error " + le.getMessage()); - ctx.setAttribute("output.status.message", le.getMessage()); - throw new APPCException(le); - } - - } - - - - //////// code uses jaxb license model, should be fixed - /* - final VfLicenseModel.FeatureGroupList featureGroupList = licenseModel.getFeatureGroupList(); - if (null != featureGroupList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup featureGroup = featureGroupList.getFeatureGroup(); - if (null != featureGroup) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList - entitlementPoolList = featureGroup.getEntitlementPoolList(); - if (null != entitlementPoolList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList.EntitlementPool - entitlementPool = entitlementPoolList.getEntitlementPool(); - if (null != entitlementPool) { - final String entitlementPoolUuid = entitlementPool.getEntitlementPoolUuid(); - // add entitlementPoolUuid into context - ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, entitlementPoolUuid); - } - } - - final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList - licenseKeyGroupList = featureGroup.getLicenseKeyGroupList(); - if (null != licenseKeyGroupList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList.LicenseKeyGroup - licenseKeyGroup = licenseKeyGroupList.getLicenseKeyGroup(); - if (null != licenseKeyGroup) { - final String licenseKeyGroupUuid = licenseKeyGroup.getLicenseKeyGroupUuid(); - // add licenseKeyGroupUuid into context - ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, licenseKeyGroupUuid); - } - } - } - } - */ - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java new file mode 100644 index 000000000..eba364a10 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal; + +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.objects.BundleInfo; + +import java.util.Date; + +/** + * Provides APIs for interacting with MD-SAL store + */ +public interface MDSALStore { + + /** + * Checks the presence of any yang module in the MD-SAL store, + * Due to limitation of SchemaContext interface of ODL that it does not + * contain the information about dynamically loaded yang modules, it + * checks the presence of OSGI bundle + * @param moduleName Name of the Module + * @param revision revision of the Module + * @return returns true- module is present, false - module is absent + */ + boolean isModulePresent(String moduleName, Date revision); + + /** + * This method will be used to store yang module to MD-SAL store + * @param yang - yang module that need to be stored. In String format + * @param bundleInfo - Bundle Information that contains name , description, version , location. These parameters used to create bundle which will push yang to MD-SAL store. + * @throws MDSALStoreException + */ + void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException; + + /** + * This method is used to store configuration JSON to MD-SAL store. It invokes store configuration Operation with required parameters + * @param moduleName - Yang module name where JSON need to be posted + * @param requestId - Request ID which is used as unique key for configuration JSON + * @param configJSON - String value of configuration JSON that needs to be stored in MD-SAl store + * @throws MDSALStoreException + */ + void storeJson(String moduleName , String requestId , String configJSON ) throws MDSALStoreException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java new file mode 100644 index 000000000..2bb30b1c2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.exception; + +/** + * This is custom exception type defined for MD-SAL store. All exceptions thrown by mdsal store module need to be wrapped in this class. +*/ + public class MDSALStoreException extends Exception { + + private static final long serialVersionUID = 1L; + + public MDSALStoreException(){ + } + + /** + * Create MDSALStoreException using only message. + * @param message -- message to the caller. + */ + public MDSALStoreException (String message){ + super(message); + } + + /** + * Create MDSALStoreException using orignal cause + * @param cause - cause that is being wrapped / suppressed. + */ + public MDSALStoreException (Throwable cause){ + super(cause); + } + + /** + * + * @param message - message to the caller. + * @param cause - cause that is being wrapped / suppressed . + */ + public MDSALStoreException(String message , Throwable cause){ + super(message , cause); + } + + /** + * + * @param message - message to the caller. + * @param cause - cause that is being wrapped / suppressed . + * @param enableSuppression - Indicates if suppression is enabled. + * @param writableStackTrace - Indicates if writable stacktrace is supported + */ + public MDSALStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java new file mode 100644 index 000000000..bb847477f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; +/** + * This class contains the definitions of all constant values used in the appc-dg-mdsal-store + * These properties are used for creating osgi bundle zip file. It also defines contents for Blueprint.xml file of bundle + */ +public class Constants { + + private Constants(){} + /** + * Manifest attribute for OSGI Bundle Name + */ + public static final String MANIFEST_ATTR_BUNDLE_NAME= "Bundle-Name"; + + /** + * Manifest attribute for OSGI Bundle Symbolic Name + */ + public static final String MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME= "Bundle-SymbolicName"; + + /** + * Manifest attribute for OSGI Bundle Description + */ + public static final String MANIFEST_ATTR_BUNDLE_DESCRIPTION= "Bundle-Description"; + + /** + * Manifest attribute for OSGI Bundle Manifest version + */ + public static final String MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION= "Bundle-ManifestVersion"; + + /** + * Manifest attribute for OSGI Bundle Version + */ + public static final String MANIFEST_ATTR_BUNDLE_VERSION= "Bundle-Version"; + + /** + * Manifest attribute for OSGI Bundle Blueprint + */ + public static final String MANIFEST_ATTR_BUNDLE_BLUEPRINT= "Bundle-Blueprint"; + + /** + * Manifest value for Mainfest Version + */ + public static final String MANIFEST_VALUE_VERSION= "1.0"; + + /** + * Manifest value for OSGI Bundle Vesion + */ + public static final String MANIFEST_VALUE_BUNDLE_MAN_VERSION= "2"; + + /** + * Manifest value for OSGI Bundle Blueprint location + */ + public static final String MANIFEST_VALUE_BUNDLE_BLUEPRINT= "OSGI-INF/blueprint/blueprint.xml"; + + /** + * Base URL for config actions exposed by RESTCONF API + */ + + public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config"; + + public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url"; + + public static final String CONFIG_PATH = "/restconf/config"; + + /** + * Restconf authentication user property name + */ + public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user"; + + /** + * Restconf authentication password property name + */ + public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass"; + + /** + * Content for blueprint.xml used while creation of OSGI bundle. + */ + public static final String BLUEPRINT = "\n" + + "\n" + + "\n" + + "\n" + + ""; + + /** + * HTTP Header attribute for Content type - JSON + */ + public static final String OPERATION_APPLICATION_JSON= " application/json"; + + /** + * HTTP protocol used for config operations + */ + public static final String OPERATION_HTTPS= "https"; + + /** + * Constant for backslash to be used while formatting URL + */ + public static final String URL_BACKSLASH ="/"; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java new file mode 100644 index 000000000..bc951d926 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; + +import org.onap.appc.mdsal.MDSALStore; + +/* + * Factory class to create/get instance of MDSALStore + */ +public class MDSALStoreFactory { + private static class ReferenceHolder{ + private static MDSALStore store = new MDSALStoreImpl(); + private ReferenceHolder(){} + } + private MDSALStoreFactory(){ + + } + + /** + * Method for creating MDSALStore instance, It creates an instance of + * MDSALStoreImpl once and returns the same instance everytime it is invoked. + * @return + */ + public static MDSALStore createMDSALStore (){ + return ReferenceHolder.store; + } +} + diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java new file mode 100644 index 000000000..c9e083557 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.objects.BundleInfo; +import org.onap.appc.mdsal.operation.ConfigOperation; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Date; +import java.util.Properties; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +/** + * Implementation of MDSALStore + */ +public class MDSALStoreImpl implements MDSALStore{ + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class); + + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + MDSALStoreImpl(){ + String configUrl = null; + String user =null; + String password = null; + Properties properties = configuration.getProperties(); + if (properties != null) { + configUrl= properties.getProperty( Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT); + user = properties.getProperty(Constants.CONFIG_USER_PROPERTY); + password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY); + } + ConfigOperation.setUrl(configUrl); + ConfigOperation.setAuthentication(user,password); + } + + + @Override + public boolean isModulePresent(String moduleName, Date revision) { + + if(logger.isDebugEnabled()){ + logger.debug("isModulePresent invoked with moduleName = " +moduleName + " , revision = " +revision); + } + + BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + /** + * SchemaContext interface of ODL provides APIs for querying details of yang modules + * loaded into MD-SAL store, but its limitation is, it only returns information about + * static yang modules loaded on server start up, it does not return information about + * the yang modules loaded dynamically. Due to this limitation, we are checking the + * presence of OSGI bundle instead of yang module. (Note: Assuming OSGI bundle is named + * with the yang module name). + */ + + Bundle bundle = bundleContext.getBundle(moduleName); + if(logger.isDebugEnabled()){ + logger.debug("isModulePresent returned = " + (bundle != null)); + } + return bundle != null; + } + + @Override + public void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException { + + BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + byte[] byteArray = createBundleJar(yang, Constants.BLUEPRINT, bundleInfo); + + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray)){ + Bundle bundle = bundleContext.installBundle(bundleInfo.getLocation(), inputStream); + bundle.start(); + } catch (Exception e) { + logger.error("Error storing yang module: " + yang + ". Error message: " + e.getMessage()); + throw new MDSALStoreException("Error storing yang module: " + yang + " " + e.getMessage(), e); + } + } + + @Override + public void storeJson( String module , String requestId ,String configJSON) throws MDSALStoreException { + + try { + ConfigOperation.storeConfig(configJSON , module , org.onap.appc.Constants.YANG_BASE_CONTAINER, org.onap.appc.Constants.YANG_VNF_CONFIG_LIST,requestId,org.onap.appc.Constants.YANG_VNF_CONFIG); + } catch (APPCException e) { + throw new MDSALStoreException("Exception while storing config json to MDSAL store." +e.getMessage(), e); + } + } + + private byte[] createBundleJar(String yang, String blueprint, BundleInfo bundleInfo) throws MDSALStoreException { + + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, Constants.MANIFEST_VALUE_VERSION); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME), bundleInfo.getName()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME), bundleInfo.getName()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION), bundleInfo.getDescription()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION), Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION), String.valueOf(bundleInfo.getVersion())); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT), Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT); + + byte[] retunValue; + + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) { + jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/")); + jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/"+bundleInfo.getName()+".yang")); + jarOutputStream.write(yang.getBytes()); + jarOutputStream.closeEntry(); + + jarOutputStream.putNextEntry(new JarEntry("OSGI-INF/blueprint/")); + jarOutputStream.putNextEntry(new JarEntry(Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT)); + jarOutputStream.write(blueprint.getBytes()); + jarOutputStream.closeEntry(); + jarOutputStream.close(); + retunValue = outputStream.toByteArray(); + } catch (Exception e) { + logger.error("Error creating bundle jar: " + bundleInfo.getName() + ". Error message: " + e.getMessage()); + throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(), e); + } + return retunValue; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java new file mode 100644 index 000000000..b6d65447d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.objects; +/** + * Holds bundle information which includes name , description , version and location. This information will be used to create osgi bundle. + */ + public class BundleInfo { + + private String name; + private String description; + private Integer version; + private String location; + + /** + * Creates an object of BundleInfo with version initialized to 1 + */ + public BundleInfo(){ + version =1; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java new file mode 100644 index 000000000..1dcf1c6b0 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.impl.Constants; +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 org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.io.IOUtils; + +/** + * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. + */ +public class ConfigOperation { + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); + + private static URL url; + private static String basicAuth; + + ConfigOperation(){} + + private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input + * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store + * @param module - Module name that contains yang Schema + * @param containerName - yang container name which will be used as base container. + * @param subModules - Sub modules list if any. Order of sub module is top to bottom. + * @throws APPCException + */ + public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { + if (configJson == null) { + throw new APPCException("Provided message was null"); + } + LOG.debug("Config JSON: " + configJson +"\n" + +"module" + module +"\n" + +"containerName" + containerName +"\n" + +"subModules length : " + subModules.length ); + + int httpCode; + String respBody ; + try { + String path = requestFormatter.buildPath(module, containerName, subModules); + LOG.debug("Configuration Path : " + path); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + HttpResponse response = doPut(serviceUrl , configJson); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + LOG.error("Error while storing configuration json "+e.getMessage(), e); + throw new APPCException(e); + } + + if (httpCode < 200 || httpCode >= 300 ) { + try { + LOG.debug("Config operation Error response code: " + httpCode); + ArrayList errorMessage = new ArrayList<>(); + JsonNode responseJson = toJsonNodeFromJsonString(respBody); + if(responseJson!=null && responseJson.get("errors")!=null) { + JsonNode errors = responseJson.get("errors").get("error"); + for (Iterator i = errors.elements();i.hasNext();){ + JsonNode error = i.next(); + errorMessage.add(error.get("error-message").textValue()); + } + } + throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); + } catch (Exception e) { + LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); + throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); + } + }else{ + LOG.debug("Config operation successful. Response code: " + httpCode); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param url - Destination URL for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException + */ + public static HttpResponse doPut (URL url, String body) throws APPCException { + HttpPut put; + try { + put = new HttpPut(url.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(Constants.OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + LOG.error("Malformed URL " +newUrl + e.getMessage(), e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basicAuth = null; + } + return basicAuth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client." , e); + client = new DefaultHttpClient(); + } + } else if ("http".equals(url.getProtocol())) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + private static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge new file mode 100644 index 000000000..36f471853 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.impl.Constants; +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 org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.io.IOUtils; + +/** + * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. +*/ +public class ConfigOperation { + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); + + private static URL url; + private static String basicAuth; + + ConfigOperation(){} + + private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input + * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store + * @param module - Module name that contains yang Schema + * @param containerName - yang container name which will be used as base container. + * @param subModules - Sub modules list if any. Order of sub module is top to bottom. + * @throws APPCException + */ + public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { + if (configJson == null) { + throw new APPCException("Provided message was null"); + } + LOG.debug("Config JSON: " + configJson +"\n" + +"module" + module +"\n" + +"containerName" + containerName +"\n" + +"subModules length : " + subModules.length ); + + int httpCode; + String respBody ; + try { + String path = requestFormatter.buildPath(url, module, containerName, subModules); + LOG.debug("Configuration Path : " + path); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + HttpResponse response = doPut(serviceUrl , configJson); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + LOG.error("Error while storing configuration json "+e.getMessage(), e); + throw new APPCException(e); + } + + if (httpCode < 200 || httpCode >= 300 ) { + try { + LOG.debug("Config operation Error response code: " + httpCode); + ArrayList errorMessage = new ArrayList<>(); + JsonNode responseJson = toJsonNodeFromJsonString(respBody); + if(responseJson!=null && responseJson.get("errors")!=null) { + JsonNode errors = responseJson.get("errors").get("error"); + for (Iterator i = errors.elements();i.hasNext();){ + JsonNode error = i.next(); + errorMessage.add(error.get("error-message").textValue()); + } + } + throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); + } catch (Exception e) { + LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); + throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); + } + }else{ + LOG.debug("Config operation successful. Response code: " + httpCode); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param url - Destination URL for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException + */ + public static HttpResponse doPut (URL url, String body) throws APPCException { + HttpPut put; + try { + put = new HttpPut(url.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(Constants.OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + LOG.error("Malformed URL " +newUrl + e.getMessage(), e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basicAuth = null; + } + return basicAuth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client." , e); + client = new DefaultHttpClient(); + } + } else if ("http".equals(url.getProtocol())) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + private static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java new file mode 100644 index 000000000..b2ada2ecc --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.mdsal.impl.Constants; + +import java.net.URL; +/** + * Creates request url path for config actions based on parameter like module name , container-name and sub modules if any. + */ + +public class ConfigOperationRequestFormatter { + /** + * Build a request url path for config actions + * @param module - yang module name + * @param containerName - yang container name + * @param subModules - sub module /container names as string in varargs ( String ) format + * @return - resultant path in String format + */ + public String buildPath(String module, String containerName , String... subModules ) { + + StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); + if(subModules.length >0){ + for(String subModule : subModules){ + path.append(subModule); + path.append("/"); + } + } + return path.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java deleted file mode 100644 index eba364a10..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal; - -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.objects.BundleInfo; - -import java.util.Date; - -/** - * Provides APIs for interacting with MD-SAL store - */ -public interface MDSALStore { - - /** - * Checks the presence of any yang module in the MD-SAL store, - * Due to limitation of SchemaContext interface of ODL that it does not - * contain the information about dynamically loaded yang modules, it - * checks the presence of OSGI bundle - * @param moduleName Name of the Module - * @param revision revision of the Module - * @return returns true- module is present, false - module is absent - */ - boolean isModulePresent(String moduleName, Date revision); - - /** - * This method will be used to store yang module to MD-SAL store - * @param yang - yang module that need to be stored. In String format - * @param bundleInfo - Bundle Information that contains name , description, version , location. These parameters used to create bundle which will push yang to MD-SAL store. - * @throws MDSALStoreException - */ - void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException; - - /** - * This method is used to store configuration JSON to MD-SAL store. It invokes store configuration Operation with required parameters - * @param moduleName - Yang module name where JSON need to be posted - * @param requestId - Request ID which is used as unique key for configuration JSON - * @param configJSON - String value of configuration JSON that needs to be stored in MD-SAl store - * @throws MDSALStoreException - */ - void storeJson(String moduleName , String requestId , String configJSON ) throws MDSALStoreException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java deleted file mode 100644 index 2bb30b1c2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.exception; - -/** - * This is custom exception type defined for MD-SAL store. All exceptions thrown by mdsal store module need to be wrapped in this class. -*/ - public class MDSALStoreException extends Exception { - - private static final long serialVersionUID = 1L; - - public MDSALStoreException(){ - } - - /** - * Create MDSALStoreException using only message. - * @param message -- message to the caller. - */ - public MDSALStoreException (String message){ - super(message); - } - - /** - * Create MDSALStoreException using orignal cause - * @param cause - cause that is being wrapped / suppressed. - */ - public MDSALStoreException (Throwable cause){ - super(cause); - } - - /** - * - * @param message - message to the caller. - * @param cause - cause that is being wrapped / suppressed . - */ - public MDSALStoreException(String message , Throwable cause){ - super(message , cause); - } - - /** - * - * @param message - message to the caller. - * @param cause - cause that is being wrapped / suppressed . - * @param enableSuppression - Indicates if suppression is enabled. - * @param writableStackTrace - Indicates if writable stacktrace is supported - */ - public MDSALStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java deleted file mode 100644 index bb847477f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; -/** - * This class contains the definitions of all constant values used in the appc-dg-mdsal-store - * These properties are used for creating osgi bundle zip file. It also defines contents for Blueprint.xml file of bundle - */ -public class Constants { - - private Constants(){} - /** - * Manifest attribute for OSGI Bundle Name - */ - public static final String MANIFEST_ATTR_BUNDLE_NAME= "Bundle-Name"; - - /** - * Manifest attribute for OSGI Bundle Symbolic Name - */ - public static final String MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME= "Bundle-SymbolicName"; - - /** - * Manifest attribute for OSGI Bundle Description - */ - public static final String MANIFEST_ATTR_BUNDLE_DESCRIPTION= "Bundle-Description"; - - /** - * Manifest attribute for OSGI Bundle Manifest version - */ - public static final String MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION= "Bundle-ManifestVersion"; - - /** - * Manifest attribute for OSGI Bundle Version - */ - public static final String MANIFEST_ATTR_BUNDLE_VERSION= "Bundle-Version"; - - /** - * Manifest attribute for OSGI Bundle Blueprint - */ - public static final String MANIFEST_ATTR_BUNDLE_BLUEPRINT= "Bundle-Blueprint"; - - /** - * Manifest value for Mainfest Version - */ - public static final String MANIFEST_VALUE_VERSION= "1.0"; - - /** - * Manifest value for OSGI Bundle Vesion - */ - public static final String MANIFEST_VALUE_BUNDLE_MAN_VERSION= "2"; - - /** - * Manifest value for OSGI Bundle Blueprint location - */ - public static final String MANIFEST_VALUE_BUNDLE_BLUEPRINT= "OSGI-INF/blueprint/blueprint.xml"; - - /** - * Base URL for config actions exposed by RESTCONF API - */ - - public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config"; - - public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url"; - - public static final String CONFIG_PATH = "/restconf/config"; - - /** - * Restconf authentication user property name - */ - public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user"; - - /** - * Restconf authentication password property name - */ - public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass"; - - /** - * Content for blueprint.xml used while creation of OSGI bundle. - */ - public static final String BLUEPRINT = "\n" + - "\n" + - "\n" + - "\n" + - ""; - - /** - * HTTP Header attribute for Content type - JSON - */ - public static final String OPERATION_APPLICATION_JSON= " application/json"; - - /** - * HTTP protocol used for config operations - */ - public static final String OPERATION_HTTPS= "https"; - - /** - * Constant for backslash to be used while formatting URL - */ - public static final String URL_BACKSLASH ="/"; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java deleted file mode 100644 index bc951d926..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; - -import org.onap.appc.mdsal.MDSALStore; - -/* - * Factory class to create/get instance of MDSALStore - */ -public class MDSALStoreFactory { - private static class ReferenceHolder{ - private static MDSALStore store = new MDSALStoreImpl(); - private ReferenceHolder(){} - } - private MDSALStoreFactory(){ - - } - - /** - * Method for creating MDSALStore instance, It creates an instance of - * MDSALStoreImpl once and returns the same instance everytime it is invoked. - * @return - */ - public static MDSALStore createMDSALStore (){ - return ReferenceHolder.store; - } -} - diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java deleted file mode 100644 index c9e083557..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.objects.BundleInfo; -import org.onap.appc.mdsal.operation.ConfigOperation; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.Date; -import java.util.Properties; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; - -/** - * Implementation of MDSALStore - */ -public class MDSALStoreImpl implements MDSALStore{ - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class); - - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - MDSALStoreImpl(){ - String configUrl = null; - String user =null; - String password = null; - Properties properties = configuration.getProperties(); - if (properties != null) { - configUrl= properties.getProperty( Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT); - user = properties.getProperty(Constants.CONFIG_USER_PROPERTY); - password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY); - } - ConfigOperation.setUrl(configUrl); - ConfigOperation.setAuthentication(user,password); - } - - - @Override - public boolean isModulePresent(String moduleName, Date revision) { - - if(logger.isDebugEnabled()){ - logger.debug("isModulePresent invoked with moduleName = " +moduleName + " , revision = " +revision); - } - - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - /** - * SchemaContext interface of ODL provides APIs for querying details of yang modules - * loaded into MD-SAL store, but its limitation is, it only returns information about - * static yang modules loaded on server start up, it does not return information about - * the yang modules loaded dynamically. Due to this limitation, we are checking the - * presence of OSGI bundle instead of yang module. (Note: Assuming OSGI bundle is named - * with the yang module name). - */ - - Bundle bundle = bundleContext.getBundle(moduleName); - if(logger.isDebugEnabled()){ - logger.debug("isModulePresent returned = " + (bundle != null)); - } - return bundle != null; - } - - @Override - public void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException { - - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - byte[] byteArray = createBundleJar(yang, Constants.BLUEPRINT, bundleInfo); - - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray)){ - Bundle bundle = bundleContext.installBundle(bundleInfo.getLocation(), inputStream); - bundle.start(); - } catch (Exception e) { - logger.error("Error storing yang module: " + yang + ". Error message: " + e.getMessage()); - throw new MDSALStoreException("Error storing yang module: " + yang + " " + e.getMessage(), e); - } - } - - @Override - public void storeJson( String module , String requestId ,String configJSON) throws MDSALStoreException { - - try { - ConfigOperation.storeConfig(configJSON , module , org.onap.appc.Constants.YANG_BASE_CONTAINER, org.onap.appc.Constants.YANG_VNF_CONFIG_LIST,requestId,org.onap.appc.Constants.YANG_VNF_CONFIG); - } catch (APPCException e) { - throw new MDSALStoreException("Exception while storing config json to MDSAL store." +e.getMessage(), e); - } - } - - private byte[] createBundleJar(String yang, String blueprint, BundleInfo bundleInfo) throws MDSALStoreException { - - Manifest manifest = new Manifest(); - manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, Constants.MANIFEST_VALUE_VERSION); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME), bundleInfo.getName()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME), bundleInfo.getName()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION), bundleInfo.getDescription()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION), Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION), String.valueOf(bundleInfo.getVersion())); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT), Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT); - - byte[] retunValue; - - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) { - jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/")); - jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/"+bundleInfo.getName()+".yang")); - jarOutputStream.write(yang.getBytes()); - jarOutputStream.closeEntry(); - - jarOutputStream.putNextEntry(new JarEntry("OSGI-INF/blueprint/")); - jarOutputStream.putNextEntry(new JarEntry(Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT)); - jarOutputStream.write(blueprint.getBytes()); - jarOutputStream.closeEntry(); - jarOutputStream.close(); - retunValue = outputStream.toByteArray(); - } catch (Exception e) { - logger.error("Error creating bundle jar: " + bundleInfo.getName() + ". Error message: " + e.getMessage()); - throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(), e); - } - return retunValue; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java deleted file mode 100644 index b6d65447d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.objects; -/** - * Holds bundle information which includes name , description , version and location. This information will be used to create osgi bundle. - */ - public class BundleInfo { - - private String name; - private String description; - private Integer version; - private String location; - - /** - * Creates an object of BundleInfo with version initialized to 1 - */ - public BundleInfo(){ - version =1; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Integer getVersion() { - return version; - } - - public void setVersion(Integer version) { - this.version = version; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java deleted file mode 100644 index 1dcf1c6b0..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java +++ /dev/null @@ -1,295 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.impl.Constants; -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 org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.security.*; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.commons.io.IOUtils; - -/** - * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. - */ -public class ConfigOperation { - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); - - private static URL url; - private static String basicAuth; - - ConfigOperation(){} - - private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input - * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store - * @param module - Module name that contains yang Schema - * @param containerName - yang container name which will be used as base container. - * @param subModules - Sub modules list if any. Order of sub module is top to bottom. - * @throws APPCException - */ - public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { - if (configJson == null) { - throw new APPCException("Provided message was null"); - } - LOG.debug("Config JSON: " + configJson +"\n" - +"module" + module +"\n" - +"containerName" + containerName +"\n" - +"subModules length : " + subModules.length ); - - int httpCode; - String respBody ; - try { - String path = requestFormatter.buildPath(module, containerName, subModules); - LOG.debug("Configuration Path : " + path); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - HttpResponse response = doPut(serviceUrl , configJson); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - LOG.error("Error while storing configuration json "+e.getMessage(), e); - throw new APPCException(e); - } - - if (httpCode < 200 || httpCode >= 300 ) { - try { - LOG.debug("Config operation Error response code: " + httpCode); - ArrayList errorMessage = new ArrayList<>(); - JsonNode responseJson = toJsonNodeFromJsonString(respBody); - if(responseJson!=null && responseJson.get("errors")!=null) { - JsonNode errors = responseJson.get("errors").get("error"); - for (Iterator i = errors.elements();i.hasNext();){ - JsonNode error = i.next(); - errorMessage.add(error.get("error-message").textValue()); - } - } - throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); - } catch (Exception e) { - LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); - throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); - } - }else{ - LOG.debug("Config operation successful. Response code: " + httpCode); - } - } - - /** - * This is Generic method that can be used to perform REST Put operation - * @param url - Destination URL for put - * @param body - payload for put action which will be sent as request body. - * @return - HttpResponse object which is returned from put REST call. - * @throws APPCException - */ - public static HttpResponse doPut (URL url, String body) throws APPCException { - HttpPut put; - try { - put = new HttpPut(url.toExternalForm()); - put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); - put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); - - if (basicAuth != null) { - put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); - } - - StringEntity entity = new StringEntity(body); - entity.setContentType(Constants.OPERATION_APPLICATION_JSON); - put.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - try { - return client.execute(put); - } catch (IOException e) { - throw new APPCException(e); - } - - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public static String getUrl() { - return url.toExternalForm(); - } - - public static void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - LOG.error("Malformed URL " +newUrl + e.getMessage(), e); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user The user with optional domain name (for AAF) - * @param password The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basicAuth = null; - } - return basicAuth; - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - LOG.error("Error creating HTTP Client. Creating default client." , e); - client = new DefaultHttpClient(); - } - } else if ("http".equals(url.getProtocol())) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - private static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkClientTrusted"); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkServerTrusted"); - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[1]; - } - }; - - sslContext.init(null, new TrustManager[]{ - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - private static JsonNode toJsonNodeFromJsonString(String jsonStr) { - JsonNode jsonNode = null; - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); - } - } - return jsonNode; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge deleted file mode 100644 index 36f471853..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge +++ /dev/null @@ -1,295 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.impl.Constants; -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 org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.security.*; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.commons.io.IOUtils; - -/** - * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. -*/ -public class ConfigOperation { - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); - - private static URL url; - private static String basicAuth; - - ConfigOperation(){} - - private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input - * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store - * @param module - Module name that contains yang Schema - * @param containerName - yang container name which will be used as base container. - * @param subModules - Sub modules list if any. Order of sub module is top to bottom. - * @throws APPCException - */ - public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { - if (configJson == null) { - throw new APPCException("Provided message was null"); - } - LOG.debug("Config JSON: " + configJson +"\n" - +"module" + module +"\n" - +"containerName" + containerName +"\n" - +"subModules length : " + subModules.length ); - - int httpCode; - String respBody ; - try { - String path = requestFormatter.buildPath(url, module, containerName, subModules); - LOG.debug("Configuration Path : " + path); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - HttpResponse response = doPut(serviceUrl , configJson); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - LOG.error("Error while storing configuration json "+e.getMessage(), e); - throw new APPCException(e); - } - - if (httpCode < 200 || httpCode >= 300 ) { - try { - LOG.debug("Config operation Error response code: " + httpCode); - ArrayList errorMessage = new ArrayList<>(); - JsonNode responseJson = toJsonNodeFromJsonString(respBody); - if(responseJson!=null && responseJson.get("errors")!=null) { - JsonNode errors = responseJson.get("errors").get("error"); - for (Iterator i = errors.elements();i.hasNext();){ - JsonNode error = i.next(); - errorMessage.add(error.get("error-message").textValue()); - } - } - throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); - } catch (Exception e) { - LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); - throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); - } - }else{ - LOG.debug("Config operation successful. Response code: " + httpCode); - } - } - - /** - * This is Generic method that can be used to perform REST Put operation - * @param url - Destination URL for put - * @param body - payload for put action which will be sent as request body. - * @return - HttpResponse object which is returned from put REST call. - * @throws APPCException - */ - public static HttpResponse doPut (URL url, String body) throws APPCException { - HttpPut put; - try { - put = new HttpPut(url.toExternalForm()); - put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); - put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); - - if (basicAuth != null) { - put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); - } - - StringEntity entity = new StringEntity(body); - entity.setContentType(Constants.OPERATION_APPLICATION_JSON); - put.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - try { - return client.execute(put); - } catch (IOException e) { - throw new APPCException(e); - } - - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public static String getUrl() { - return url.toExternalForm(); - } - - public static void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - LOG.error("Malformed URL " +newUrl + e.getMessage(), e); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user The user with optional domain name (for AAF) - * @param password The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basicAuth = null; - } - return basicAuth; - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - LOG.error("Error creating HTTP Client. Creating default client." , e); - client = new DefaultHttpClient(); - } - } else if ("http".equals(url.getProtocol())) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - private static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkClientTrusted"); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkServerTrusted"); - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[1]; - } - }; - - sslContext.init(null, new TrustManager[]{ - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - private static JsonNode toJsonNodeFromJsonString(String jsonStr) { - JsonNode jsonNode = null; - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); - } - } - return jsonNode; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java deleted file mode 100644 index b2ada2ecc..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.mdsal.impl.Constants; - -import java.net.URL; -/** - * Creates request url path for config actions based on parameter like module name , container-name and sub modules if any. - */ - -public class ConfigOperationRequestFormatter { - /** - * Build a request url path for config actions - * @param module - yang module name - * @param containerName - yang container name - * @param subModules - sub module /container names as string in varargs ( String ) format - * @return - resultant path in String format - */ - public String buildPath(String module, String containerName , String... subModules ) { - - StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); - if(subModules.length >0){ - for(String subModule : subModules){ - path.append(subModule); - path.append("/"); - } - } - return path.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java new file mode 100644 index 000000000..e1c563a4b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface NetconfClientPlugin extends SvcLogicJavaPlugin { + void configure(Map params, SvcLogicContext ctx) throws APPCException; + void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException; + void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void getConfig(Map params, SvcLogicContext ctx) throws APPCException; + void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java new file mode 100644 index 000000000..a4086a521 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public interface NetconfDBPlugin extends SvcLogicJavaPlugin { + void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java new file mode 100644 index 000000000..174226473 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.netconf.*; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.NetconfClientPlugin; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + + + +public class NetconfClientPluginImpl implements NetconfClientPlugin { + + private static final String NETCONF_CLIENT_FACTORY_NAME = "org.onap.appc.adapter.netconf.NetconfClientFactory"; + private static ObjectMapper mapper = new ObjectMapper(); + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + private NetconfDataAccessService dao; + private NetconfClientFactory clientFactory; + + public NetconfClientPluginImpl() { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference srefNetconfClientFactory = bctx.getServiceReference(NetconfClientFactory.class); + clientFactory = (NetconfClientFactory) bctx.getService(srefNetconfClientFactory); + } + + public void setDao(NetconfDataAccessService dao) { + this.dao = dao; + this.dao.setSchema(Constants.NETCONF_SCHEMA); + } + + public void configure(Map params, SvcLogicContext ctx) throws APPCException { + + try { + // by default, it uses the jsch Netconf Adapter implementation by calling GetNetconfClient(NetconfClientType.SSH). + NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + try { + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + String netconfMessage = params.get("file-content"); + client.connect(connectionDetails); + client.configure(netconfMessage); + } catch (IOException e) { + logger.error("Error " + e.getMessage()); + throw new APPCException(e); + } finally { + client.disconnect(); + } + } catch (Exception e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + logger.error("Error " + e.getMessage()); + throw e; + } + } + + @Override + public void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to operationStateValidation with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + try{ + String paramName = Constants.VNF_TYPE_FIELD_NAME; + String vfType = params.get(paramName); + validateMandatoryParam(paramName, vfType); + VnfType vnfType = VnfType.getVnfType(vfType); + + paramName = Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME; + String vnfHostIpAddress = params.get(paramName); + validateMandatoryParam(paramName, vnfHostIpAddress); + + //get connectionDetails + String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME); + NetconfConnectionDetails connectionDetails = null; + if(StringUtils.isEmpty(connectionDetailsStr)){ + connectionDetails = retrieveConnectionDetails(vnfType); + connectionDetails.setHost(vnfHostIpAddress); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + }else{ + connectionDetails = mapper.readValue(connectionDetailsStr, NetconfConnectionDetails.class); + } + if(connectionDetails == null){ + throw new IllegalStateException("missing connectionDetails for VnfType:"+vnfType.name()); + } + + //get operationsStateNetconfMessage + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType); + String configurationFileName = operationalStateValidator.getConfigurationFileName(); + String operationsStateNetconfMessage = null; + if(!StringUtils.isEmpty(configurationFileName)){ + operationsStateNetconfMessage = retrieveConfigurationFileContent(configurationFileName); + } + + //connect checK Opertaions state and dissconnect + NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + try { + client.connect(connectionDetails); + String response = null; + if(!StringUtils.isEmpty(operationsStateNetconfMessage)) { + response = client.exchangeMessage(operationsStateNetconfMessage); + } + operationalStateValidator.validateResponse(response); + } finally { + client.disconnect(); + } + } catch (APPCException e) { + logger.error(e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw e; + } + catch (Exception e) { + logger.error(e.toString()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw new APPCException(e); + } + } + + @Override + public void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + this.configure(params, ctx); + } + + @Override + public void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + + NetconfClient client = null; + try { + if (logger.isDebugEnabled()) { + logger.debug("Entered backup to DEVICE_INTERFACE_LOG"); + } + + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + + //store configuration in database + dao.logDeviceInteraction(null,null,getCurrentDateTime(),configuration); + + } catch (Exception e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + } + + @Override + public void getConfig(Map params, SvcLogicContext ctx) throws APPCException { + NetconfClient client = null; + String confId=params.get("conf-id"); + if(confId.equalsIgnoreCase("current")){ + try { + if (logger.isDebugEnabled()) { + logger.debug("Entered getConfig to DEVICE_INTERFACE_LOG"); + } + //get netconf client to get configuration + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); + NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + if(configuration !=null){ + String fullConfig = ctx.getAttribute("fullConfig"); + fullConfig = fullConfig==null?"":fullConfig; + ctx.setAttribute("fullConfig",fullConfig + configuration); + + ctx.setAttribute("getConfig_Result","Success"); + String entityName=ctx.getAttribute("entity");//VM name + if(entityName!=null){ + ctx.setAttribute(entityName+".Configuration",configuration); + } + }else{ + ctx.setAttribute("getConfig_Result","failure"); + } + } catch (Exception e) { + ctx.setAttribute("getConfig_Result","failure"); + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + }else{ + logger.info("Current Conf id value is not supported"); + } + + } + + + @Override + public void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException { + NetconfClient client = null; + try { + logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG"); + //get netconf client to get configuration + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); + NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(params.get("host-ip-address")); + connectionDetails.setUsername(params.get("user-name")); + connectionDetails.setPassword(params.get("password")); + connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + if(configuration !=null){ + // logger.info("*************************************Configuration Output*************************************"); + ctx.setAttribute("running-config", configuration); + + ctx.setAttribute("getRunningConfig_Result","Success"); + }else{ + ctx.setAttribute("getRunningConfig_Result","failure"); + } + } catch (Exception e) { + ctx.setAttribute("getRunningConfig_Result","failure"); + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + } + + private String getCurrentDateTime() { + + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private int getPort(String s) { + int port = 830; + if((s != null) && !s.isEmpty()) { + port = Integer.parseInt(s); + } + return port; + } + + void validateMandatoryParam(String paramName, String paramValue) { + if(StringUtils.isEmpty(paramValue)){ + throw new IllegalArgumentException("input "+paramName+" param is empty"); + } + } + + public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{ + + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) { + logger.error("Missing configuration for " + vnfType.getFamilyType().name()); + throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + return connectionDetails; + } + + public String retrieveConfigurationFileContent(String configFileName){ + return dao.retrieveConfigFileName(configFileName); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java new file mode 100644 index 000000000..459ece9c1 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.Map; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.NetconfDBPlugin; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class NetconfDBPluginImpl implements NetconfDBPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static ObjectMapper mapper = new ObjectMapper(); + + // populated by blueprint framework + private NetconfDataAccessService daoService; + + public void setDaoService(NetconfDataAccessService daoService) { + this.daoService = daoService; + this.daoService.setSchema(Constants.NETCONF_SCHEMA); + } + + public NetconfDBPluginImpl() { + } + + public void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + + try { + String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); + ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + } catch(DataAccessException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } + + getConnection(params, ctx); + } + + @Override + public void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + logger.info("Setting entity value :" +params.get(Constants.RESOURCEKEY)); + ctx.setAttribute("entity", params.get(Constants.RESOURCEKEY)); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + try { + if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.RESOURCEKEY), connectionDetails)) { + ctx.setAttribute("retrieveVMDSConfiguration_Result","failure"); + logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); + throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + ctx.setAttribute("retrieveVMDSConfiguration_Result","success"); + } catch(APPCException e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } catch(DataAccessException | JsonProcessingException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } + } + + @Override + public void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException { + String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); + ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + } + + public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { + getConnection(params, ctx); + } + + private void getConnection(Map params, SvcLogicContext ctx) throws APPCException { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + try { + if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.VNF_TYPE_FIELD_NAME), connectionDetails)) { + logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); + throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + } catch(APPCException e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } catch(DataAccessException | JsonProcessingException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java deleted file mode 100644 index e1c563a4b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface NetconfClientPlugin extends SvcLogicJavaPlugin { - void configure(Map params, SvcLogicContext ctx) throws APPCException; - void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException; - void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void getConfig(Map params, SvcLogicContext ctx) throws APPCException; - void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java deleted file mode 100644 index a4086a521..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - - -public interface NetconfDBPlugin extends SvcLogicJavaPlugin { - void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java deleted file mode 100644 index 174226473..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.netconf.*; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.NetconfClientPlugin; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; - - - -public class NetconfClientPluginImpl implements NetconfClientPlugin { - - private static final String NETCONF_CLIENT_FACTORY_NAME = "org.onap.appc.adapter.netconf.NetconfClientFactory"; - private static ObjectMapper mapper = new ObjectMapper(); - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - private NetconfDataAccessService dao; - private NetconfClientFactory clientFactory; - - public NetconfClientPluginImpl() { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference srefNetconfClientFactory = bctx.getServiceReference(NetconfClientFactory.class); - clientFactory = (NetconfClientFactory) bctx.getService(srefNetconfClientFactory); - } - - public void setDao(NetconfDataAccessService dao) { - this.dao = dao; - this.dao.setSchema(Constants.NETCONF_SCHEMA); - } - - public void configure(Map params, SvcLogicContext ctx) throws APPCException { - - try { - // by default, it uses the jsch Netconf Adapter implementation by calling GetNetconfClient(NetconfClientType.SSH). - NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - try { - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - String netconfMessage = params.get("file-content"); - client.connect(connectionDetails); - client.configure(netconfMessage); - } catch (IOException e) { - logger.error("Error " + e.getMessage()); - throw new APPCException(e); - } finally { - client.disconnect(); - } - } catch (Exception e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - logger.error("Error " + e.getMessage()); - throw e; - } - } - - @Override - public void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to operationStateValidation with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - try{ - String paramName = Constants.VNF_TYPE_FIELD_NAME; - String vfType = params.get(paramName); - validateMandatoryParam(paramName, vfType); - VnfType vnfType = VnfType.getVnfType(vfType); - - paramName = Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME; - String vnfHostIpAddress = params.get(paramName); - validateMandatoryParam(paramName, vnfHostIpAddress); - - //get connectionDetails - String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME); - NetconfConnectionDetails connectionDetails = null; - if(StringUtils.isEmpty(connectionDetailsStr)){ - connectionDetails = retrieveConnectionDetails(vnfType); - connectionDetails.setHost(vnfHostIpAddress); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - }else{ - connectionDetails = mapper.readValue(connectionDetailsStr, NetconfConnectionDetails.class); - } - if(connectionDetails == null){ - throw new IllegalStateException("missing connectionDetails for VnfType:"+vnfType.name()); - } - - //get operationsStateNetconfMessage - OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType); - String configurationFileName = operationalStateValidator.getConfigurationFileName(); - String operationsStateNetconfMessage = null; - if(!StringUtils.isEmpty(configurationFileName)){ - operationsStateNetconfMessage = retrieveConfigurationFileContent(configurationFileName); - } - - //connect checK Opertaions state and dissconnect - NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - try { - client.connect(connectionDetails); - String response = null; - if(!StringUtils.isEmpty(operationsStateNetconfMessage)) { - response = client.exchangeMessage(operationsStateNetconfMessage); - } - operationalStateValidator.validateResponse(response); - } finally { - client.disconnect(); - } - } catch (APPCException e) { - logger.error(e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw e; - } - catch (Exception e) { - logger.error(e.toString()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw new APPCException(e); - } - } - - @Override - public void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - this.configure(params, ctx); - } - - @Override - public void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - - NetconfClient client = null; - try { - if (logger.isDebugEnabled()) { - logger.debug("Entered backup to DEVICE_INTERFACE_LOG"); - } - - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - - //store configuration in database - dao.logDeviceInteraction(null,null,getCurrentDateTime(),configuration); - - } catch (Exception e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - } - - @Override - public void getConfig(Map params, SvcLogicContext ctx) throws APPCException { - NetconfClient client = null; - String confId=params.get("conf-id"); - if(confId.equalsIgnoreCase("current")){ - try { - if (logger.isDebugEnabled()) { - logger.debug("Entered getConfig to DEVICE_INTERFACE_LOG"); - } - //get netconf client to get configuration - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); - NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - if(configuration !=null){ - String fullConfig = ctx.getAttribute("fullConfig"); - fullConfig = fullConfig==null?"":fullConfig; - ctx.setAttribute("fullConfig",fullConfig + configuration); - - ctx.setAttribute("getConfig_Result","Success"); - String entityName=ctx.getAttribute("entity");//VM name - if(entityName!=null){ - ctx.setAttribute(entityName+".Configuration",configuration); - } - }else{ - ctx.setAttribute("getConfig_Result","failure"); - } - } catch (Exception e) { - ctx.setAttribute("getConfig_Result","failure"); - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - }else{ - logger.info("Current Conf id value is not supported"); - } - - } - - - @Override - public void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException { - NetconfClient client = null; - try { - logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG"); - //get netconf client to get configuration - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); - NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(params.get("host-ip-address")); - connectionDetails.setUsername(params.get("user-name")); - connectionDetails.setPassword(params.get("password")); - connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - if(configuration !=null){ - // logger.info("*************************************Configuration Output*************************************"); - ctx.setAttribute("running-config", configuration); - - ctx.setAttribute("getRunningConfig_Result","Success"); - }else{ - ctx.setAttribute("getRunningConfig_Result","failure"); - } - } catch (Exception e) { - ctx.setAttribute("getRunningConfig_Result","failure"); - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - } - - private String getCurrentDateTime() { - - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); - return dateFormat.format(date); - } - - private int getPort(String s) { - int port = 830; - if((s != null) && !s.isEmpty()) { - port = Integer.parseInt(s); - } - return port; - } - - void validateMandatoryParam(String paramName, String paramValue) { - if(StringUtils.isEmpty(paramValue)){ - throw new IllegalArgumentException("input "+paramName+" param is empty"); - } - } - - public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{ - - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) { - logger.error("Missing configuration for " + vnfType.getFamilyType().name()); - throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - return connectionDetails; - } - - public String retrieveConfigurationFileContent(String configFileName){ - return dao.retrieveConfigFileName(configFileName); - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java deleted file mode 100644 index 459ece9c1..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.Map; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.NetconfDBPlugin; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class NetconfDBPluginImpl implements NetconfDBPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static ObjectMapper mapper = new ObjectMapper(); - - // populated by blueprint framework - private NetconfDataAccessService daoService; - - public void setDaoService(NetconfDataAccessService daoService) { - this.daoService = daoService; - this.daoService.setSchema(Constants.NETCONF_SCHEMA); - } - - public NetconfDBPluginImpl() { - } - - public void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - - try { - String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); - ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - } catch(DataAccessException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } - - getConnection(params, ctx); - } - - @Override - public void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - logger.info("Setting entity value :" +params.get(Constants.RESOURCEKEY)); - ctx.setAttribute("entity", params.get(Constants.RESOURCEKEY)); - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - try { - if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.RESOURCEKEY), connectionDetails)) { - ctx.setAttribute("retrieveVMDSConfiguration_Result","failure"); - logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); - throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - ctx.setAttribute("retrieveVMDSConfiguration_Result","success"); - } catch(APPCException e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } catch(DataAccessException | JsonProcessingException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } - } - - @Override - public void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException { - String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); - ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - } - - public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { - getConnection(params, ctx); - } - - private void getConnection(Map params, SvcLogicContext ctx) throws APPCException { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - try { - if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.VNF_TYPE_FIELD_NAME), connectionDetails)) { - logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); - throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - } catch(APPCException e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } catch(DataAccessException | JsonProcessingException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java new file mode 100644 index 000000000..379e164b5 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import java.util.HashMap; + +import org.onap.appc.adapter.netconf.ConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +class DAOServiceMock implements NetconfDataAccessService { + + private String configFile; + private ConnectionDetails connection; + private HashMap backupConf; + + @Override + public void setSchema(String schema) { + } + + @Override + public void setDbLibService(DbLibService dbLibService) { + } + + void setConfigFile(String configFile) { + this.configFile = configFile; + } + + public HashMap getBackupConf() { + return backupConf; + } + + public void setConnection(ConnectionDetails connection) { + this.connection = connection; + } + + @Override + public String retrieveConfigFileName(String xmlID) throws DataAccessException { + if (!xmlID.equals("wrong")) { + return configFile; + } else { + throw new DataAccessException(); + } + } + + @Override + public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws + DataAccessException { + return false; + } + + @Override + public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws + DataAccessException { + if (vnfType.equals("VNF")) { + connectionDetails.setHost(connection.getHost()); + connectionDetails.setPassword(connection.getPassword()); + connectionDetails.setPort(connection.getPort()); + connectionDetails.setUsername(connection.getUsername()); + + return true; + } else { + return false; + } + } + + @Override + public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws + DataAccessException { + this.backupConf = new HashMap<>(); + backupConf.put("creationDate", creationDate); + backupConf.put("logText", logText); + return true; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java new file mode 100644 index 000000000..802fe15e0 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.OperationalStateValidator; +import org.onap.appc.adapter.netconf.VnfType; +import org.onap.appc.exceptions.APPCException; + + +public class MockOperationalStateValidatorImpl implements OperationalStateValidator { + + private boolean validated; + private String configurationFileName; + + public boolean isValidated() { + return validated; + } + + @Override + public VnfType getVnfType() { + return null; + } + + @Override + public String getConfigurationFileName() { + return configurationFileName; + } + + @Override + public void validateResponse(String response) throws APPCException { + if (response.equals("wrong")) { + throw new APPCException(); + } else { + this.validated = true; + } + + } + + public void setConfigurationFileName(String configurationFileName) { + this.configurationFileName = configurationFileName; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java new file mode 100644 index 000000000..f61d188d9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfClientFactory; +import org.onap.appc.adapter.netconf.NetconfClientType; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; + + +public class NetconfClientFactoryMock extends NetconfClientFactory { + + private final NetconfClientJschMock jschClient = new NetconfClientJschMock(); + + @Override + public NetconfClient GetNetconfClient(NetconfClientType type){ + + return jschClient; + + } +} + + diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java new file mode 100644 index 000000000..82361a95e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.exceptions.APPCException; + + +public class NetconfClientJschMock implements NetconfClient { + + private boolean connection; + private String lastMessage; + private String answer = "answer"; + private String configuration; + private NetconfConnectionDetails lastConnectionDetails; + + public boolean isConnection() { + return connection; + } + + public String getLastMessage() { + return lastMessage; + } + + public String getAnswer() { + return answer; + } + + public String getConf() { + return configuration; + } + + public void setConf(String configuration) { + this.configuration = configuration; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public NetconfConnectionDetails getLastConnectionDetails() { + return lastConnectionDetails; + } + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { + this.connection = true; + this.lastConnectionDetails = connectionDetails; + + } + + @Override + public String exchangeMessage(String message) throws APPCException { + if (connection) { + this.lastMessage = message; + return answer; + } else return null; + } + + @Override + public void configure(String configuration) throws APPCException { + if (connection) { + this.configuration = configuration; + } + + } + + @Override + public String getConfiguration() throws APPCException { + if (connection) { + return configuration; + } else return null; + } + + @Override + public void disconnect() throws APPCException { + this.connection = false; + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java new file mode 100644 index 000000000..0becff701 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java @@ -0,0 +1,681 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.exceptions.APPCException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.netconf.*; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.impl.NetconfClientPluginImpl; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.lang.reflect.Field; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.powermock.api.mockito.PowerMockito.when; + + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class}) + +public class NetconfClientPluginImplTest { + private NetconfClientPluginImpl netconfClientPlugin; + private NetconfDataAccessService dao; + private NetconfClientFactory clientFactory; + private Map params; + + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref1 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref2 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref3 = Mockito.mock(ServiceReference.class); + private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + + String host = "http://www.test.com"; + String host1 = "http://www.test1.com"; + String vnfType = "VNF"; + int port = 8080; + String username = "test"; + String password = "test"; + String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}"; + String fileContent = "\n" + + "\n" + + "\t\n" + + "\t\t\n" + + "\t\t\t\n" + + "\t\t \n" + + "\t\n" + + "'"; + String operationalState = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + clientFactory = new NetconfClientFactoryMock(); + + } + + + @Test + public void testConfigure() throws Exception { + + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + + netconfClientPlugin.configure(params, ctx); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + try { + Assert.assertEquals("wrong configuration", fileContent, client.getConf()); + Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost()); + Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort()); + Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername()); + Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword()); + Assert.assertFalse(client.isConnection()); + } catch (Exception e) { + Assert.fail("failed with because of " + e.getCause()); + } + + + } + + + @Test + public void testConfigureNegativeIOException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + + try { + netconfClientPlugin.configure(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(client.getLastConnectionDetails()); + Assert.assertNull(client.getConf()); + } + + } + + @Test + public void testOperationStateValidation() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + substituteMapper(true); + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + substituteMapper(false); + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse(validatorMock.isValidated()); + Assert.assertNull(client.getLastMessage()); + } + } + + @Test + public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class); + final NetconfConnectionDetails netconfConnectionDetails = null; + when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidationNegativeAppcException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer("wrong"); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, ""); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testBackupConfiguration() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + netconfClientPlugin.backupConfiguration(params, ctx); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); + Date date = new Date(); + String creationDateExpected = dateFormat.format(date); + String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10); + + + Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText")); + Assert.assertEquals(creationDateExpected, creationDateActual); + + + } + + + @Test + public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + try { + netconfClientPlugin.backupConfiguration(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + Assert.assertNull(mockdao.getBackupConf()); + } + + } + + @Test + public void testGetConfig() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig")); + Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeConfigurationNull() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeNotSupportedConfId() throws Exception { + fullInit(); + String entity = "123"; + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current1"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertNull(ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + @Test + public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + + + try { + netconfClientPlugin.getConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfig() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("running-config")); + Assert.assertEquals("success", ctx.getStatus()); + } + + @Test + public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + try { + netconfClientPlugin.getRunningConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfigNegativeConfigurationNull() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + } + + @Test + public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception { + shortInit(); + String paramName = "test"; + String paramValue = ""; + + try { + netconfClientPlugin.validateMandatoryParam(paramName, paramValue); + Assert.assertTrue(false); + } catch (Exception e) { + Assert.assertTrue(true); + } + } + + @Test + public void testRetrieveConnectionDetails() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF); + + + Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost()); + Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword()); + Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort()); + Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername()); + } + + + @Test + public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = null; + try { + connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(connectionDetailsActual); + } + + + } + + @Test + public void testRetrieveConfigurationFileContent() throws Exception { + shortInit(); + + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig")); + } + + private ConnectionDetails getConnectionDetails() { + + ConnectionDetails connectionDetails = new ConnectionDetails(); + connectionDetails.setPassword(password); + connectionDetails.setPort(port); + connectionDetails.setUsername(username); + connectionDetails.setHost(host); + return connectionDetails; + } + + + private void initDao() throws NoSuchFieldException, IllegalAccessException { + dao = new DAOServiceMock(); + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1); + when(bundleContext.getService(sref1)).thenReturn(dao); + + + } + + private void fullInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initClientFactory2(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void shortInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void initClientFactory() throws NoSuchFieldException, IllegalAccessException { + + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2); + when(bundleContext.getService(sref2)).thenReturn(clientFactory); + + } + + private void initClientFactory2() { + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3); + when(bundleContext.getService(sref3)).thenReturn(clientFactory); + } + + private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { + ObjectMapper mapper = new ObjectMapperMock(); + ObjectMapper mapper2 = new ObjectMapper(); + Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper"); + field.setAccessible(true); + if (command) { + field.set(netconfClientPlugin, mapper); + } else { + field.set(netconfClientPlugin, mapper2); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java new file mode 100644 index 000000000..5137b904b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java @@ -0,0 +1,253 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.*; +import org.onap.appc.adapter.netconf.ConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.appc.dg.netconf.impl.NetconfDBPluginImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import static org.powermock.api.support.SuppressCode.suppressConstructor; + +public class NetconfDBPluginImplTest { + private NetconfDBPluginImpl netconfDBPlugin; + private NetconfDataAccessService daoService; + private DAOServiceMock daoMock; + private Map params; + private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + String host = "http://www.test.com"; + String host1 = "http://www.test1.com"; + int port = 8080; + String username = "test"; + String password = "test"; + String configContent = "\n" + + "\n" + + "\t\n" + + "\t\t\n" + + "\t\t\t\n" + + "\t\t \n" + + "\t\n" + + "'"; + + + @Test + public void testRetrieveDSConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("configuration-file-name", "VnfGetRunningConfig"); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveDSConfiguration(params, ctx); + + Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); + Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); + } + + + @Test + public void testRetrieveDSConfigurationNegativeErrorFieldNameDaoException() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("configuration-file-name", "wrong"); + + try { + netconfDBPlugin.retrieveDSConfiguration(params, ctx); + } catch (DataAccessException e) { + //Assert.assertNotNull(ctx.getAttribute("org.onap.appc.dg.error")); + Assert.assertNull(ctx.getAttribute("file-content")); + } + + + } + + @Test + public void testRetrieveVMDSConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("resourceKey", "VNF"); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + + Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result", "success", ctx.getAttribute("retrieveVMDSConfiguration_Result")); + Assert.assertEquals("wrong entity", "VNF", ctx.getAttribute("entity")); + assertConnectionDetails(ctx, host); + } + + @Test + public void testRetrieveVMDSConfigurationNegativeMissingConfiguration() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("resourceKey", "MOCK"); + + try { + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + + Assert.assertEquals("failure", ctx.getAttribute("retrieveVMDSConfiguration_Result")); + } + } + + + @Test + public void testRetrieveVMDSConfigurationNegativeJsonProcessingException() throws Exception { + + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("resourceKey", "VNF"); + + init(); + substituteMapper(true); + try { + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + substituteMapper(false); + Assert.assertTrue(false); + + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + + } + + } + + @Test + public void testRetrieveConfigFile() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("configuration-file-name", "VnfGetRunningConfig"); + netconfDBPlugin.retrieveConfigFile(params, ctx); + + Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); + Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); + } + + @Test + public void testRetrieveConnectionDetails() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + + assertConnectionDetails(ctx, host1); + } + + @Test + public void testRetrieveConnectionDetailsNegativeJsonProcessingException() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "MOCK"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + + try { + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(ctx.getAttribute("connection-details")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + } + + + @Test + public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + substituteMapper(true); + + try { + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + substituteMapper(false); + Assert.assertTrue(false); + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNull(ctx.getAttribute("connection-details")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + } + + private void assertConnectionDetails(SvcLogicContext ctx, String host) throws IOException { + String sConnectionDetails = ctx.getAttribute("connection-details"); + NetconfConnectionDetails connectionDetails = new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class); + Assert.assertEquals(host, connectionDetails.getHost()); + Assert.assertEquals(port, connectionDetails.getPort()); + Assert.assertEquals(username, connectionDetails.getUsername()); + Assert.assertEquals(password, connectionDetails.getPassword()); + Assert.assertNull(connectionDetails.getCapabilities()); + Assert.assertNull(connectionDetails.getAdditionalProperties()); + } + + private void init() { + netconfDBPlugin = new NetconfDBPluginImpl(); + daoService = new DAOServiceMock(); + netconfDBPlugin.setDaoService(daoService); + daoMock = (DAOServiceMock) daoService; + daoMock.setConfigFile(configContent); + daoMock.setConnection(getConnectionDetails()); + + } + + private ConnectionDetails getConnectionDetails() { + ConnectionDetails connectionDetails = new ConnectionDetails(); + connectionDetails.setHost(host); + connectionDetails.setUsername(username); + connectionDetails.setPort(port); + connectionDetails.setPassword(password); + return connectionDetails; + } + + private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { + ObjectMapper mapper = new ObjectMapperMock(); + ObjectMapper mapper2 = new ObjectMapper(); + Field field = NetconfDBPluginImpl.class.getDeclaredField("mapper"); + field.setAccessible(true); + if (command) { + field.set(netconfDBPlugin, mapper); + } else { + field.set(netconfDBPlugin, mapper2); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java new file mode 100644 index 000000000..cacc15eae --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; + + +public class ObjectMapperMock extends ObjectMapper { + + @Override + public String writeValueAsString(Object var1) throws JsonProcessingException { + throw new JsonProcessingException("") { + }; + + } + + @Override + public T readValue(String var1, Class var2) throws IOException, JsonParseException, JsonMappingException { + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java new file mode 100644 index 000000000..2194fc14c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.appc.adapter.netconf.*; + + +public class OperationStateValidatorFactoryMock extends OperationalStateValidatorFactory { + public static OperationalStateValidator getOperationalStateValidator(String vnfType) { + VnfType vnfTypeEnum = null; + try { + vnfTypeEnum = VnfType.getVnfType(vnfType); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Illegal value in vnfType. vnfType=" + vnfType, e); + } + return getOperationalStateValidator(vnfTypeEnum); + } + + public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { + + return new MockOperationalStateValidatorImpl(); + + + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java deleted file mode 100644 index 379e164b5..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import java.util.HashMap; - -import org.onap.appc.adapter.netconf.ConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -class DAOServiceMock implements NetconfDataAccessService { - - private String configFile; - private ConnectionDetails connection; - private HashMap backupConf; - - @Override - public void setSchema(String schema) { - } - - @Override - public void setDbLibService(DbLibService dbLibService) { - } - - void setConfigFile(String configFile) { - this.configFile = configFile; - } - - public HashMap getBackupConf() { - return backupConf; - } - - public void setConnection(ConnectionDetails connection) { - this.connection = connection; - } - - @Override - public String retrieveConfigFileName(String xmlID) throws DataAccessException { - if (!xmlID.equals("wrong")) { - return configFile; - } else { - throw new DataAccessException(); - } - } - - @Override - public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws - DataAccessException { - return false; - } - - @Override - public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws - DataAccessException { - if (vnfType.equals("VNF")) { - connectionDetails.setHost(connection.getHost()); - connectionDetails.setPassword(connection.getPassword()); - connectionDetails.setPort(connection.getPort()); - connectionDetails.setUsername(connection.getUsername()); - - return true; - } else { - return false; - } - } - - @Override - public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws - DataAccessException { - this.backupConf = new HashMap<>(); - backupConf.put("creationDate", creationDate); - backupConf.put("logText", logText); - return true; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java deleted file mode 100644 index 802fe15e0..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.OperationalStateValidator; -import org.onap.appc.adapter.netconf.VnfType; -import org.onap.appc.exceptions.APPCException; - - -public class MockOperationalStateValidatorImpl implements OperationalStateValidator { - - private boolean validated; - private String configurationFileName; - - public boolean isValidated() { - return validated; - } - - @Override - public VnfType getVnfType() { - return null; - } - - @Override - public String getConfigurationFileName() { - return configurationFileName; - } - - @Override - public void validateResponse(String response) throws APPCException { - if (response.equals("wrong")) { - throw new APPCException(); - } else { - this.validated = true; - } - - } - - public void setConfigurationFileName(String configurationFileName) { - this.configurationFileName = configurationFileName; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java deleted file mode 100644 index f61d188d9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfClientFactory; -import org.onap.appc.adapter.netconf.NetconfClientType; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; - - -public class NetconfClientFactoryMock extends NetconfClientFactory { - - private final NetconfClientJschMock jschClient = new NetconfClientJschMock(); - - @Override - public NetconfClient GetNetconfClient(NetconfClientType type){ - - return jschClient; - - } -} - - diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java deleted file mode 100644 index 82361a95e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.exceptions.APPCException; - - -public class NetconfClientJschMock implements NetconfClient { - - private boolean connection; - private String lastMessage; - private String answer = "answer"; - private String configuration; - private NetconfConnectionDetails lastConnectionDetails; - - public boolean isConnection() { - return connection; - } - - public String getLastMessage() { - return lastMessage; - } - - public String getAnswer() { - return answer; - } - - public String getConf() { - return configuration; - } - - public void setConf(String configuration) { - this.configuration = configuration; - } - - public void setAnswer(String answer) { - this.answer = answer; - } - - public NetconfConnectionDetails getLastConnectionDetails() { - return lastConnectionDetails; - } - - @Override - public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { - this.connection = true; - this.lastConnectionDetails = connectionDetails; - - } - - @Override - public String exchangeMessage(String message) throws APPCException { - if (connection) { - this.lastMessage = message; - return answer; - } else return null; - } - - @Override - public void configure(String configuration) throws APPCException { - if (connection) { - this.configuration = configuration; - } - - } - - @Override - public String getConfiguration() throws APPCException { - if (connection) { - return configuration; - } else return null; - } - - @Override - public void disconnect() throws APPCException { - this.connection = false; - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java deleted file mode 100644 index 0becff701..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java +++ /dev/null @@ -1,681 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.exceptions.APPCException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.netconf.*; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.impl.NetconfClientPluginImpl; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.lang.reflect.Field; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.when; - - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class}) - -public class NetconfClientPluginImplTest { - private NetconfClientPluginImpl netconfClientPlugin; - private NetconfDataAccessService dao; - private NetconfClientFactory clientFactory; - private Map params; - - private final BundleContext bundleContext = Mockito.mock(BundleContext.class); - private final Bundle bundleService = Mockito.mock(Bundle.class); - private final ServiceReference sref1 = Mockito.mock(ServiceReference.class); - private final ServiceReference sref2 = Mockito.mock(ServiceReference.class); - private final ServiceReference sref3 = Mockito.mock(ServiceReference.class); - private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - - - String host = "http://www.test.com"; - String host1 = "http://www.test1.com"; - String vnfType = "VNF"; - int port = 8080; - String username = "test"; - String password = "test"; - String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}"; - String fileContent = "\n" + - "\n" + - "\t\n" + - "\t\t\n" + - "\t\t\t\n" + - "\t\t \n" + - "\t\n" + - "'"; - String operationalState = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"; - - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - clientFactory = new NetconfClientFactoryMock(); - - } - - - @Test - public void testConfigure() throws Exception { - - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - - netconfClientPlugin.configure(params, ctx); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - - try { - Assert.assertEquals("wrong configuration", fileContent, client.getConf()); - Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost()); - Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort()); - Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername()); - Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword()); - Assert.assertFalse(client.isConnection()); - } catch (Exception e) { - Assert.fail("failed with because of " + e.getCause()); - } - - - } - - - @Test - public void testConfigureNegativeIOException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - - - try { - netconfClientPlugin.configure(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(client.getLastConnectionDetails()); - Assert.assertNull(client.getConf()); - } - - } - - @Test - public void testOperationStateValidation() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - - @Test - public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - substituteMapper(true); - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - substituteMapper(false); - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse(validatorMock.isValidated()); - Assert.assertNull(client.getLastMessage()); - } - } - - @Test - public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class); - final NetconfConnectionDetails netconfConnectionDetails = null; - when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails); - - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse("validation process failed", validatorMock.isValidated()); - - } - } - - - @Test - public void testOperationStateValidationNegativeAppcException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer("wrong"); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse("validation process failed", validatorMock.isValidated()); - - } - } - - - @Test - public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - ((DAOServiceMock) dao).setConnection(getConnectionDetails()); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, ""); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - @Test - public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - ((DAOServiceMock) dao).setConnection(getConnectionDetails()); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - - @Test - public void testBackupConfiguration() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - netconfClientPlugin.backupConfiguration(params, ctx); - - DAOServiceMock mockdao = (DAOServiceMock) dao; - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); - Date date = new Date(); - String creationDateExpected = dateFormat.format(date); - String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10); - - - Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText")); - Assert.assertEquals(creationDateExpected, creationDateActual); - - - } - - - @Test - public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - try { - netconfClientPlugin.backupConfiguration(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - - DAOServiceMock mockdao = (DAOServiceMock) dao; - Assert.assertNull(mockdao.getBackupConf()); - } - - } - - @Test - public void testGetConfig() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result")); - Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig")); - Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration")); - } - - - @Test - public void testGetConfigNegativeConfigurationNull() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - } - - - @Test - public void testGetConfigNegativeNotSupportedConfId() throws Exception { - fullInit(); - String entity = "123"; - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current1"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertNull(ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - } - - @Test - public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - - - try { - netconfClientPlugin.getConfig(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - - } - - @Test - public void testGetRunningConfig() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - params.put("port-number", String.valueOf(port)); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - netconfClientPlugin.getRunningConfig(params, ctx); - - Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertEquals(fileContent, ctx.getAttribute("running-config")); - Assert.assertEquals("success", ctx.getStatus()); - } - - @Test - public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - try { - netconfClientPlugin.getRunningConfig(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertNull(ctx.getAttribute("running-config")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - - } - - @Test - public void testGetRunningConfigNegativeConfigurationNull() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - params.put("port-number", String.valueOf(port)); - - netconfClientPlugin.getRunningConfig(params, ctx); - - Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertNull(ctx.getAttribute("running-config")); - } - - @Test - public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception { - shortInit(); - String paramName = "test"; - String paramValue = ""; - - try { - netconfClientPlugin.validateMandatoryParam(paramName, paramValue); - Assert.assertTrue(false); - } catch (Exception e) { - Assert.assertTrue(true); - } - } - - @Test - public void testRetrieveConnectionDetails() throws Exception { - shortInit(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - ConnectionDetails connectionDetails1 = getConnectionDetails(); - daoServiceMock.setConnection(connectionDetails1); - - NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF); - - - Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost()); - Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword()); - Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort()); - Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername()); - } - - - @Test - public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { - shortInit(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - ConnectionDetails connectionDetails1 = getConnectionDetails(); - daoServiceMock.setConnection(connectionDetails1); - - NetconfConnectionDetails connectionDetailsActual = null; - try { - connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(connectionDetailsActual); - } - - - } - - @Test - public void testRetrieveConfigurationFileContent() throws Exception { - shortInit(); - - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig")); - } - - private ConnectionDetails getConnectionDetails() { - - ConnectionDetails connectionDetails = new ConnectionDetails(); - connectionDetails.setPassword(password); - connectionDetails.setPort(port); - connectionDetails.setUsername(username); - connectionDetails.setHost(host); - return connectionDetails; - } - - - private void initDao() throws NoSuchFieldException, IllegalAccessException { - dao = new DAOServiceMock(); - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1); - when(bundleContext.getService(sref1)).thenReturn(dao); - - - } - - private void fullInit() throws NoSuchFieldException, IllegalAccessException { - initClientFactory(); - initClientFactory2(); - initDao(); - netconfClientPlugin = new NetconfClientPluginImpl(); - netconfClientPlugin.setDao(this.dao); - } - - private void shortInit() throws NoSuchFieldException, IllegalAccessException { - initClientFactory(); - initDao(); - netconfClientPlugin = new NetconfClientPluginImpl(); - netconfClientPlugin.setDao(this.dao); - } - - private void initClientFactory() throws NoSuchFieldException, IllegalAccessException { - - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2); - when(bundleContext.getService(sref2)).thenReturn(clientFactory); - - } - - private void initClientFactory2() { - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3); - when(bundleContext.getService(sref3)).thenReturn(clientFactory); - } - - private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { - ObjectMapper mapper = new ObjectMapperMock(); - ObjectMapper mapper2 = new ObjectMapper(); - Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper"); - field.setAccessible(true); - if (command) { - field.set(netconfClientPlugin, mapper); - } else { - field.set(netconfClientPlugin, mapper2); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java deleted file mode 100644 index 5137b904b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.*; -import org.onap.appc.adapter.netconf.ConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.appc.dg.netconf.impl.NetconfDBPluginImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.support.SuppressCode.suppressConstructor; - -public class NetconfDBPluginImplTest { - private NetconfDBPluginImpl netconfDBPlugin; - private NetconfDataAccessService daoService; - private DAOServiceMock daoMock; - private Map params; - private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - String host = "http://www.test.com"; - String host1 = "http://www.test1.com"; - int port = 8080; - String username = "test"; - String password = "test"; - String configContent = "\n" + - "\n" + - "\t\n" + - "\t\t\n" + - "\t\t\t\n" + - "\t\t \n" + - "\t\n" + - "'"; - - - @Test - public void testRetrieveDSConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("configuration-file-name", "VnfGetRunningConfig"); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveDSConfiguration(params, ctx); - - Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); - Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); - } - - - @Test - public void testRetrieveDSConfigurationNegativeErrorFieldNameDaoException() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("configuration-file-name", "wrong"); - - try { - netconfDBPlugin.retrieveDSConfiguration(params, ctx); - } catch (DataAccessException e) { - //Assert.assertNotNull(ctx.getAttribute("org.onap.appc.dg.error")); - Assert.assertNull(ctx.getAttribute("file-content")); - } - - - } - - @Test - public void testRetrieveVMDSConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("resourceKey", "VNF"); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - - Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result", "success", ctx.getAttribute("retrieveVMDSConfiguration_Result")); - Assert.assertEquals("wrong entity", "VNF", ctx.getAttribute("entity")); - assertConnectionDetails(ctx, host); - } - - @Test - public void testRetrieveVMDSConfigurationNegativeMissingConfiguration() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("resourceKey", "MOCK"); - - try { - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - - Assert.assertEquals("failure", ctx.getAttribute("retrieveVMDSConfiguration_Result")); - } - } - - - @Test - public void testRetrieveVMDSConfigurationNegativeJsonProcessingException() throws Exception { - - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("resourceKey", "VNF"); - - init(); - substituteMapper(true); - try { - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - substituteMapper(false); - Assert.assertTrue(false); - - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - - } - - } - - @Test - public void testRetrieveConfigFile() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("configuration-file-name", "VnfGetRunningConfig"); - netconfDBPlugin.retrieveConfigFile(params, ctx); - - Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); - Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); - } - - @Test - public void testRetrieveConnectionDetails() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - - assertConnectionDetails(ctx, host1); - } - - @Test - public void testRetrieveConnectionDetailsNegativeJsonProcessingException() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "MOCK"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - - try { - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(ctx.getAttribute("connection-details")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - } - - - @Test - public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - substituteMapper(true); - - try { - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - substituteMapper(false); - Assert.assertTrue(false); - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNull(ctx.getAttribute("connection-details")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - } - - private void assertConnectionDetails(SvcLogicContext ctx, String host) throws IOException { - String sConnectionDetails = ctx.getAttribute("connection-details"); - NetconfConnectionDetails connectionDetails = new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class); - Assert.assertEquals(host, connectionDetails.getHost()); - Assert.assertEquals(port, connectionDetails.getPort()); - Assert.assertEquals(username, connectionDetails.getUsername()); - Assert.assertEquals(password, connectionDetails.getPassword()); - Assert.assertNull(connectionDetails.getCapabilities()); - Assert.assertNull(connectionDetails.getAdditionalProperties()); - } - - private void init() { - netconfDBPlugin = new NetconfDBPluginImpl(); - daoService = new DAOServiceMock(); - netconfDBPlugin.setDaoService(daoService); - daoMock = (DAOServiceMock) daoService; - daoMock.setConfigFile(configContent); - daoMock.setConnection(getConnectionDetails()); - - } - - private ConnectionDetails getConnectionDetails() { - ConnectionDetails connectionDetails = new ConnectionDetails(); - connectionDetails.setHost(host); - connectionDetails.setUsername(username); - connectionDetails.setPort(port); - connectionDetails.setPassword(password); - return connectionDetails; - } - - private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { - ObjectMapper mapper = new ObjectMapperMock(); - ObjectMapper mapper2 = new ObjectMapper(); - Field field = NetconfDBPluginImpl.class.getDeclaredField("mapper"); - field.setAccessible(true); - if (command) { - field.set(netconfDBPlugin, mapper); - } else { - field.set(netconfDBPlugin, mapper2); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java deleted file mode 100644 index cacc15eae..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - - -public class ObjectMapperMock extends ObjectMapper { - - @Override - public String writeValueAsString(Object var1) throws JsonProcessingException { - throw new JsonProcessingException("") { - }; - - } - - @Override - public T readValue(String var1, Class var2) throws IOException, JsonParseException, JsonMappingException { - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java deleted file mode 100644 index 2194fc14c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.apache.commons.lang3.NotImplementedException; -import org.onap.appc.adapter.netconf.*; - - -public class OperationStateValidatorFactoryMock extends OperationalStateValidatorFactory { - public static OperationalStateValidator getOperationalStateValidator(String vnfType) { - VnfType vnfTypeEnum = null; - try { - vnfTypeEnum = VnfType.getVnfType(vnfType); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Illegal value in vnfType. vnfType=" + vnfType, e); - } - return getOperationalStateValidator(vnfTypeEnum); - } - - public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { - - return new MockOperationalStateValidatorImpl(); - - - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java new file mode 100644 index 000000000..da5e3dfe6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public interface SshDBPlugin extends SvcLogicJavaPlugin { + void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java new file mode 100644 index 000000000..591e58805 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * Set of common methods that can be called from DG. + */ +public interface SshService extends SvcLogicJavaPlugin { + + /** + * Input parameter for SHH connection details + */ + String PARAM_IN_connection_details = "connection_details"; + + /** + * Input parameter for SSH command to be executed. + */ + String PARAM_IN_command = "command"; + + /** + * Input parameter for SSH command timeout + */ + String PARAM_IN_timeout = "timeout"; + + /** + * Output parameter - SSH command execution status. + */ + String PARAM_OUT_status = "status"; + + /** + * Output parameter - content of SSH command stdout. + */ + String PARAM_OUT_stdout = "stdout"; + + /** + * Output parameter - content of SSH command stderr. + */ + String PARAM_OUT_stderr = "stderr"; + + /** + * Default SSH connection port. + */ + int DEF_port = 22; + + /** + * Default SSH command timeout + */ + long DEF_timeout = 120000; + + /** + * Default success status. + */ + int DEF_SUCCESS_STATUS = 0; + + /** + * Execute remote command over SSH. + * + * @param params contains list of input parameters required for the implementation + * @param ctx SLI service logic context + * @throws APPCException + */ + void exec(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Execute remote command over SSH and check return status assuming that success status is 0. + * If non-zero status is returned - fail the execution by throwing exception with content written + * by command to stderr. + * + * @param params contains list of input parameters required for the implementation + * @param ctx SLI service logic context + * @throws APPCException + */ + void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java new file mode 100644 index 000000000..c3dfc61d6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.Map; + +import org.onap.appc.adapter.ssh.Constants; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.adapter.ssh.SshDataAccessException; +import org.onap.appc.adapter.ssh.SshDataAccessService; +import org.onap.appc.dg.ssh.SshDBPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class SshDBPluginImpl implements SshDBPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static ObjectMapper mapper = new ObjectMapper(); + + private SshDataAccessService dataAccessService; + + public void setDataAccessService(SshDataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { + SshConnectionDetails connectionDetails = new SshConnectionDetails(); + //String vnfType = ctx.getAttribute("aai.prefix")+"."+"vnf-type"; + String vnfType = params.get("vnf-type"); + try { + if (!dataAccessService.retrieveConnectionDetails(vnfType, connectionDetails)) { + logger.error("Missing connection details for VNF type: " + vnfType); + throw new APPCException("Missing configuration for " + vnfType + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + } catch(APPCException e) { + String msg = EELFResourceManager.format(Msg.APPC_EXCEPTION, vnfType, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + } catch(SshDataAccessException e) { + String msg = EELFResourceManager.format(Msg.SSH_DATA_EXCEPTION, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw e; + } catch (JsonProcessingException e) { + String msg = EELFResourceManager.format(Msg.JSON_PROCESSING_EXCEPTION, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(e); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java new file mode 100644 index 000000000..1c584cdb9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; + +import org.onap.appc.adapter.ssh.SshAdapter; +import org.onap.appc.adapter.ssh.SshConnection; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.dg.ssh.SshService; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class SshServiceImpl implements SshService { + + private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static final ObjectMapper mapper = new ObjectMapper(); + + private SshAdapter sshAdapter; + + public void setSshAdapter(SshAdapter sshAdapter) { + this.sshAdapter = sshAdapter; + } + + @Override + public void exec(Map params, SvcLogicContext ctx) throws APPCException { + SshConnectionDetails connectionDetails = resolveConnectionDetails(params.get(PARAM_IN_connection_details)); + String command = params.get(PARAM_IN_command); + logger.debug("=> Connecting to SSH server..."); + SshConnection sshConnection = sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(), connectionDetails.getUsername(), connectionDetails.getPassword()); + sshConnection.connect(); + try { + logger.debug("=> Connected to SSH server..."); + logger.debug("=> Running SSH command..."); + long timeout = DEF_timeout; + String stimeout = params.get(PARAM_IN_timeout); + if ((stimeout != null && !stimeout.isEmpty())) { + timeout = Long.parseLong(stimeout); + } + sshConnection.setExecTimeout(timeout); + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + int status = sshConnection.execCommand(command, stdout, stderr); + String stdoutRes = stdout.toString(); + String stderrRes = stderr.toString(); + logger.debug("=> executed SSH command"); + ctx.setAttribute(PARAM_OUT_status, String.format("%01d", status)); + ctx.setAttribute(PARAM_OUT_stdout, stdoutRes); + ctx.setAttribute(PARAM_OUT_stderr, stderrRes); + } finally { + sshConnection.disconnect(); + } + } + + private SshConnectionDetails resolveConnectionDetails(String connectionDetailsStr) throws APPCException { + SshConnectionDetails connectionDetails = null; + try { + connectionDetails = mapper.readValue(connectionDetailsStr, SshConnectionDetails.class); + if (0 == connectionDetails.getPort()) connectionDetails.setPort(DEF_port); + } catch (IOException e) { + throw new APPCException(e); + } + return connectionDetails; + } + + @Override + public void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException { + exec(params, ctx); + int status = Integer.parseInt(ctx.getAttribute(PARAM_OUT_status)); + if(status != DEF_SUCCESS_STATUS) { + StringBuilder errmsg = new StringBuilder(); + errmsg.append("SSH command returned error status [").append(status).append(']'); + String stderr = ctx.getAttribute(PARAM_OUT_stderr); + if((stderr != null) && !stderr.isEmpty()) { + errmsg.append(". Error: [").append(stderr).append(']'); + } + throw new APPCException(errmsg.toString()); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java deleted file mode 100644 index da5e3dfe6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public interface SshDBPlugin extends SvcLogicJavaPlugin { - void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java deleted file mode 100644 index 591e58805..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -/** - * Set of common methods that can be called from DG. - */ -public interface SshService extends SvcLogicJavaPlugin { - - /** - * Input parameter for SHH connection details - */ - String PARAM_IN_connection_details = "connection_details"; - - /** - * Input parameter for SSH command to be executed. - */ - String PARAM_IN_command = "command"; - - /** - * Input parameter for SSH command timeout - */ - String PARAM_IN_timeout = "timeout"; - - /** - * Output parameter - SSH command execution status. - */ - String PARAM_OUT_status = "status"; - - /** - * Output parameter - content of SSH command stdout. - */ - String PARAM_OUT_stdout = "stdout"; - - /** - * Output parameter - content of SSH command stderr. - */ - String PARAM_OUT_stderr = "stderr"; - - /** - * Default SSH connection port. - */ - int DEF_port = 22; - - /** - * Default SSH command timeout - */ - long DEF_timeout = 120000; - - /** - * Default success status. - */ - int DEF_SUCCESS_STATUS = 0; - - /** - * Execute remote command over SSH. - * - * @param params contains list of input parameters required for the implementation - * @param ctx SLI service logic context - * @throws APPCException - */ - void exec(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Execute remote command over SSH and check return status assuming that success status is 0. - * If non-zero status is returned - fail the execution by throwing exception with content written - * by command to stderr. - * - * @param params contains list of input parameters required for the implementation - * @param ctx SLI service logic context - * @throws APPCException - */ - void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java deleted file mode 100644 index c3dfc61d6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.Map; - -import org.onap.appc.adapter.ssh.Constants; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.adapter.ssh.SshDataAccessException; -import org.onap.appc.adapter.ssh.SshDataAccessService; -import org.onap.appc.dg.ssh.SshDBPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class SshDBPluginImpl implements SshDBPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static ObjectMapper mapper = new ObjectMapper(); - - private SshDataAccessService dataAccessService; - - public void setDataAccessService(SshDataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { - SshConnectionDetails connectionDetails = new SshConnectionDetails(); - //String vnfType = ctx.getAttribute("aai.prefix")+"."+"vnf-type"; - String vnfType = params.get("vnf-type"); - try { - if (!dataAccessService.retrieveConnectionDetails(vnfType, connectionDetails)) { - logger.error("Missing connection details for VNF type: " + vnfType); - throw new APPCException("Missing configuration for " + vnfType + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - } catch(APPCException e) { - String msg = EELFResourceManager.format(Msg.APPC_EXCEPTION, vnfType, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - } catch(SshDataAccessException e) { - String msg = EELFResourceManager.format(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw e; - } catch (JsonProcessingException e) { - String msg = EELFResourceManager.format(Msg.JSON_PROCESSING_EXCEPTION, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(e); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java deleted file mode 100644 index 1c584cdb9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -import org.onap.appc.adapter.ssh.SshAdapter; -import org.onap.appc.adapter.ssh.SshConnection; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.dg.ssh.SshService; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class SshServiceImpl implements SshService { - - private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static final ObjectMapper mapper = new ObjectMapper(); - - private SshAdapter sshAdapter; - - public void setSshAdapter(SshAdapter sshAdapter) { - this.sshAdapter = sshAdapter; - } - - @Override - public void exec(Map params, SvcLogicContext ctx) throws APPCException { - SshConnectionDetails connectionDetails = resolveConnectionDetails(params.get(PARAM_IN_connection_details)); - String command = params.get(PARAM_IN_command); - logger.debug("=> Connecting to SSH server..."); - SshConnection sshConnection = sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(), connectionDetails.getUsername(), connectionDetails.getPassword()); - sshConnection.connect(); - try { - logger.debug("=> Connected to SSH server..."); - logger.debug("=> Running SSH command..."); - long timeout = DEF_timeout; - String stimeout = params.get(PARAM_IN_timeout); - if ((stimeout != null && !stimeout.isEmpty())) { - timeout = Long.parseLong(stimeout); - } - sshConnection.setExecTimeout(timeout); - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - int status = sshConnection.execCommand(command, stdout, stderr); - String stdoutRes = stdout.toString(); - String stderrRes = stderr.toString(); - logger.debug("=> executed SSH command"); - ctx.setAttribute(PARAM_OUT_status, String.format("%01d", status)); - ctx.setAttribute(PARAM_OUT_stdout, stdoutRes); - ctx.setAttribute(PARAM_OUT_stderr, stderrRes); - } finally { - sshConnection.disconnect(); - } - } - - private SshConnectionDetails resolveConnectionDetails(String connectionDetailsStr) throws APPCException { - SshConnectionDetails connectionDetails = null; - try { - connectionDetails = mapper.readValue(connectionDetailsStr, SshConnectionDetails.class); - if (0 == connectionDetails.getPort()) connectionDetails.setPort(DEF_port); - } catch (IOException e) { - throw new APPCException(e); - } - return connectionDetails; - } - - @Override - public void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException { - exec(params, ctx); - int status = Integer.parseInt(ctx.getAttribute(PARAM_OUT_status)); - if(status != DEF_SUCCESS_STATUS) { - StringBuilder errmsg = new StringBuilder(); - errmsg.append("SSH command returned error status [").append(status).append(']'); - String stderr = ctx.getAttribute(PARAM_OUT_stderr); - if((stderr != null) && !stderr.isEmpty()) { - errmsg.append(". Error: [").append(stderr).append(']'); - } - throw new APPCException(errmsg.toString()); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java new file mode 100644 index 000000000..bb232863f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.appc.adapter.ssh.SshAdapterMock; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.adapter.ssh.SshConnectionMock; +import org.onap.appc.dg.ssh.SshService; +import org.onap.appc.dg.ssh.impl.SshServiceImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class SshServiceImplTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testExec() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshService.setSshAdapter(sshAdapterMock); + + System.out.println("=> Executing SSH command [" + command + "]..."); + + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + sshService.exec(params, svcLogicContext); + int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); + String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); + String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); + System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); + + List connectionMocks = sshAdapterMock.getConnectionMocks(); + Assert.assertEquals(1, connectionMocks.size()); + SshConnectionMock connectionMock = connectionMocks.get(0); + Assert.assertNotNull(connectionMock); + Assert.assertEquals(host, connectionMock.getHost()); + Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); + Assert.assertEquals(username, connectionMock.getUsername()); + Assert.assertEquals(password, connectionMock.getPassword()); + Assert.assertEquals(1, connectionMock.getConnectCallCount()); + Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); + List executedCommands = connectionMock.getExecutedCommands(); + Assert.assertEquals(1, executedCommands.size()); + String executedCommand = executedCommands.get(0); + Assert.assertEquals(command, executedCommand); + } + + @Test + public void testExecWithStatusCheck() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshService.setSshAdapter(sshAdapterMock); + + System.out.println("=> Executing SSH command [" + command + "]..."); + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + sshService.execWithStatusCheck(params, svcLogicContext); + int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); + String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); + String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); + System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); + + List connectionMocks = sshAdapterMock.getConnectionMocks(); + Assert.assertEquals(1, connectionMocks.size()); + SshConnectionMock connectionMock = connectionMocks.get(0); + Assert.assertNotNull(connectionMock); + Assert.assertEquals(host, connectionMock.getHost()); + Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); + Assert.assertEquals(username, connectionMock.getUsername()); + Assert.assertEquals(password, connectionMock.getPassword()); + Assert.assertEquals(1, connectionMock.getConnectCallCount()); + Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); + List executedCommands = connectionMock.getExecutedCommands(); + Assert.assertEquals(1, executedCommands.size()); + String executedCommand = executedCommands.get(0); + Assert.assertEquals(command, executedCommand); + } + + /** + * Checks that execWithStatusCheck() throws appropriate exception if execution status != 0. + * + * @throws APPCException + * @throws JsonProcessingException + */ + @Test + public void testExecWithStatusCheckFail() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + int expectedStatus = 2; + String expectedErr = "Test failure"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshAdapterMock.setReturnStatus(expectedStatus); + sshAdapterMock.setReturnStderr(expectedErr); + sshService.setSshAdapter(sshAdapterMock); + + thrown.expect(APPCException.class); + thrown.expectMessage(CoreMatchers.containsString(expectedErr)); + + System.out.println("=> Executing SSH command [" + command + "]..."); + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + // should fail, no need to perform further assertions + sshService.execWithStatusCheck(params, svcLogicContext); + } + + private String createConnectionDetails(String host, String username, String password) throws JsonProcessingException { + SshConnectionDetails connDetails = new SshConnectionDetails(); + connDetails.setHost(host); + connDetails.setUsername(username); + connDetails.setPassword(password); + return mapper.writeValueAsString(connDetails); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java deleted file mode 100644 index bb232863f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.appc.adapter.ssh.SshAdapterMock; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.adapter.ssh.SshConnectionMock; -import org.onap.appc.dg.ssh.SshService; -import org.onap.appc.dg.ssh.impl.SshServiceImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -public class SshServiceImplTest { - - private static final ObjectMapper mapper = new ObjectMapper(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testExec() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshService.setSshAdapter(sshAdapterMock); - - System.out.println("=> Executing SSH command [" + command + "]..."); - - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - sshService.exec(params, svcLogicContext); - int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); - String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); - String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); - System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); - - List connectionMocks = sshAdapterMock.getConnectionMocks(); - Assert.assertEquals(1, connectionMocks.size()); - SshConnectionMock connectionMock = connectionMocks.get(0); - Assert.assertNotNull(connectionMock); - Assert.assertEquals(host, connectionMock.getHost()); - Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); - Assert.assertEquals(username, connectionMock.getUsername()); - Assert.assertEquals(password, connectionMock.getPassword()); - Assert.assertEquals(1, connectionMock.getConnectCallCount()); - Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); - List executedCommands = connectionMock.getExecutedCommands(); - Assert.assertEquals(1, executedCommands.size()); - String executedCommand = executedCommands.get(0); - Assert.assertEquals(command, executedCommand); - } - - @Test - public void testExecWithStatusCheck() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshService.setSshAdapter(sshAdapterMock); - - System.out.println("=> Executing SSH command [" + command + "]..."); - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - sshService.execWithStatusCheck(params, svcLogicContext); - int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); - String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); - String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); - System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); - - List connectionMocks = sshAdapterMock.getConnectionMocks(); - Assert.assertEquals(1, connectionMocks.size()); - SshConnectionMock connectionMock = connectionMocks.get(0); - Assert.assertNotNull(connectionMock); - Assert.assertEquals(host, connectionMock.getHost()); - Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); - Assert.assertEquals(username, connectionMock.getUsername()); - Assert.assertEquals(password, connectionMock.getPassword()); - Assert.assertEquals(1, connectionMock.getConnectCallCount()); - Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); - List executedCommands = connectionMock.getExecutedCommands(); - Assert.assertEquals(1, executedCommands.size()); - String executedCommand = executedCommands.get(0); - Assert.assertEquals(command, executedCommand); - } - - /** - * Checks that execWithStatusCheck() throws appropriate exception if execution status != 0. - * - * @throws APPCException - * @throws JsonProcessingException - */ - @Test - public void testExecWithStatusCheckFail() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - int expectedStatus = 2; - String expectedErr = "Test failure"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshAdapterMock.setReturnStatus(expectedStatus); - sshAdapterMock.setReturnStderr(expectedErr); - sshService.setSshAdapter(sshAdapterMock); - - thrown.expect(APPCException.class); - thrown.expectMessage(CoreMatchers.containsString(expectedErr)); - - System.out.println("=> Executing SSH command [" + command + "]..."); - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - // should fail, no need to perform further assertions - sshService.execWithStatusCheck(params, svcLogicContext); - } - - private String createConnectionDetails(String host, String username, String password) throws JsonProcessingException { - SshConnectionDetails connDetails = new SshConnectionDetails(); - connDetails.setHost(host); - connDetails.setUsername(username); - connDetails.setPassword(password); - return mapper.writeValueAsString(connDetails); - } - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCheckConfigStatus.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCheckConfigStatus.java new file mode 100644 index 000000000..a64d0eb36 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCheckConfigStatus.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +/* TODO: move the dgtest to opensource +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestCheckConfigStatus /* extends AbstractDGTestCase */ { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestCheckConfigStatus.class); + public static String CheckConfigStatusXML = "src/main/resources/xml/APPC_CheckConfigStatus.xml"; + + + +/* + @Test + public void testCheckConfigStatusSuccess() { + try { + + String propertyfileName = "APPC/CheckConfigStatus/CheckConfigStatus_Success.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; + + Map serviceReferences = new HashMap(); + + GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testCheckConfigStatusFailure() { + try { + + String propertyfileName = "APPC/CheckConfigStatus/CheckConfigStatus_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; + + Map serviceReferences = new HashMap(); + + + GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + + @Test + public void testParseErrorLogFail() { + try { + + String propertyfileName = "APPC/CheckConfigStatus/ParseErrorLogFail.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); + + GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //System.out.println("error-message "+ ctx.getAttribute("error-message")); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testParseErrorLogSuccess() { + try { + + String propertyfileName = "APPC/CheckConfigStatus/ParseErrorLogSuccess.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); + + GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testMaxRetries() { + try { + + String propertyfileName = "APPC/CheckConfigStatus/MaxRetries.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); + + GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCommonConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCommonConfig.java new file mode 100644 index 000000000..cd2b9d223 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestCommonConfig.java @@ -0,0 +1,230 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.openecomp.sdnc.config.generator.convert.ConvertNode; +import org.openecomp.sdnc.config.generator.merge.MergeNode; +/* move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestCommonConfig /* extends AbstractDGTestCase */ { + +/* + + public String jsonPath = "src/main/resources/json"; + public String xmlpath = "src/main/resources/xml"; + + @Test + public void testCommonConfig() { + try { + //DGXMLGenerator generator = new DGXMLGenerator(); + //generator.generateXMLFromJSON(jsonPath, xmlpath, null); + + String propertyfileName = "APPC/CommonConfiguration/APPC_method_CommonConfiguration_TC2.properties"; + + String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; + String callGraph1XML = "src/main/resources/xml/APPC_GetConfigParams.xml"; + String callGraph2XML = "src/main/resources/xml/APPC_Configure.xml"; + String callGraph3XML = "src/main/resources/xml/APPC_SetStatus.xml"; + String callGraph4XML = "src/main/resources/xml/APPC_DownloadRestconfConfig.xml"; + String callGraph5XML = "src/main/resources/xml/APPC_GenerateConfig.xml"; + String callGraph6XML = "src/main/resources/xml/APPC_DownloadXmlConfig.xml"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { commonConfigureXML, + callGraph1XML, + callGraph2XML, + callGraph3XML, + callGraph4XML, + callGraph5XML, + callGraph6XML }; + + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); + serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); + + GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + + @Test + public void testGetConfigParamsFailure() { + try { + //DGXMLGenerator generator = new DGXMLGenerator(); + //generator.generateXMLFromJSON(jsonPath, xmlpath, null); + + String propertyfileName = "APPC/CommonConfiguration/GetConfigParamsFail.properties"; + + String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; + + + // Register Call graphs + String injectGraphXmls[] = new String[] { commonConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + @Test + public void testInvalidRequestAction() { + try { + //DGXMLGenerator generator = new DGXMLGenerator(); + //generator.generateXMLFromJSON(jsonPath, xmlpath, null); + + String propertyfileName = "APPC/CommonConfiguration/InvalidRequestAction.properties"; + + String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; + + + // Register Call graphs + String injectGraphXmls[] = new String[] { commonConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Test + public void testCommonConfigISBCTemplateSuccess() { + try { + //DGXMLGenerator generator = new DGXMLGenerator(); + //generator.generateXMLFromJSON(jsonPath, xmlpath, null); + + String propertyfileName = "APPC/CommonConfiguration/ISBCTemplateSuccess.properties"; + + String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; + String callGraph1XML = "src/main/resources/xml/APPC_GetConfigParams.xml"; + String callGraph2XML = "src/main/resources/xml/APPC_Configure.xml"; + String callGraph3XML = "src/main/resources/xml/APPC_SetStatus.xml"; + String callGraph4XML = "src/main/resources/xml/APPC_GenerateTemplateConfig.xml"; + String callGraph5XML = "src/main/resources/xml/APPC_CheckConfigStatus.xml"; + String callGraph6XML = "src/main/resources/xml/APPC_DownloadIsbcConfig.xml"; + String callGraph7XML = "src/main/resources/xml/APPC_UpdateAaiInfo.xml"; + String callGraph8XML = "src/main/resources/xml/APPC_GetVfModuleInfo.xml"; + String callGraph9XML = "src/main/resources/xml/APPC_SaveRunningConfig.xml"; + String callGraph10XML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { commonConfigureXML, + callGraph1XML, + callGraph2XML, + callGraph3XML, + callGraph4XML, + callGraph5XML, + callGraph6XML, + callGraph7XML, + callGraph8XML, + callGraph9XML, + callGraph10XML }; + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + + + + GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } +*/ +} + + + + + diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigurationDocumentRequest.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigurationDocumentRequest.java new file mode 100644 index 000000000..a4592e72e --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigurationDocumentRequest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +/* move to opensource +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestConfigurationDocumentRequest /* extends AbstractDGTestCase */ { + +/* + @Test + public void testSDCMessage() { + try { + String propertyfileName = "SDC-MESSAGE_method_configuration-document-request_TC1.properties"; + + String configurationDocumentRequestXML = "src/main/resources/xml/SDC-MESSAGE_method_configuration-document-request_3.0.0.xml"; + + + // Register Call graphs + String injectGraphXmls[] = new String[] { configurationDocumentRequestXML}; + + Map serviceReferences = new HashMap(); + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + + GraphKey graphKey = new GraphKey("SDC-MESSAGE", null, "configuration-document-request", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + + } +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigure.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigure.java new file mode 100644 index 000000000..052ad7848 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestConfigure.java @@ -0,0 +1,285 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestConfigure /* extends AbstractDGTestCase */ { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestConfigure.class); + public static String ConfigureXML = "src/main/resources/xml/APPC_Configure.xml"; + +/* + @Test + public void testTemplateConfigureSuccess() { + try { + + String propertyfileName = "APPC/Configure/Configure_Success.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testTemplateConfigureFailure() { + try { + + String propertyfileName = "APPC/Configure/Configure_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGetTemplateFailure() { + try { + + String propertyfileName = "APPC/Configure/GetTemplate_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGenerateTemplateConfigFailure() { + try { + + String propertyfileName = "APPC/Configure/GenerateTemplateConfig_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testConfigBlockConfigureSuccess() { + try { + + String propertyfileName = "APPC/Configure/ConfigBlockConfigure_Success.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testConfigBlockConfigureFailure() { + try { + + String propertyfileName = "APPC/Configure/ConfigBlockConfigure_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGenerateConfigFailure() { + try { + + String propertyfileName = "APPC/Configure/GenerateConfig_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { ConfigureXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadCliConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadCliConfig.java new file mode 100644 index 000000000..782493c2d --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadCliConfig.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to opensource +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGMockUtils; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestDownloadCliConfig /* extends AbstractDGTestCase */ { + +/* + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestDownloadIsbcConfig.class); + public static String DownloadCliConfigXML = "src/main/resources/xml/APPC_DownloadCliConfig.xml"; + + @Test + public void testDownloadCliConfigSuccess() { + try { + String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_Success.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; + + Map serviceReferences = new HashMap(); + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //DGMockUtils.printContext(ctx); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testDownloadCliConfigDBFailure() { + try { + + String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_DB_Failure.properties"; + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; + Map serviceReferences = new HashMap(); + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //DGMockUtils.printContext(ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testDownloadCliConfigAdaptorFailure() { + try { + + String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_Adaptor_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; + + Map serviceReferences = new HashMap(); + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //DGMockUtils.printContext(ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadIsbcConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadIsbcConfig.java new file mode 100644 index 000000000..92e39e862 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestDownloadIsbcConfig.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestDownloadIsbcConfig /* extends AbstractDGTestCase */{ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestDownloadIsbcConfig.class); + public static String DownloadIsbcConfigXML = "src/main/resources/xml/APPC_DownloadIsbcConfig.xml"; + +/* + @Test + public void testDownloadIsbcConfigSuccess() { + try { + + String propertyfileName = "APPC/DownloadIsbcConfig/DownloadIsbcConfig_Success.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; + + Map serviceReferences = new HashMap(); + + + + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testConfigFileFailure() { + try { + + String propertyfileName = "APPC/DownloadIsbcConfig/ConfigFile_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; + + Map serviceReferences = new HashMap(); + + + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testPutFailure() { + try { + + String propertyfileName = "APPC/DownloadIsbcConfig/Put_Failure.properties"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; + + Map serviceReferences = new HashMap(); + + + + + GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + + + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateConfig.java new file mode 100644 index 000000000..f329d6b6c --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateConfig.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +import org.apache.sling.testing.mock.osgi.MockOsgi; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestGenerateConfig /* extends AbstractDGTestCase */ { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGenerateConfig.class); + public static String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; + +/* + + @Test + public void testGenerateConfigWithParameters() { + try { + + String propertyfileName = "APPC/GenerateConfig/GenerateConfigWithParams.properties"; + //String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { generateConfigXML }; + + Map serviceReferences = new HashMap(); + + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); + + serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); + + + GraphKey graphKey = new GraphKey("APPC", null, "GenerateConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGenerateConfigWithNoParameters() { + try { + + String propertyfileName = "APPC/GenerateConfig/GenerateConfigNoParams.properties"; + //String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; + + // Register Call graphs + String injectGraphXmls[] = new String[] { generateConfigXML }; + + Map serviceReferences = new HashMap(); + + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); + + serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); + + + GraphKey graphKey = new GraphKey("APPC", null, "GenerateConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateTemplateConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateTemplateConfig.java new file mode 100644 index 000000000..250e4ac30 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGenerateTemplateConfig.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to opensource +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestGenerateTemplateConfig /* extends AbstractDGTestCase */ { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGenerateTemplateConfig.class); +/* + public static String generateConfigXML = "src/main/resources/xml/APPC_GenerateTemplateConfig.xml"; + + @Test + public void testGenerateTemplateConfigWithParameters() { + try { + + String propertyfileName = "APPC/GenerateTemplateConfig/GenerateTemplateConfigWithParams.properties"; + Map serviceReferences = new HashMap(); + + + serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { generateConfigXML }; + + GraphKey graphKey = new GraphKey("APPC", null, "GenerateTemplateConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGenerateTemplateConfigWithNoParameters() { + try { + + String propertyfileName = "APPC/GenerateTemplateConfig/GenerateTemplateConfigNoParams.properties"; + Map serviceReferences = new HashMap(); + + + serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); + serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { generateConfigXML }; + + GraphKey graphKey = new GraphKey("APPC", null, "GenerateTemplateConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetAaiInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetAaiInfo.java new file mode 100644 index 000000000..6674054cb --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetAaiInfo.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class TestGetAaiInfo /* extends AbstractDGTestCase */{ + +/* + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetAaiInfo.class); + public static String getAaiInfoXML = "src/main/resources/xml/APPC_GetAaiInfo.xml"; + + + + + @Test + public void testGetSuccess() { + try { + + + String propertyfileName = "APPC/GetAaiInfo/GetInfoSuccess.properties"; + Map serviceReferences = new HashMap(); + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getAaiInfoXML}; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGetVnfFail() { + try { + + + String propertyfileName = "APPC/GetAaiInfo/GetVnfFail.properties"; + Map serviceReferences = new HashMap(); + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getAaiInfoXML}; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testGetVServerFail() { + try { + + + String propertyfileName = "APPC/GetAaiInfo/GetVServerFail.properties"; + Map serviceReferences = new HashMap(); + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getAaiInfoXML}; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} + + + + diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetConfigParams.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetConfigParams.java new file mode 100644 index 000000000..fd219b013 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetConfigParams.java @@ -0,0 +1,277 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +/* move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class TestGetConfigParams /* extends AbstractDGTestCase */ { + + +/* + + public static String getConfigParamsXML = "src/main/resources/xml/APPC_GetConfigParams.xml"; + + + + @Test + public void testGetConfigParamsWithDefaultTemplate() { + try { + + String propertyfileName = "APPC/GetConfigParams/DefaultTemplate.properties"; + Map serviceReferences = new HashMap(); + + + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + + @Test + public void testGetConfigParamsWithTemplateName() { + try { + + + String propertyfileName = "APPC/GetConfigParams/TemplateName.properties"; + Map serviceReferences = new HashMap(); + + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGetConfigParamsWithCliString() { + try { + + String propertyfileName = "APPC/GetConfigParams/CliString.properties"; + Map serviceReferences = new HashMap(); + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testGetConfigParamsWithCliJson() { + try { + + + String propertyfileName = "APPC/GetConfigParams/CliJson.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGetConfigParamsForRestore() { + try { + String propertyfileName = "APPC/GetConfigParams/Restore.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGetConfigParamsCommonConfigFail() { + try { + String propertyfileName = "APPC/GetConfigParams/CommonConfigFail.properties"; + Map serviceReferences = new HashMap(); + + + serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGetConfigParamsJson2DGContextFail() { + try { + String propertyfileName = "APPC/GetConfigParams/Json2DGContextFail.properties"; + Map serviceReferences = new HashMap(); + + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getConfigParamsXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetDeviceRunningConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetDeviceRunningConfig.java new file mode 100644 index 000000000..48fb106db --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetDeviceRunningConfig.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestGetDeviceRunningConfig /* extends AbstractDGTestCase */ { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetConfigParams.class); +/* + public String jsonPath = "src/main/resources/json"; + public String xmlpath = "src/main/resources/xml"; + + @Test + public void testChefRunningConfigSuccess() { + try { + logger.info("********************************* testChefRunningConfigSuccess *************************************"); + //DGMockUtils.generateXMLFile(jsonPath, xmlpath); + + String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Success.properties"; + + String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; + // Register Call graphs + String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + assertContextWithProperty(ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testChefRunningConfigFailure() { + try { + + logger.info("********************************* testChefRunningConfigFailure *************************************"); + String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Failure.properties"; + + String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; + // Register Call graphs + String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + assertContextWithProperty(ctx); + + //DGMockUtils.printContext(ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testChefRunningConfigOthers() { + try { + logger.info("********************************* testChefRunningConfigOthers *************************************"); + String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Others.properties"; + + String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; + // Register Call graphs + String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + assertContextWithProperty(ctx); + + //DGMockUtils.printContext(ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetVfModuleInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetVfModuleInfo.java new file mode 100644 index 000000000..6bc64f233 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestGetVfModuleInfo.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need move to open source +import org.apache.sling.testing.mock.osgi.MockOsgi; +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestGetVfModuleInfo /* extends AbstractDGTestCase */ { + + //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); + +/* + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetVfModuleInfo.class); + public static String GetVfModuleInfoXML = "src/main/resources/xml/APPC_GetVfModuleInfo.xml"; + + + + @Test + public void testGetVfModuleInfoSuccess() { + try { + + String propertyfileName = "APPC/GetVfModuleInfo/GetVfModuleInfo_Success.properties"; + Map serviceReferences = new HashMap(); + + // Register Call graphs + String injectGraphXmls[] = new String[] { GetVfModuleInfoXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetVfModuleInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + + @Test + public void testGetVfModuleInfoFailure() { + try { + + String propertyfileName = "APPC/GetVfModuleInfo/GetVfModuleInfo_Failure.properties"; + Map serviceReferences = new HashMap(); + + // Register Call graphs + String injectGraphXmls[] = new String[] { GetVfModuleInfoXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "GetVfModuleInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestProcessParameterDefinition.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestProcessParameterDefinition.java new file mode 100644 index 000000000..f638c00c9 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestProcessParameterDefinition.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class TestProcessParameterDefinition /* extends AbstractDGTestCase */ { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestProcessParameterDefinition.class); + public static String getProcessPDXML = "src/main/resources/xml/APPC_ProcessParameterDefinition.xml"; + +/* + + + @Test + public void testProcessPD() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/ProcessPD.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //System.out.println(ctx.getAttribute("tmp.allParams.configuration-parameters")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + + @Test + public void testGetPDFail() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/GetPDFail.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + @Test + public void testNoInstarParams() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/NoInstarParams.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testGetInstarParamsFail() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/GetInstarParamsFail.properties"; + Map serviceReferences = new HashMap(); + + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testMergeParamsFail() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/MergeParamsFail.properties"; + Map serviceReferences = new HashMap(); + + + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + @Test + public void testSaveMdSal() { + try { + + + String propertyfileName = "APPC/ProcessParameterDefinition/SaveMdsalFail.properties"; + Map serviceReferences = new HashMap(); + + + + serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { getProcessPDXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + //System.out.println(ctx.getAttribute("tmp.allParams.configuration-parameters")); + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} + + + + diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestPublishConfiguration.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestPublishConfiguration.java new file mode 100644 index 000000000..b00194d7a --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestPublishConfiguration.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestPublishConfiguration { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestPublishConfiguration.class); + public static String PublishConfigurationXML = "src/main/resources/xml/APPC_PublishConfiguration.xml"; + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSaveRunningConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSaveRunningConfig.java new file mode 100644 index 000000000..c85bfb3f7 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSaveRunningConfig.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to open source +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +import org.apache.sling.testing.mock.osgi.MockOsgi; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestSaveRunningConfig /* extends AbstractDGTestCase */{ + //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSaveRunningConfig.class); + public static String SaveRunningConfigXML = "src/main/resources/xml/APPC_SaveRunningConfig.xml"; + +/* + + + @Test + public void testSaveRunningConfigSuccess() { + try { + + String propertyfileName = "APPC/SaveRunningConfig/SaveRunningConfig_Success.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + + @Test + public void testSaveRunningConfigFailure() { + try { + + String propertyfileName = "APPC/SaveRunningConfig/SaveRunningConfig_Failure.properties"; + Map serviceReferences = new HashMap(); + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Test + public void testSaveRunningUploadConfigFailure() { + try { + + String propertyfileName = "APPC/SaveRunningConfig/UploadConfig_Failure.properties"; + Map serviceReferences = new HashMap(); + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSetStatus.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSetStatus.java new file mode 100644 index 000000000..4f7dc5cf1 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestSetStatus.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* need to move to open source +import org.apache.sling.testing.mock.osgi.MockOsgi; +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestSetStatus /* extends AbstractDGTestCase */ { + //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSetStatus.class); + public static String SetStatusXML = "src/main/resources/xml/APPC_SetStatus.xml"; + + +/* + @Test + public void testSetStatusSuccess() { + try { + + String propertyfileName = "APPC/SetStatus/SetStatus_Success.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SetStatusXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + + @Test + public void testSetStatusAaiFailure() { + try { + + String propertyfileName = "APPC/SetStatus/SetStatus_AaiFailure.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SetStatusXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + @Test + public void testSetStatusFailure() { + try { + + String propertyfileName = "APPC/SetStatus/SetStatus_SaveRunningFailure.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { SetStatusXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + +*/ + +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestUpdateAaiInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestUpdateAaiInfo.java new file mode 100644 index 000000000..05e7fa5cd --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/TestUpdateAaiInfo.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; + + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.dg.mock.instance.MockAaiResource; +import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; +import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* move to open source +import org.apache.sling.testing.mock.osgi.MockOsgi; +import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; +import com.att.sdnctl.dgtestlibrary.DGTestCase; +import com.att.sdnctl.dgtestlibrary.GraphKey; +*/ +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; + + +public class TestUpdateAaiInfo /* extends AbstractDGTestCase */ { + //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestUpdateAaiInfo.class); + public static String UpdateAaiInfoXML = "src/main/resources/xml/APPC_UpdateAaiInfo.xml"; + +/* + + @Test + public void testUpdateAaiInfoSuccess() { + try { + + String propertyfileName = "APPC/UpdateAaiInfo/Update_Success.properties"; + Map serviceReferences = new HashMap(); + + // Register Call graphs + String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; + + + Map resourceReferences = new HashMap(); + + + resourceReferences.put("org.openecomp.sdnc.sli.aai.AAIService", new MockAaiResource()); + + GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + @Test + public void testUpdateAaiInfoFail() { + try { + + String propertyfileName = "APPC/UpdateAaiInfo/Update_Fail.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + @Test + public void testGetVnfcRefFail() { + try { + + String propertyfileName = "APPC/UpdateAaiInfo/GetVnfcRef_Fail.properties"; + Map serviceReferences = new HashMap(); + + + + // Register Call graphs + String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; + + + GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); + DGTestCase tc = new DGTestCase(graphKey); + tc.setInjectGraphXmls(injectGraphXmls); + tc.setServiceReferences(serviceReferences); + tc.setPropertyfileName(propertyfileName); + + Map resourceReferences = new HashMap(); + tc.setResourceReferences(resourceReferences); + + SvcLogicContext ctx = new SvcLogicContext(); + processTestCase(tc, ctx); + + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + +*/ +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockAaiResource.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockAaiResource.java new file mode 100644 index 000000000..9f93b51a9 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockAaiResource.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; + + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import static org.junit.Assert.*; + +public class MockAaiResource implements SvcLogicResource { + + private final static Logger logger = LoggerFactory.getLogger(MockAaiResource.class); + + @Override + public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) throws SvcLogicException { + if (ctx.getAttribute("j").equals("0") && "tmp.aai-data-vm".equals(prefix)) { + logger.info("Mock VM Get query1 called " + ctx.getAttribute("j") ); + + assertEquals(resource, "vserver"); + assertEquals(key, "'vserver-name = $request-parameters.vm[$j].vm-name'"); + + ctx.setAttribute("tmp.aai-data-vm.vserver-id", "vserverid1"); + + ctx.setAttribute("tmp.aai-data-vm.tenant-id", "tenantid1"); + ctx.setAttribute("tmp.aai-data-vm.cloud-owner", "att-aic"); + ctx.setAttribute("tmp.aai-data-vm.cloud-region-id", "cloudregionid1"); + } + else if (ctx.getAttribute("j").equals("1") && "tmp.aai-data-vm".equals(prefix)) { + logger.info("Mock VM Get query1 called " + ctx.getAttribute("j") ); + + assertEquals(resource, "vserver"); + assertEquals(key, "'vserver-name = $request-parameters.vm[$j].vm-name'"); + + ctx.setAttribute("tmp.aai-data-vm.vserver-id", "vserverid2"); + ctx.setAttribute("tmp.aai-data-vm.tenant-id", "tenantid2"); + ctx.setAttribute("tmp.aai-data-vm.cloud-owner", "att-aic"); + ctx.setAttribute("tmp.aai-data-vm.cloud-region-id", "cloudregionid2"); + } + else if ("tmp.aai-data-vnfc".equals(prefix)) { + logger.info("Mock VNFC Get query1 called " ); + + assertEquals(resource, "vnfc"); + assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); + return QueryStatus.NOT_FOUND; + } + return QueryStatus.SUCCESS; + } + + public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock query2 called " + ctx.getAttribute("j")); + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock Save called"); + if (ctx.getAttribute("j").equals("0") && + ctx.getAttribute("k").equals("0") && + "tmp.vnfc-sys-controller".equals(prefix)) { + assertEquals(resource, "vnfc"); + assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); + assertEquals(parms.get("prov-status"), "NVTPROV"); + assertEquals(parms.get("orchestration-status"), "CONFIGURED"); + assertEquals(parms.get("in-maint"), "false"); + assertEquals(parms.get("is-closed-loop"), "false"); + assertEquals(parms.get("vnfc-function-code"), "funccode"); + assertEquals(parms.get("vnfc-type"), "vnfctype"); + assertEquals(parms.get("ipaddress-v4-oam-vip"), "135.1.1.1"); + assertEquals(parms.get("group-notation"), "groupnotation"); + assertEquals(parms.get("relationship-list.relationship[0].related-to"), "vserver"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-key"), "vserver.vserver-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-value"), "vserverid1"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-key"), "tenant.tenant-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-value"), "tenantid1"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-key"), "cloud-region.cloud-owner"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-value"), "att-aic"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-key"), "cloud-region.cloud-region-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-value"), "cloudregionid1"); + assertEquals(parms.get("relationship-list.relationship[1].related-to"), "generic-vnf"); + assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); + assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-value"), "ibcx0001v"); + assertEquals(parms.get("relationship-list.relationship[2].related-to"), "vf-module"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-value"), "ibcx0001v"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-key"), "vf-module.vf-module-id"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-value"), "1"); + } + else if (ctx.getAttribute("j").equals("1") && + ctx.getAttribute("k").equals("0") && + "tmp.vnfc-sys-controller".equals(prefix)) { + assertEquals(resource, "vnfc"); + assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); + assertEquals(parms.get("prov-status"), "NVTPROV"); + assertEquals(parms.get("orchestration-status"), "CONFIGURED"); + assertEquals(parms.get("in-maint"), "false"); + assertEquals(parms.get("is-closed-loop"), "false"); + assertEquals(parms.get("vnfc-function-code"), "funccode1"); + assertEquals(parms.get("vnfc-type"), "vnfctype1"); + assertEquals(parms.get("ipaddress-v4-oam-vip"), "135.2.2.2"); + assertEquals(parms.get("group-notation"), "groupnotation1"); + assertEquals(parms.get("relationship-list.relationship[0].related-to"), "vserver"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-key"), "vserver.vserver-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-value"), "vserverid2"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-key"), "tenant.tenant-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-value"), "tenantid2"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-key"), "cloud-region.cloud-owner"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-value"), "att-aic"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-key"), "cloud-region.cloud-region-id"); + assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-value"), "cloudregionid2"); + assertEquals(parms.get("relationship-list.relationship[1].related-to"), "generic-vnf"); + assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); + assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-value"), "ibcx0001v"); + assertEquals(parms.get("relationship-list.relationship[2].related-to"), "vf-module"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-value"), "ibcx0001v"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-key"), "vf-module.vf-module-id"); + assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-value"), "1"); + } + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + public QueryStatus update(String resource, String key, + Map parms, String prefix, SvcLogicContext ctx) + throws SvcLogicException { + return QueryStatus.SUCCESS; + } + +} + + + + + diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockConfigureNodeExecutor.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockConfigureNodeExecutor.java new file mode 100644 index 000000000..4d2e4c9b4 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockConfigureNodeExecutor.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; + + +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class MockConfigureNodeExecutor implements SvcLogicAdaptor{ + + @Override + public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) { + + if ( "get".equals(key)) { + + if ("135.1.1.1".equals(parameters.get("host") )) { + String fullPathFileName = parameters.get("fullPathFileName"); + if (("SuccessFile").equals(fullPathFileName ) ) + return ConfigStatus.FAILURE; + if (("FailureFile").equals(fullPathFileName ) ) + return ConfigStatus.SUCCESS; + if (("FailureLogFile").equals(fullPathFileName ) ) + return ConfigStatus.SUCCESS; + } + else if ("135.2.2.2".equals(parameters.get("host")) ) { + String fullPathFileName = parameters.get("fullPathFileName"); + if (("SuccessFile").equals(fullPathFileName ) ) + return ConfigStatus.FAILURE; + if (("FailureFile").equals(fullPathFileName ) ) + return ConfigStatus.FAILURE; + } + + return ConfigStatus.SUCCESS; + } + else { + ctx.setAttribute("Status", "Success"); + + return ConfigStatus.SUCCESS; + } + } + + @Override + public ConfigStatus activate(String key, SvcLogicContext ctx) { + return null; + } + + @Override + public ConfigStatus deactivate(String key, SvcLogicContext ctx) { + return null; + } +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java new file mode 100644 index 000000000..aeea98a97 --- /dev/null +++ b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/onap/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class MockSvcLogicJavaPlugin implements SvcLogicJavaPlugin{ + private final static Logger logger = LoggerFactory.getLogger(MockSvcLogicJavaPlugin.class); + public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + public static String OUTPUT_PARAM_STATUS = "status"; + + + public void mountDevice(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ + logger.info("Executed MountDevice Plugin"); + } + + public void downloadDeviceConfiguration(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ + ctx.setAttribute("downloadStatus", "success"); + logger.info("Executed Download Device Configuration Plugin"); + throw new SvcLogicException("failed in Download.."); + } + + public void getCommonConfigInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException, FileNotFoundException, IOException { + logger.info("Mock getCommonConfigInfo Called...."); + } + + public void getConfigFileReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock getConfigFileReference Called...."); + } + + public void getTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock getTemplate Called...."); + } + + public void saveConfigFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock saveConfigFiles called..."); + } + + public void updateUploadConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock updateUploadConfig called..."); + } + + public void savePrepareRelationship(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock savePrepareRelationship called..."); + } + + public void saveConfigBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock saveConfigBlock called..."); + + if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { + logger.info("No params..."); + ctx.setAttribute("file-category", "device_configuration"); + ctx.setAttribute("deviceconfig-file-content", "deviceConfig"); + } else { + logger.info("Config params exist..."); + ctx.setAttribute("file-category", "device_configuration"); + ctx.setAttribute("file-category1", "configuration_block"); + ctx.setAttribute("file-category2", "config_data"); + } + } + + public void saveTemplateConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + logger.info("Mock saveTemplateConfig called..."); + + if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { + logger.info("No params..."); + ctx.setAttribute("file-category", "device_configuration"); + ctx.setAttribute("deviceconfig-file-content", "deviceConfig"); + + } else { + logger.info("Config params exist..."); + ctx.setAttribute("file-category", "device_configuration"); + ctx.setAttribute("file-category1", "config_data"); + } + } +} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCheckConfigStatus.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCheckConfigStatus.java deleted file mode 100644 index a64d0eb36..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCheckConfigStatus.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -/* TODO: move the dgtest to opensource -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TestCheckConfigStatus /* extends AbstractDGTestCase */ { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestCheckConfigStatus.class); - public static String CheckConfigStatusXML = "src/main/resources/xml/APPC_CheckConfigStatus.xml"; - - - -/* - @Test - public void testCheckConfigStatusSuccess() { - try { - - String propertyfileName = "APPC/CheckConfigStatus/CheckConfigStatus_Success.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; - - Map serviceReferences = new HashMap(); - - GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testCheckConfigStatusFailure() { - try { - - String propertyfileName = "APPC/CheckConfigStatus/CheckConfigStatus_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; - - Map serviceReferences = new HashMap(); - - - GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - - @Test - public void testParseErrorLogFail() { - try { - - String propertyfileName = "APPC/CheckConfigStatus/ParseErrorLogFail.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); - - GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //System.out.println("error-message "+ ctx.getAttribute("error-message")); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testParseErrorLogSuccess() { - try { - - String propertyfileName = "APPC/CheckConfigStatus/ParseErrorLogSuccess.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); - - GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testMaxRetries() { - try { - - String propertyfileName = "APPC/CheckConfigStatus/MaxRetries.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { CheckConfigStatusXML }; - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); - - GraphKey graphKey = new GraphKey("APPC", null, "CheckConfigStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCommonConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCommonConfig.java deleted file mode 100644 index cd2b9d223..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestCommonConfig.java +++ /dev/null @@ -1,230 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.openecomp.sdnc.config.generator.convert.ConvertNode; -import org.openecomp.sdnc.config.generator.merge.MergeNode; -/* move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestCommonConfig /* extends AbstractDGTestCase */ { - -/* - - public String jsonPath = "src/main/resources/json"; - public String xmlpath = "src/main/resources/xml"; - - @Test - public void testCommonConfig() { - try { - //DGXMLGenerator generator = new DGXMLGenerator(); - //generator.generateXMLFromJSON(jsonPath, xmlpath, null); - - String propertyfileName = "APPC/CommonConfiguration/APPC_method_CommonConfiguration_TC2.properties"; - - String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; - String callGraph1XML = "src/main/resources/xml/APPC_GetConfigParams.xml"; - String callGraph2XML = "src/main/resources/xml/APPC_Configure.xml"; - String callGraph3XML = "src/main/resources/xml/APPC_SetStatus.xml"; - String callGraph4XML = "src/main/resources/xml/APPC_DownloadRestconfConfig.xml"; - String callGraph5XML = "src/main/resources/xml/APPC_GenerateConfig.xml"; - String callGraph6XML = "src/main/resources/xml/APPC_DownloadXmlConfig.xml"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { commonConfigureXML, - callGraph1XML, - callGraph2XML, - callGraph3XML, - callGraph4XML, - callGraph5XML, - callGraph6XML }; - - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); - serviceReferences.put("org.onap.appc.ccadaptor.ConfigComponentAdaptor", new MockConfigureNodeExecutor()); - - GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - - @Test - public void testGetConfigParamsFailure() { - try { - //DGXMLGenerator generator = new DGXMLGenerator(); - //generator.generateXMLFromJSON(jsonPath, xmlpath, null); - - String propertyfileName = "APPC/CommonConfiguration/GetConfigParamsFail.properties"; - - String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; - - - // Register Call graphs - String injectGraphXmls[] = new String[] { commonConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - @Test - public void testInvalidRequestAction() { - try { - //DGXMLGenerator generator = new DGXMLGenerator(); - //generator.generateXMLFromJSON(jsonPath, xmlpath, null); - - String propertyfileName = "APPC/CommonConfiguration/InvalidRequestAction.properties"; - - String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; - - - // Register Call graphs - String injectGraphXmls[] = new String[] { commonConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @Test - public void testCommonConfigISBCTemplateSuccess() { - try { - //DGXMLGenerator generator = new DGXMLGenerator(); - //generator.generateXMLFromJSON(jsonPath, xmlpath, null); - - String propertyfileName = "APPC/CommonConfiguration/ISBCTemplateSuccess.properties"; - - String commonConfigureXML = "src/main/resources/xml/APPC_CommonConfiguration.xml"; - String callGraph1XML = "src/main/resources/xml/APPC_GetConfigParams.xml"; - String callGraph2XML = "src/main/resources/xml/APPC_Configure.xml"; - String callGraph3XML = "src/main/resources/xml/APPC_SetStatus.xml"; - String callGraph4XML = "src/main/resources/xml/APPC_GenerateTemplateConfig.xml"; - String callGraph5XML = "src/main/resources/xml/APPC_CheckConfigStatus.xml"; - String callGraph6XML = "src/main/resources/xml/APPC_DownloadIsbcConfig.xml"; - String callGraph7XML = "src/main/resources/xml/APPC_UpdateAaiInfo.xml"; - String callGraph8XML = "src/main/resources/xml/APPC_GetVfModuleInfo.xml"; - String callGraph9XML = "src/main/resources/xml/APPC_SaveRunningConfig.xml"; - String callGraph10XML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { commonConfigureXML, - callGraph1XML, - callGraph2XML, - callGraph3XML, - callGraph4XML, - callGraph5XML, - callGraph6XML, - callGraph7XML, - callGraph8XML, - callGraph9XML, - callGraph10XML }; - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - - - - GraphKey graphKey = new GraphKey("APPC", null, "CommonConfiguration", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } -*/ -} - - - - - diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigurationDocumentRequest.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigurationDocumentRequest.java deleted file mode 100644 index a4592e72e..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigurationDocumentRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -/* move to opensource -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestConfigurationDocumentRequest /* extends AbstractDGTestCase */ { - -/* - @Test - public void testSDCMessage() { - try { - String propertyfileName = "SDC-MESSAGE_method_configuration-document-request_TC1.properties"; - - String configurationDocumentRequestXML = "src/main/resources/xml/SDC-MESSAGE_method_configuration-document-request_3.0.0.xml"; - - - // Register Call graphs - String injectGraphXmls[] = new String[] { configurationDocumentRequestXML}; - - Map serviceReferences = new HashMap(); - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode",new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - - GraphKey graphKey = new GraphKey("SDC-MESSAGE", null, "configuration-document-request", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - - } -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigure.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigure.java deleted file mode 100644 index 052ad7848..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestConfigure.java +++ /dev/null @@ -1,285 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TestConfigure /* extends AbstractDGTestCase */ { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestConfigure.class); - public static String ConfigureXML = "src/main/resources/xml/APPC_Configure.xml"; - -/* - @Test - public void testTemplateConfigureSuccess() { - try { - - String propertyfileName = "APPC/Configure/Configure_Success.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testTemplateConfigureFailure() { - try { - - String propertyfileName = "APPC/Configure/Configure_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGetTemplateFailure() { - try { - - String propertyfileName = "APPC/Configure/GetTemplate_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGenerateTemplateConfigFailure() { - try { - - String propertyfileName = "APPC/Configure/GenerateTemplateConfig_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testConfigBlockConfigureSuccess() { - try { - - String propertyfileName = "APPC/Configure/ConfigBlockConfigure_Success.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testConfigBlockConfigureFailure() { - try { - - String propertyfileName = "APPC/Configure/ConfigBlockConfigure_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGenerateConfigFailure() { - try { - - String propertyfileName = "APPC/Configure/GenerateConfig_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { ConfigureXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "Configure", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadCliConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadCliConfig.java deleted file mode 100644 index 782493c2d..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadCliConfig.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to opensource -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGMockUtils; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestDownloadCliConfig /* extends AbstractDGTestCase */ { - -/* - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestDownloadIsbcConfig.class); - public static String DownloadCliConfigXML = "src/main/resources/xml/APPC_DownloadCliConfig.xml"; - - @Test - public void testDownloadCliConfigSuccess() { - try { - String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_Success.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; - - Map serviceReferences = new HashMap(); - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //DGMockUtils.printContext(ctx); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testDownloadCliConfigDBFailure() { - try { - - String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_DB_Failure.properties"; - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; - Map serviceReferences = new HashMap(); - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //DGMockUtils.printContext(ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testDownloadCliConfigAdaptorFailure() { - try { - - String propertyfileName = "APPC/DownloadCliConfig/DownloadCliConfig_Adaptor_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadCliConfigXML }; - - Map serviceReferences = new HashMap(); - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadCliConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //DGMockUtils.printContext(ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadIsbcConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadIsbcConfig.java deleted file mode 100644 index 92e39e862..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestDownloadIsbcConfig.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TestDownloadIsbcConfig /* extends AbstractDGTestCase */{ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestDownloadIsbcConfig.class); - public static String DownloadIsbcConfigXML = "src/main/resources/xml/APPC_DownloadIsbcConfig.xml"; - -/* - @Test - public void testDownloadIsbcConfigSuccess() { - try { - - String propertyfileName = "APPC/DownloadIsbcConfig/DownloadIsbcConfig_Success.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; - - Map serviceReferences = new HashMap(); - - - - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testConfigFileFailure() { - try { - - String propertyfileName = "APPC/DownloadIsbcConfig/ConfigFile_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; - - Map serviceReferences = new HashMap(); - - - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testPutFailure() { - try { - - String propertyfileName = "APPC/DownloadIsbcConfig/Put_Failure.properties"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { DownloadIsbcConfigXML }; - - Map serviceReferences = new HashMap(); - - - - - GraphKey graphKey = new GraphKey("APPC", null, "DownloadIsbcConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - - - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateConfig.java deleted file mode 100644 index f329d6b6c..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateConfig.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -import org.apache.sling.testing.mock.osgi.MockOsgi; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestGenerateConfig /* extends AbstractDGTestCase */ { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGenerateConfig.class); - public static String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; - -/* - - @Test - public void testGenerateConfigWithParameters() { - try { - - String propertyfileName = "APPC/GenerateConfig/GenerateConfigWithParams.properties"; - //String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { generateConfigXML }; - - Map serviceReferences = new HashMap(); - - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); - - serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); - - - GraphKey graphKey = new GraphKey("APPC", null, "GenerateConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGenerateConfigWithNoParameters() { - try { - - String propertyfileName = "APPC/GenerateConfig/GenerateConfigNoParams.properties"; - //String generateConfigXML = "src/main/resources/xml/APPC_GenerateConfig.xml"; - - // Register Call graphs - String injectGraphXmls[] = new String[] { generateConfigXML }; - - Map serviceReferences = new HashMap(); - - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - //serviceReferences.put("com.att.appc.config.generator.node.ConfigResourceNode", new MockConfigResourceNode()); - - serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); - - - GraphKey graphKey = new GraphKey("APPC", null, "GenerateConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateTemplateConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateTemplateConfig.java deleted file mode 100644 index 250e4ac30..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGenerateTemplateConfig.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to opensource -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestGenerateTemplateConfig /* extends AbstractDGTestCase */ { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGenerateTemplateConfig.class); -/* - public static String generateConfigXML = "src/main/resources/xml/APPC_GenerateTemplateConfig.xml"; - - @Test - public void testGenerateTemplateConfigWithParameters() { - try { - - String propertyfileName = "APPC/GenerateTemplateConfig/GenerateTemplateConfigWithParams.properties"; - Map serviceReferences = new HashMap(); - - - serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { generateConfigXML }; - - GraphKey graphKey = new GraphKey("APPC", null, "GenerateTemplateConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGenerateTemplateConfigWithNoParameters() { - try { - - String propertyfileName = "APPC/GenerateTemplateConfig/GenerateTemplateConfigNoParams.properties"; - Map serviceReferences = new HashMap(); - - - serviceReferences.put("org.onap.appc.data.services.node.ConfigResourceNode", new MockSvcLogicJavaPlugin()); - serviceReferences.put("org.openecomp.sdnc.config.generator.merge.MergeNode", new org.openecomp.sdnc.config.generator.merge.MergeNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { generateConfigXML }; - - GraphKey graphKey = new GraphKey("APPC", null, "GenerateTemplateConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetAaiInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetAaiInfo.java deleted file mode 100644 index 6674054cb..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetAaiInfo.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class TestGetAaiInfo /* extends AbstractDGTestCase */{ - -/* - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetAaiInfo.class); - public static String getAaiInfoXML = "src/main/resources/xml/APPC_GetAaiInfo.xml"; - - - - - @Test - public void testGetSuccess() { - try { - - - String propertyfileName = "APPC/GetAaiInfo/GetInfoSuccess.properties"; - Map serviceReferences = new HashMap(); - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getAaiInfoXML}; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGetVnfFail() { - try { - - - String propertyfileName = "APPC/GetAaiInfo/GetVnfFail.properties"; - Map serviceReferences = new HashMap(); - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getAaiInfoXML}; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testGetVServerFail() { - try { - - - String propertyfileName = "APPC/GetAaiInfo/GetVServerFail.properties"; - Map serviceReferences = new HashMap(); - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getAaiInfoXML}; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} - - - - diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetConfigParams.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetConfigParams.java deleted file mode 100644 index fd219b013..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetConfigParams.java +++ /dev/null @@ -1,277 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -/* move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class TestGetConfigParams /* extends AbstractDGTestCase */ { - - -/* - - public static String getConfigParamsXML = "src/main/resources/xml/APPC_GetConfigParams.xml"; - - - - @Test - public void testGetConfigParamsWithDefaultTemplate() { - try { - - String propertyfileName = "APPC/GetConfigParams/DefaultTemplate.properties"; - Map serviceReferences = new HashMap(); - - - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - - @Test - public void testGetConfigParamsWithTemplateName() { - try { - - - String propertyfileName = "APPC/GetConfigParams/TemplateName.properties"; - Map serviceReferences = new HashMap(); - - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGetConfigParamsWithCliString() { - try { - - String propertyfileName = "APPC/GetConfigParams/CliString.properties"; - Map serviceReferences = new HashMap(); - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testGetConfigParamsWithCliJson() { - try { - - - String propertyfileName = "APPC/GetConfigParams/CliJson.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGetConfigParamsForRestore() { - try { - String propertyfileName = "APPC/GetConfigParams/Restore.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGetConfigParamsCommonConfigFail() { - try { - String propertyfileName = "APPC/GetConfigParams/CommonConfigFail.properties"; - Map serviceReferences = new HashMap(); - - - serviceReferences.put("org.openecomp.sdnc.config.generator.convert.ConvertNode", new org.openecomp.sdnc.config.generator.convert.ConvertNode()); - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGetConfigParamsJson2DGContextFail() { - try { - String propertyfileName = "APPC/GetConfigParams/Json2DGContextFail.properties"; - Map serviceReferences = new HashMap(); - - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getConfigParamsXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetConfigParams", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetDeviceRunningConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetDeviceRunningConfig.java deleted file mode 100644 index 48fb106db..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetDeviceRunningConfig.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestGetDeviceRunningConfig /* extends AbstractDGTestCase */ { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetConfigParams.class); -/* - public String jsonPath = "src/main/resources/json"; - public String xmlpath = "src/main/resources/xml"; - - @Test - public void testChefRunningConfigSuccess() { - try { - logger.info("********************************* testChefRunningConfigSuccess *************************************"); - //DGMockUtils.generateXMLFile(jsonPath, xmlpath); - - String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Success.properties"; - - String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; - // Register Call graphs - String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - assertContextWithProperty(ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testChefRunningConfigFailure() { - try { - - logger.info("********************************* testChefRunningConfigFailure *************************************"); - String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Failure.properties"; - - String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; - // Register Call graphs - String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - assertContextWithProperty(ctx); - - //DGMockUtils.printContext(ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testChefRunningConfigOthers() { - try { - logger.info("********************************* testChefRunningConfigOthers *************************************"); - String propertyfileName = "APPC/GetDeviceRunningConfig/Chef_Others.properties"; - - String getDeviceRunningConfigXML = "src/main/resources/xml/APPC_GetDeviceRunningConfig.xml"; - // Register Call graphs - String injectGraphXmls[] = new String[] { getDeviceRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetDeviceRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - assertContextWithProperty(ctx); - - //DGMockUtils.printContext(ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetVfModuleInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetVfModuleInfo.java deleted file mode 100644 index 6bc64f233..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestGetVfModuleInfo.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need move to open source -import org.apache.sling.testing.mock.osgi.MockOsgi; -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestGetVfModuleInfo /* extends AbstractDGTestCase */ { - - //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); - -/* - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestGetVfModuleInfo.class); - public static String GetVfModuleInfoXML = "src/main/resources/xml/APPC_GetVfModuleInfo.xml"; - - - - @Test - public void testGetVfModuleInfoSuccess() { - try { - - String propertyfileName = "APPC/GetVfModuleInfo/GetVfModuleInfo_Success.properties"; - Map serviceReferences = new HashMap(); - - // Register Call graphs - String injectGraphXmls[] = new String[] { GetVfModuleInfoXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetVfModuleInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - - @Test - public void testGetVfModuleInfoFailure() { - try { - - String propertyfileName = "APPC/GetVfModuleInfo/GetVfModuleInfo_Failure.properties"; - Map serviceReferences = new HashMap(); - - // Register Call graphs - String injectGraphXmls[] = new String[] { GetVfModuleInfoXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "GetVfModuleInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestProcessParameterDefinition.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestProcessParameterDefinition.java deleted file mode 100644 index f638c00c9..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestProcessParameterDefinition.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class TestProcessParameterDefinition /* extends AbstractDGTestCase */ { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestProcessParameterDefinition.class); - public static String getProcessPDXML = "src/main/resources/xml/APPC_ProcessParameterDefinition.xml"; - -/* - - - @Test - public void testProcessPD() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/ProcessPD.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //System.out.println(ctx.getAttribute("tmp.allParams.configuration-parameters")); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - @Test - public void testGetPDFail() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/GetPDFail.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - @Test - public void testNoInstarParams() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/NoInstarParams.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testGetInstarParamsFail() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/GetInstarParamsFail.properties"; - Map serviceReferences = new HashMap(); - - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testMergeParamsFail() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/MergeParamsFail.properties"; - Map serviceReferences = new HashMap(); - - - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Test - public void testSaveMdSal() { - try { - - - String propertyfileName = "APPC/ProcessParameterDefinition/SaveMdsalFail.properties"; - Map serviceReferences = new HashMap(); - - - - serviceReferences.put("org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode", new org.openecomp.sdnc.config.params.parser.PropertyDefinitionNode()); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { getProcessPDXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "ProcessParameterDefinition", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - //System.out.println(ctx.getAttribute("tmp.allParams.configuration-parameters")); - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} - - - - diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestPublishConfiguration.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestPublishConfiguration.java deleted file mode 100644 index b00194d7a..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestPublishConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestPublishConfiguration { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestPublishConfiguration.class); - public static String PublishConfigurationXML = "src/main/resources/xml/APPC_PublishConfiguration.xml"; - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSaveRunningConfig.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSaveRunningConfig.java deleted file mode 100644 index c85bfb3f7..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSaveRunningConfig.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to open source -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -import org.apache.sling.testing.mock.osgi.MockOsgi; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestSaveRunningConfig /* extends AbstractDGTestCase */{ - //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSaveRunningConfig.class); - public static String SaveRunningConfigXML = "src/main/resources/xml/APPC_SaveRunningConfig.xml"; - -/* - - - @Test - public void testSaveRunningConfigSuccess() { - try { - - String propertyfileName = "APPC/SaveRunningConfig/SaveRunningConfig_Success.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - - @Test - public void testSaveRunningConfigFailure() { - try { - - String propertyfileName = "APPC/SaveRunningConfig/SaveRunningConfig_Failure.properties"; - Map serviceReferences = new HashMap(); - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @Test - public void testSaveRunningUploadConfigFailure() { - try { - - String propertyfileName = "APPC/SaveRunningConfig/UploadConfig_Failure.properties"; - Map serviceReferences = new HashMap(); - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SaveRunningConfigXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SaveRunningConfig", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSetStatus.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSetStatus.java deleted file mode 100644 index 4f7dc5cf1..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestSetStatus.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* need to move to open source -import org.apache.sling.testing.mock.osgi.MockOsgi; -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestSetStatus /* extends AbstractDGTestCase */ { - //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSetStatus.class); - public static String SetStatusXML = "src/main/resources/xml/APPC_SetStatus.xml"; - - -/* - @Test - public void testSetStatusSuccess() { - try { - - String propertyfileName = "APPC/SetStatus/SetStatus_Success.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SetStatusXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - - @Test - public void testSetStatusAaiFailure() { - try { - - String propertyfileName = "APPC/SetStatus/SetStatus_AaiFailure.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SetStatusXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - @Test - public void testSetStatusFailure() { - try { - - String propertyfileName = "APPC/SetStatus/SetStatus_SaveRunningFailure.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { SetStatusXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "SetStatus", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - -*/ - -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestUpdateAaiInfo.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestUpdateAaiInfo.java deleted file mode 100644 index 05e7fa5cd..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/TestUpdateAaiInfo.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg; - - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.dg.mock.instance.MockAaiResource; -import org.onap.appc.dg.mock.instance.MockConfigureNodeExecutor; -import org.onap.appc.dg.mock.instance.MockSvcLogicJavaPlugin; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -/* move to open source -import org.apache.sling.testing.mock.osgi.MockOsgi; -import com.att.sdnctl.dgtestlibrary.AbstractDGTestCase; -import com.att.sdnctl.dgtestlibrary.DGTestCase; -import com.att.sdnctl.dgtestlibrary.GraphKey; -*/ -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicAdaptorFactory; - - -public class TestUpdateAaiInfo /* extends AbstractDGTestCase */ { - //private final static Logger logger = LoggerFactory.getLogger(TestGetParams.class); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestUpdateAaiInfo.class); - public static String UpdateAaiInfoXML = "src/main/resources/xml/APPC_UpdateAaiInfo.xml"; - -/* - - @Test - public void testUpdateAaiInfoSuccess() { - try { - - String propertyfileName = "APPC/UpdateAaiInfo/Update_Success.properties"; - Map serviceReferences = new HashMap(); - - // Register Call graphs - String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; - - - Map resourceReferences = new HashMap(); - - - resourceReferences.put("org.openecomp.sdnc.sli.aai.AAIService", new MockAaiResource()); - - GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - @Test - public void testUpdateAaiInfoFail() { - try { - - String propertyfileName = "APPC/UpdateAaiInfo/Update_Fail.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - - @Test - public void testGetVnfcRefFail() { - try { - - String propertyfileName = "APPC/UpdateAaiInfo/GetVnfcRef_Fail.properties"; - Map serviceReferences = new HashMap(); - - - - // Register Call graphs - String injectGraphXmls[] = new String[] { UpdateAaiInfoXML }; - - - GraphKey graphKey = new GraphKey("APPC", null, "UpdateAaiInfo", null); - DGTestCase tc = new DGTestCase(graphKey); - tc.setInjectGraphXmls(injectGraphXmls); - tc.setServiceReferences(serviceReferences); - tc.setPropertyfileName(propertyfileName); - - Map resourceReferences = new HashMap(); - tc.setResourceReferences(resourceReferences); - - SvcLogicContext ctx = new SvcLogicContext(); - processTestCase(tc, ctx); - - - - } catch (Exception e) { - e.printStackTrace(); - } - - } - -*/ -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockAaiResource.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockAaiResource.java deleted file mode 100644 index 9f93b51a9..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockAaiResource.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; - - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import static org.junit.Assert.*; - -public class MockAaiResource implements SvcLogicResource { - - private final static Logger logger = LoggerFactory.getLogger(MockAaiResource.class); - - @Override - public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) throws SvcLogicException { - if (ctx.getAttribute("j").equals("0") && "tmp.aai-data-vm".equals(prefix)) { - logger.info("Mock VM Get query1 called " + ctx.getAttribute("j") ); - - assertEquals(resource, "vserver"); - assertEquals(key, "'vserver-name = $request-parameters.vm[$j].vm-name'"); - - ctx.setAttribute("tmp.aai-data-vm.vserver-id", "vserverid1"); - - ctx.setAttribute("tmp.aai-data-vm.tenant-id", "tenantid1"); - ctx.setAttribute("tmp.aai-data-vm.cloud-owner", "att-aic"); - ctx.setAttribute("tmp.aai-data-vm.cloud-region-id", "cloudregionid1"); - } - else if (ctx.getAttribute("j").equals("1") && "tmp.aai-data-vm".equals(prefix)) { - logger.info("Mock VM Get query1 called " + ctx.getAttribute("j") ); - - assertEquals(resource, "vserver"); - assertEquals(key, "'vserver-name = $request-parameters.vm[$j].vm-name'"); - - ctx.setAttribute("tmp.aai-data-vm.vserver-id", "vserverid2"); - ctx.setAttribute("tmp.aai-data-vm.tenant-id", "tenantid2"); - ctx.setAttribute("tmp.aai-data-vm.cloud-owner", "att-aic"); - ctx.setAttribute("tmp.aai-data-vm.cloud-region-id", "cloudregionid2"); - } - else if ("tmp.aai-data-vnfc".equals(prefix)) { - logger.info("Mock VNFC Get query1 called " ); - - assertEquals(resource, "vnfc"); - assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); - return QueryStatus.NOT_FOUND; - } - return QueryStatus.SUCCESS; - } - - public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock query2 called " + ctx.getAttribute("j")); - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock Save called"); - if (ctx.getAttribute("j").equals("0") && - ctx.getAttribute("k").equals("0") && - "tmp.vnfc-sys-controller".equals(prefix)) { - assertEquals(resource, "vnfc"); - assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); - assertEquals(parms.get("prov-status"), "NVTPROV"); - assertEquals(parms.get("orchestration-status"), "CONFIGURED"); - assertEquals(parms.get("in-maint"), "false"); - assertEquals(parms.get("is-closed-loop"), "false"); - assertEquals(parms.get("vnfc-function-code"), "funccode"); - assertEquals(parms.get("vnfc-type"), "vnfctype"); - assertEquals(parms.get("ipaddress-v4-oam-vip"), "135.1.1.1"); - assertEquals(parms.get("group-notation"), "groupnotation"); - assertEquals(parms.get("relationship-list.relationship[0].related-to"), "vserver"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-key"), "vserver.vserver-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-value"), "vserverid1"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-key"), "tenant.tenant-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-value"), "tenantid1"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-key"), "cloud-region.cloud-owner"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-value"), "att-aic"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-key"), "cloud-region.cloud-region-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-value"), "cloudregionid1"); - assertEquals(parms.get("relationship-list.relationship[1].related-to"), "generic-vnf"); - assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); - assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-value"), "ibcx0001v"); - assertEquals(parms.get("relationship-list.relationship[2].related-to"), "vf-module"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-value"), "ibcx0001v"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-key"), "vf-module.vf-module-id"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-value"), "1"); - } - else if (ctx.getAttribute("j").equals("1") && - ctx.getAttribute("k").equals("0") && - "tmp.vnfc-sys-controller".equals(prefix)) { - assertEquals(resource, "vnfc"); - assertEquals(key, "'vnfc-name = $request-parameters.vm[$j].vnfc[$k].vnfc-name'"); - assertEquals(parms.get("prov-status"), "NVTPROV"); - assertEquals(parms.get("orchestration-status"), "CONFIGURED"); - assertEquals(parms.get("in-maint"), "false"); - assertEquals(parms.get("is-closed-loop"), "false"); - assertEquals(parms.get("vnfc-function-code"), "funccode1"); - assertEquals(parms.get("vnfc-type"), "vnfctype1"); - assertEquals(parms.get("ipaddress-v4-oam-vip"), "135.2.2.2"); - assertEquals(parms.get("group-notation"), "groupnotation1"); - assertEquals(parms.get("relationship-list.relationship[0].related-to"), "vserver"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-key"), "vserver.vserver-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[0].relationship-value"), "vserverid2"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-key"), "tenant.tenant-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[1].relationship-value"), "tenantid2"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-key"), "cloud-region.cloud-owner"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[2].relationship-value"), "att-aic"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-key"), "cloud-region.cloud-region-id"); - assertEquals(parms.get("relationship-list.relationship[0].relationship-data[3].relationship-value"), "cloudregionid2"); - assertEquals(parms.get("relationship-list.relationship[1].related-to"), "generic-vnf"); - assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); - assertEquals(parms.get("relationship-list.relationship[1].relationship-data[0].relationship-value"), "ibcx0001v"); - assertEquals(parms.get("relationship-list.relationship[2].related-to"), "vf-module"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-key"), "generic-vnf.vnf-id"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[0].relationship-value"), "ibcx0001v"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-key"), "vf-module.vf-module-id"); - assertEquals(parms.get("relationship-list.relationship[2].relationship-data[1].relationship-value"), "1"); - } - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - @Override - public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - public QueryStatus update(String resource, String key, - Map parms, String prefix, SvcLogicContext ctx) - throws SvcLogicException { - return QueryStatus.SUCCESS; - } - -} - - - - - diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockConfigureNodeExecutor.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockConfigureNodeExecutor.java deleted file mode 100644 index 4d2e4c9b4..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockConfigureNodeExecutor.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; - - -import java.util.Map; - -import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class MockConfigureNodeExecutor implements SvcLogicAdaptor{ - - @Override - public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) { - - if ( "get".equals(key)) { - - if ("135.1.1.1".equals(parameters.get("host") )) { - String fullPathFileName = parameters.get("fullPathFileName"); - if (("SuccessFile").equals(fullPathFileName ) ) - return ConfigStatus.FAILURE; - if (("FailureFile").equals(fullPathFileName ) ) - return ConfigStatus.SUCCESS; - if (("FailureLogFile").equals(fullPathFileName ) ) - return ConfigStatus.SUCCESS; - } - else if ("135.2.2.2".equals(parameters.get("host")) ) { - String fullPathFileName = parameters.get("fullPathFileName"); - if (("SuccessFile").equals(fullPathFileName ) ) - return ConfigStatus.FAILURE; - if (("FailureFile").equals(fullPathFileName ) ) - return ConfigStatus.FAILURE; - } - - return ConfigStatus.SUCCESS; - } - else { - ctx.setAttribute("Status", "Success"); - - return ConfigStatus.SUCCESS; - } - } - - @Override - public ConfigStatus activate(String key, SvcLogicContext ctx) { - return null; - } - - @Override - public ConfigStatus deactivate(String key, SvcLogicContext ctx) { - return null; - } -} diff --git a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java b/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java deleted file mode 100644 index aeea98a97..000000000 --- a/appc-directed-graph/appc-dgraph/provider/src/test/java/org/openecomp/appc/dg/mock/instance/MockSvcLogicJavaPlugin.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.dg.mock.instance; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class MockSvcLogicJavaPlugin implements SvcLogicJavaPlugin{ - private final static Logger logger = LoggerFactory.getLogger(MockSvcLogicJavaPlugin.class); - public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - public static String OUTPUT_PARAM_STATUS = "status"; - - - public void mountDevice(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ - logger.info("Executed MountDevice Plugin"); - } - - public void downloadDeviceConfiguration(Map inParams, SvcLogicContext ctx) throws SvcLogicException{ - ctx.setAttribute("downloadStatus", "success"); - logger.info("Executed Download Device Configuration Plugin"); - throw new SvcLogicException("failed in Download.."); - } - - public void getCommonConfigInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException, FileNotFoundException, IOException { - logger.info("Mock getCommonConfigInfo Called...."); - } - - public void getConfigFileReference(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock getConfigFileReference Called...."); - } - - public void getTemplate(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock getTemplate Called...."); - } - - public void saveConfigFiles(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock saveConfigFiles called..."); - } - - public void updateUploadConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock updateUploadConfig called..."); - } - - public void savePrepareRelationship(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock savePrepareRelationship called..."); - } - - public void saveConfigBlock(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock saveConfigBlock called..."); - - if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { - logger.info("No params..."); - ctx.setAttribute("file-category", "device_configuration"); - ctx.setAttribute("deviceconfig-file-content", "deviceConfig"); - } else { - logger.info("Config params exist..."); - ctx.setAttribute("file-category", "device_configuration"); - ctx.setAttribute("file-category1", "configuration_block"); - ctx.setAttribute("file-category2", "config_data"); - } - } - - public void saveTemplateConfig(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - logger.info("Mock saveTemplateConfig called..."); - - if (StringUtils.isBlank(ctx.getAttribute("configuration-params"))) { - logger.info("No params..."); - ctx.setAttribute("file-category", "device_configuration"); - ctx.setAttribute("deviceconfig-file-content", "deviceConfig"); - - } else { - logger.info("Config params exist..."); - ctx.setAttribute("file-category", "device_configuration"); - ctx.setAttribute("file-category1", "config_data"); - } - } -} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGLoaderActivator.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGLoaderActivator.java new file mode 100644 index 000000000..99f7f8b6c --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGLoaderActivator.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdnc.dg.loader; + +import java.util.LinkedList; +import java.util.List; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DGLoaderActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DGLoaderActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLActivate.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLActivate.java new file mode 100644 index 000000000..6af447742 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLActivate.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +public class DGXMLActivate { + + private final static Logger logger = LoggerFactory.getLogger(DGXMLLoadNActivate.class); + private final SvcLogicStore store; + public static String STRING_ENCODING = "utf-8"; + + public DGXMLActivate(String propfile) throws Exception{ + if(StringUtils.isBlank(propfile)){ + throw new Exception(propfile + " Profile file is not defined"); + } + this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); + } + + protected DGXMLActivate(SvcLogicStore store) { + this.store = store; + } + + + public void activateDg(String activateFilePath) throws Exception { + logger.info("******************** Activating DG into Database *****************************"); + try { + List errors = new ArrayList(); + if(this.store != null){ + File activateFile = new File(activateFilePath); + if(activateFile != null && activateFile.isFile()){ + List fileLines = FileUtils.readLines(activateFile,STRING_ENCODING); + if(fileLines != null ){ + for (String line : fileLines) { + if(line != null && ! line.trim().startsWith("#")){ + String lineArray[] = line.trim().split(":"); + try { + if(lineArray != null && lineArray.length >= 4){ + String module = lineArray[0]; + String rpc = lineArray[1]; + String version = lineArray[2]; + String mode = lineArray[3]; + if(StringUtils.isNotBlank(module) && StringUtils.isNotBlank(rpc) + && StringUtils.isNotBlank(version) && StringUtils.isNotBlank(mode)){ + logger.info("Activating DG :" + line); + SvcLogicGraph graph = this.store.fetch(module, rpc, version, mode); + if(graph != null){ + logger.info("Found Graph :" + line + " Activating ..."); + this.store.activate(graph); + }else{ + throw new Exception("Failed to fetch from Database"); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + errors.add("Failed to Activate "+line + ", "+e.getMessage()); + } + } + } + } + }else{ + throw new Exception(activateFile + " is not a valid Activate file Path"); + } + }else{ + throw new Exception("Failed to initialise SvcLogicStore"); + } + + if(errors.size() > 0){ + throw new Exception(errors.toString()); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + + + public static void main(String[] args) { + try { + String activateFile = null; + String propertyPath = null; + + if(args != null && args.length >= 2){ + activateFile = args[0]; + propertyPath = args[1]; + }else{ + throw new Exception("Sufficient inputs for DGXMLActivate are missing "); + } + + DGXMLActivate dgXmlActivate = new DGXMLActivate(propertyPath); + dgXmlActivate.activateDg(activateFile); + } catch (Exception e) { + e.printStackTrace(); + }finally { + System.exit(1); + } + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLGenerator.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLGenerator.java new file mode 100644 index 000000000..60fcd5ba8 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLGenerator.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdnc.dg.loader; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class DGXMLGenerator { + private final static Logger logger = LoggerFactory.getLogger(DGXMLGenerator.class); + + public static String STRING_ENCODING = "utf-8"; + public static String JS_INTERFACE_DG_CONVERTOR = "dgconverter"; + public static String JS_METHOD_GET_NODE_TO_XML = "getNodeToXml"; + public static String GENERATOR_TEMPLATE_FILE = "js/dg_xml2json.js"; + + public void generateXMLFromJSON(String jsonPath, String xmlpath, String propertyPath) throws Exception { + try{ + ScriptEngineManager manager = new ScriptEngineManager(); + ScriptEngine engine = manager.getEngineByName("JavaScript"); + if (!(engine instanceof Invocable)) { + logger.error("Invoking methods is not supported."); + return; + } + Invocable inv = (Invocable) engine; + // engine.eval(new FileReader(DGXMLGenerator.class.getClassLoader().getResource(GENERATOR_TEMPLATE_FILE).getPath())); + String js = IOUtils.toString(DGXMLGenerator.class.getClassLoader().getResourceAsStream(GENERATOR_TEMPLATE_FILE),STRING_ENCODING); + engine.eval(js); + + Object dgconverter = engine.get(JS_INTERFACE_DG_CONVERTOR); + + List files = new ArrayList(); + if(dgconverter != null){ + File jsonPathFile = new File(jsonPath); + if(jsonPathFile.isDirectory()){ + String[] extensions = new String[] { "json", "JSON" }; + files = (List) FileUtils.listFiles(jsonPathFile, extensions, true); + }else if(jsonPathFile.isFile()){ + files.add(jsonPathFile); + }else{ + throw new Exception("Failed to get the nature of the JSON path :"+ jsonPath); + } + + logger.info("JSON Files identified "+ files.size()); + + if(files.size() > 0){ + boolean isXmlPathDeleted = FileUtils.deleteQuietly(new File(xmlpath)); + logger.info("Cleaning old DG XML under : " + xmlpath + ", delete status :" + isXmlPathDeleted); + + for (File file : files) { + String dgJson = FileUtils.readFileToString(file,STRING_ENCODING); + logger.info("Generating XML from :" + file.getName()); + String xmlFileName = xmlpath +"/"+file.getName().replace(".json", ".xml"); + + Object dgXMl = inv.invokeMethod(dgconverter, JS_METHOD_GET_NODE_TO_XML, dgJson); + // Write the XML File + if(dgXMl != null){ + File xmlFile = new File(xmlFileName); + FileUtils.writeStringToFile(xmlFile, dgXMl.toString(), STRING_ENCODING); + logger.info("Generated XML File under :" + xmlFile.getCanonicalPath()); + } + } + + }else{ + logger.info("No JSON Files to generate XML"); + } + }else{ + logger.error("Couldn't get Java Script Engine.."); + } + }catch (Exception e) { + logger.error("Failed to generate generateXMLFromJSON :"+e.getMessage()); + } + } + + + public static void main(String[] args) { + try { + DGXMLGenerator application = new DGXMLGenerator(); + String jsonPath = null; + String xmlPath = null; + String propertyPath = null; + // Generate, GenerateLoad, GenerateLoadActivate + //args = new String[]{"src/main/resources/json","src/test/resources/xml"}; + logger.info("DGXML Conversion Started with arguments :"+ args[0] +":"+ args[1]); + if(args != null && args.length >= 2){ + jsonPath = args[0]; + xmlPath = args[1]; + }else{ + throw new Exception("Sufficient inputs are missing "); + } + + application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath); + logger.info("DGXML Conversion Completed..."); + } catch (Exception e) { + logger.error("Failed in DG XML Generation :"+e.getMessage()); + e.printStackTrace(); + } + + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoad.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoad.java new file mode 100644 index 000000000..1b6116cc3 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoad.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; + +public class DGXMLLoad { + private final static Logger logger = LoggerFactory.getLogger(DGXMLLoad.class); + private final SvcLogicStore store; + public static String STRING_ENCODING = "utf-8"; + + public DGXMLLoad(String propfile) throws Exception{ + if(StringUtils.isBlank(propfile)){ + throw new Exception(propfile + " Profile file is not defined"); + } + this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); + } + + protected DGXMLLoad(SvcLogicStore store) throws Exception { + this.store=store; + } + + public void loadDGXMLFile(String dgXMLpath) throws SvcLogicException{ + if(dgXMLpath != null ){ + SvcLogicParser.load(dgXMLpath, this.store); + } + } + + private void loadDGXMLDir(String xmlPath) throws Exception { + try { + logger.info("******************** Loading DG into Database *****************************"); + List errors = new ArrayList(); + if(this.store != null){ + File xmlDir = new File(xmlPath); + if(xmlDir != null && xmlDir.isDirectory()){ + String[] extensions = new String[] { "xml", "XML" }; + List files = (List) FileUtils.listFiles(xmlDir, extensions, true); + for (File file : files) { + logger.info("Loading DG XML file :" + file.getCanonicalPath()); + try{ + SvcLogicParser.load(file.getCanonicalPath(), this.store); + }catch (Exception e) { + errors.add("Failed to load XML "+file.getCanonicalPath() + ", Exception : "+e.getMessage()); + } + } + }else{ + throw new Exception(xmlPath + " is not a valid XML Directory"); + } + }else{ + throw new Exception("Failed to initialise SvcLogicStore"); + } + + if(errors.size() > 0){ + throw new Exception(errors.toString()); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + + public static void main(String[] args) { + try { + String xmlPath = null; + String propertyPath = null; + + if(args != null && args.length >= 2){ + xmlPath = args[0]; + propertyPath = args[1]; + }else{ + throw new Exception("Sufficient inputs for DGXMLLoadNActivate are missing "); + } + DGXMLLoad dgXMLLoadDB = new DGXMLLoad(propertyPath); + dgXMLLoadDB.loadDGXMLDir(xmlPath); + } catch (Exception e) { + e.printStackTrace(); + }finally { + System.exit(1); + } + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoadNActivate.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoadNActivate.java new file mode 100644 index 000000000..54f109177 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/main/java/org/onap/sdnc/dg/loader/DGXMLLoadNActivate.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; + +public class DGXMLLoadNActivate { + private final static Logger logger = LoggerFactory.getLogger(DGXMLLoadNActivate.class); + private final SvcLogicStore store; + public static String STRING_ENCODING = "utf-8"; + + public DGXMLLoadNActivate(String propfile) throws Exception{ + if(StringUtils.isBlank(propfile)){ + throw new Exception(propfile + " Profile file is not defined"); + } + this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); + } + + protected DGXMLLoadNActivate(SvcLogicStore store) { + this.store=store; + } + + public void loadDGXMLFile(String dgXMLpath) throws SvcLogicException{ + if(dgXMLpath != null ){ + SvcLogicParser.load(dgXMLpath, this.store); + } + } + + private void loadDGXMLDir(String xmlPath) throws Exception { + try { + logger.info("******************** Loading DG into Database *****************************"); + List errors = new ArrayList(); + if(this.store != null){ + File xmlDir = new File(xmlPath); + if(xmlDir.isDirectory()){ + String[] extensions = new String[] { "xml", "XML" }; + List files = (List) FileUtils.listFiles(xmlDir, extensions, true); + for (File file : files) { + logger.info("Loading DG XML file :" + file.getCanonicalPath()); + try{ + SvcLogicParser.load(file.getCanonicalPath(), this.store); + }catch (Exception e) { + errors.add("Failed to load XML "+file.getCanonicalPath() + ", Exception : "+e.getMessage()); + } + } + }else{ + throw new Exception(xmlPath + " is not a valid XML Directory"); + } + }else{ + throw new Exception("Failed to initialise SvcLogicStore"); + } + + if(errors.size() > 0){ + throw new Exception(errors.toString()); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + + public void activateDg(String activateFilePath) throws Exception { + logger.info("******************** Activating DG into Database *****************************"); + try { + List errors = new ArrayList(); + if(this.store != null){ + File activateFile = new File(activateFilePath); + if(activateFile.isFile()){ + List fileLines = FileUtils.readLines(activateFile,STRING_ENCODING); + if(fileLines != null ){ + for (String line : fileLines) { + if(line != null && ! line.trim().startsWith("#")){ + String lineArray[] = line.trim().split(":"); + try { + if(lineArray != null && lineArray.length >= 4){ + String module = lineArray[0]; + String rpc = lineArray[1]; + String version = lineArray[2]; + String mode = lineArray[3]; + if(StringUtils.isNotBlank(module) && StringUtils.isNotBlank(rpc) + && StringUtils.isNotBlank(version) && StringUtils.isNotBlank(mode)){ + logger.info("Activating DG :" + line); + SvcLogicGraph graph = this.store.fetch(module, rpc, version, mode); + if(graph != null){ + logger.info("Found Graph :" + line + " Activating ..."); + this.store.activate(graph); + }else{ + throw new Exception("Failed to fetch from Database"); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + errors.add("Failed to Activate "+line + ", "+e.getMessage()); + } + } + } + } + }else{ + throw new Exception(activateFile + " is not a valid Activate file Path"); + } + }else{ + throw new Exception("Failed to initialise SvcLogicStore"); + } + + if(errors.size() > 0){ + throw new Exception(errors.toString()); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + + + public static void main(String[] args) { + try { + String xmlPath = null; + String propertyPath = null; + String activateFile = null; + + if(args != null && args.length >= 3){ + xmlPath = args[0]; + activateFile = args[1]; + propertyPath = args[2]; + }else{ + throw new Exception("Sufficient inputs for DGXMLLoadNActivate are missing "); + } + + //propertyPath = "/Users/bs2796/0Source/ecomp/bvc-3.2.2/others/properties/dblib.properties"; + //xmlPath = DGXMLLoadNActivate.class.getClassLoader().getResource(".").getPath() +"/xml" ; + + DGXMLLoadNActivate dgXMLLoadDB = new DGXMLLoadNActivate(propertyPath); + dgXMLLoadDB.loadDGXMLDir(xmlPath); + dgXMLLoadDB.activateDg(activateFile); + } catch (Exception e) { + e.printStackTrace(); + }finally { + System.exit(1); + } + } +} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGLoaderActivator.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGLoaderActivator.java deleted file mode 100644 index 99f7f8b6c..000000000 --- a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGLoaderActivator.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdnc.dg.loader; - -import java.util.LinkedList; -import java.util.List; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DGLoaderActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DGLoaderActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLActivate.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLActivate.java deleted file mode 100644 index 6af447742..000000000 --- a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLActivate.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - - -public class DGXMLActivate { - - private final static Logger logger = LoggerFactory.getLogger(DGXMLLoadNActivate.class); - private final SvcLogicStore store; - public static String STRING_ENCODING = "utf-8"; - - public DGXMLActivate(String propfile) throws Exception{ - if(StringUtils.isBlank(propfile)){ - throw new Exception(propfile + " Profile file is not defined"); - } - this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); - } - - protected DGXMLActivate(SvcLogicStore store) { - this.store = store; - } - - - public void activateDg(String activateFilePath) throws Exception { - logger.info("******************** Activating DG into Database *****************************"); - try { - List errors = new ArrayList(); - if(this.store != null){ - File activateFile = new File(activateFilePath); - if(activateFile != null && activateFile.isFile()){ - List fileLines = FileUtils.readLines(activateFile,STRING_ENCODING); - if(fileLines != null ){ - for (String line : fileLines) { - if(line != null && ! line.trim().startsWith("#")){ - String lineArray[] = line.trim().split(":"); - try { - if(lineArray != null && lineArray.length >= 4){ - String module = lineArray[0]; - String rpc = lineArray[1]; - String version = lineArray[2]; - String mode = lineArray[3]; - if(StringUtils.isNotBlank(module) && StringUtils.isNotBlank(rpc) - && StringUtils.isNotBlank(version) && StringUtils.isNotBlank(mode)){ - logger.info("Activating DG :" + line); - SvcLogicGraph graph = this.store.fetch(module, rpc, version, mode); - if(graph != null){ - logger.info("Found Graph :" + line + " Activating ..."); - this.store.activate(graph); - }else{ - throw new Exception("Failed to fetch from Database"); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - errors.add("Failed to Activate "+line + ", "+e.getMessage()); - } - } - } - } - }else{ - throw new Exception(activateFile + " is not a valid Activate file Path"); - } - }else{ - throw new Exception("Failed to initialise SvcLogicStore"); - } - - if(errors.size() > 0){ - throw new Exception(errors.toString()); - } - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - - - public static void main(String[] args) { - try { - String activateFile = null; - String propertyPath = null; - - if(args != null && args.length >= 2){ - activateFile = args[0]; - propertyPath = args[1]; - }else{ - throw new Exception("Sufficient inputs for DGXMLActivate are missing "); - } - - DGXMLActivate dgXmlActivate = new DGXMLActivate(propertyPath); - dgXmlActivate.activateDg(activateFile); - } catch (Exception e) { - e.printStackTrace(); - }finally { - System.exit(1); - } - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLGenerator.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLGenerator.java deleted file mode 100644 index 60fcd5ba8..000000000 --- a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLGenerator.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.sdnc.dg.loader; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.script.Invocable; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class DGXMLGenerator { - private final static Logger logger = LoggerFactory.getLogger(DGXMLGenerator.class); - - public static String STRING_ENCODING = "utf-8"; - public static String JS_INTERFACE_DG_CONVERTOR = "dgconverter"; - public static String JS_METHOD_GET_NODE_TO_XML = "getNodeToXml"; - public static String GENERATOR_TEMPLATE_FILE = "js/dg_xml2json.js"; - - public void generateXMLFromJSON(String jsonPath, String xmlpath, String propertyPath) throws Exception { - try{ - ScriptEngineManager manager = new ScriptEngineManager(); - ScriptEngine engine = manager.getEngineByName("JavaScript"); - if (!(engine instanceof Invocable)) { - logger.error("Invoking methods is not supported."); - return; - } - Invocable inv = (Invocable) engine; - // engine.eval(new FileReader(DGXMLGenerator.class.getClassLoader().getResource(GENERATOR_TEMPLATE_FILE).getPath())); - String js = IOUtils.toString(DGXMLGenerator.class.getClassLoader().getResourceAsStream(GENERATOR_TEMPLATE_FILE),STRING_ENCODING); - engine.eval(js); - - Object dgconverter = engine.get(JS_INTERFACE_DG_CONVERTOR); - - List files = new ArrayList(); - if(dgconverter != null){ - File jsonPathFile = new File(jsonPath); - if(jsonPathFile.isDirectory()){ - String[] extensions = new String[] { "json", "JSON" }; - files = (List) FileUtils.listFiles(jsonPathFile, extensions, true); - }else if(jsonPathFile.isFile()){ - files.add(jsonPathFile); - }else{ - throw new Exception("Failed to get the nature of the JSON path :"+ jsonPath); - } - - logger.info("JSON Files identified "+ files.size()); - - if(files.size() > 0){ - boolean isXmlPathDeleted = FileUtils.deleteQuietly(new File(xmlpath)); - logger.info("Cleaning old DG XML under : " + xmlpath + ", delete status :" + isXmlPathDeleted); - - for (File file : files) { - String dgJson = FileUtils.readFileToString(file,STRING_ENCODING); - logger.info("Generating XML from :" + file.getName()); - String xmlFileName = xmlpath +"/"+file.getName().replace(".json", ".xml"); - - Object dgXMl = inv.invokeMethod(dgconverter, JS_METHOD_GET_NODE_TO_XML, dgJson); - // Write the XML File - if(dgXMl != null){ - File xmlFile = new File(xmlFileName); - FileUtils.writeStringToFile(xmlFile, dgXMl.toString(), STRING_ENCODING); - logger.info("Generated XML File under :" + xmlFile.getCanonicalPath()); - } - } - - }else{ - logger.info("No JSON Files to generate XML"); - } - }else{ - logger.error("Couldn't get Java Script Engine.."); - } - }catch (Exception e) { - logger.error("Failed to generate generateXMLFromJSON :"+e.getMessage()); - } - } - - - public static void main(String[] args) { - try { - DGXMLGenerator application = new DGXMLGenerator(); - String jsonPath = null; - String xmlPath = null; - String propertyPath = null; - // Generate, GenerateLoad, GenerateLoadActivate - //args = new String[]{"src/main/resources/json","src/test/resources/xml"}; - logger.info("DGXML Conversion Started with arguments :"+ args[0] +":"+ args[1]); - if(args != null && args.length >= 2){ - jsonPath = args[0]; - xmlPath = args[1]; - }else{ - throw new Exception("Sufficient inputs are missing "); - } - - application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath); - logger.info("DGXML Conversion Completed..."); - } catch (Exception e) { - logger.error("Failed in DG XML Generation :"+e.getMessage()); - e.printStackTrace(); - } - - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoad.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoad.java deleted file mode 100644 index 1b6116cc3..000000000 --- a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoad.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicParser; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; - -public class DGXMLLoad { - private final static Logger logger = LoggerFactory.getLogger(DGXMLLoad.class); - private final SvcLogicStore store; - public static String STRING_ENCODING = "utf-8"; - - public DGXMLLoad(String propfile) throws Exception{ - if(StringUtils.isBlank(propfile)){ - throw new Exception(propfile + " Profile file is not defined"); - } - this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); - } - - protected DGXMLLoad(SvcLogicStore store) throws Exception { - this.store=store; - } - - public void loadDGXMLFile(String dgXMLpath) throws SvcLogicException{ - if(dgXMLpath != null ){ - SvcLogicParser.load(dgXMLpath, this.store); - } - } - - private void loadDGXMLDir(String xmlPath) throws Exception { - try { - logger.info("******************** Loading DG into Database *****************************"); - List errors = new ArrayList(); - if(this.store != null){ - File xmlDir = new File(xmlPath); - if(xmlDir != null && xmlDir.isDirectory()){ - String[] extensions = new String[] { "xml", "XML" }; - List files = (List) FileUtils.listFiles(xmlDir, extensions, true); - for (File file : files) { - logger.info("Loading DG XML file :" + file.getCanonicalPath()); - try{ - SvcLogicParser.load(file.getCanonicalPath(), this.store); - }catch (Exception e) { - errors.add("Failed to load XML "+file.getCanonicalPath() + ", Exception : "+e.getMessage()); - } - } - }else{ - throw new Exception(xmlPath + " is not a valid XML Directory"); - } - }else{ - throw new Exception("Failed to initialise SvcLogicStore"); - } - - if(errors.size() > 0){ - throw new Exception(errors.toString()); - } - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - - public static void main(String[] args) { - try { - String xmlPath = null; - String propertyPath = null; - - if(args != null && args.length >= 2){ - xmlPath = args[0]; - propertyPath = args[1]; - }else{ - throw new Exception("Sufficient inputs for DGXMLLoadNActivate are missing "); - } - DGXMLLoad dgXMLLoadDB = new DGXMLLoad(propertyPath); - dgXMLLoadDB.loadDGXMLDir(xmlPath); - } catch (Exception e) { - e.printStackTrace(); - }finally { - System.exit(1); - } - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoadNActivate.java b/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoadNActivate.java deleted file mode 100644 index 54f109177..000000000 --- a/appc-directed-graph/dg-loader/provider/src/main/java/org/openecomp/sdnc/dg/loader/DGXMLLoadNActivate.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.SvcLogicParser; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; - -public class DGXMLLoadNActivate { - private final static Logger logger = LoggerFactory.getLogger(DGXMLLoadNActivate.class); - private final SvcLogicStore store; - public static String STRING_ENCODING = "utf-8"; - - public DGXMLLoadNActivate(String propfile) throws Exception{ - if(StringUtils.isBlank(propfile)){ - throw new Exception(propfile + " Profile file is not defined"); - } - this.store = SvcLogicStoreFactory.getSvcLogicStore(propfile); - } - - protected DGXMLLoadNActivate(SvcLogicStore store) { - this.store=store; - } - - public void loadDGXMLFile(String dgXMLpath) throws SvcLogicException{ - if(dgXMLpath != null ){ - SvcLogicParser.load(dgXMLpath, this.store); - } - } - - private void loadDGXMLDir(String xmlPath) throws Exception { - try { - logger.info("******************** Loading DG into Database *****************************"); - List errors = new ArrayList(); - if(this.store != null){ - File xmlDir = new File(xmlPath); - if(xmlDir.isDirectory()){ - String[] extensions = new String[] { "xml", "XML" }; - List files = (List) FileUtils.listFiles(xmlDir, extensions, true); - for (File file : files) { - logger.info("Loading DG XML file :" + file.getCanonicalPath()); - try{ - SvcLogicParser.load(file.getCanonicalPath(), this.store); - }catch (Exception e) { - errors.add("Failed to load XML "+file.getCanonicalPath() + ", Exception : "+e.getMessage()); - } - } - }else{ - throw new Exception(xmlPath + " is not a valid XML Directory"); - } - }else{ - throw new Exception("Failed to initialise SvcLogicStore"); - } - - if(errors.size() > 0){ - throw new Exception(errors.toString()); - } - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - - public void activateDg(String activateFilePath) throws Exception { - logger.info("******************** Activating DG into Database *****************************"); - try { - List errors = new ArrayList(); - if(this.store != null){ - File activateFile = new File(activateFilePath); - if(activateFile.isFile()){ - List fileLines = FileUtils.readLines(activateFile,STRING_ENCODING); - if(fileLines != null ){ - for (String line : fileLines) { - if(line != null && ! line.trim().startsWith("#")){ - String lineArray[] = line.trim().split(":"); - try { - if(lineArray != null && lineArray.length >= 4){ - String module = lineArray[0]; - String rpc = lineArray[1]; - String version = lineArray[2]; - String mode = lineArray[3]; - if(StringUtils.isNotBlank(module) && StringUtils.isNotBlank(rpc) - && StringUtils.isNotBlank(version) && StringUtils.isNotBlank(mode)){ - logger.info("Activating DG :" + line); - SvcLogicGraph graph = this.store.fetch(module, rpc, version, mode); - if(graph != null){ - logger.info("Found Graph :" + line + " Activating ..."); - this.store.activate(graph); - }else{ - throw new Exception("Failed to fetch from Database"); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - errors.add("Failed to Activate "+line + ", "+e.getMessage()); - } - } - } - } - }else{ - throw new Exception(activateFile + " is not a valid Activate file Path"); - } - }else{ - throw new Exception("Failed to initialise SvcLogicStore"); - } - - if(errors.size() > 0){ - throw new Exception(errors.toString()); - } - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - - - public static void main(String[] args) { - try { - String xmlPath = null; - String propertyPath = null; - String activateFile = null; - - if(args != null && args.length >= 3){ - xmlPath = args[0]; - activateFile = args[1]; - propertyPath = args[2]; - }else{ - throw new Exception("Sufficient inputs for DGXMLLoadNActivate are missing "); - } - - //propertyPath = "/Users/bs2796/0Source/ecomp/bvc-3.2.2/others/properties/dblib.properties"; - //xmlPath = DGXMLLoadNActivate.class.getClassLoader().getResource(".").getPath() +"/xml" ; - - DGXMLLoadNActivate dgXMLLoadDB = new DGXMLLoadNActivate(propertyPath); - dgXMLLoadDB.loadDGXMLDir(xmlPath); - dgXMLLoadDB.activateDg(activateFile); - } catch (Exception e) { - e.printStackTrace(); - }finally { - System.exit(1); - } - } -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/DGLoaderTest.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/DGLoaderTest.java new file mode 100644 index 000000000..084929bc7 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/DGLoaderTest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; +import org.eclipse.osgi.framework.internal.core.BundleContextImpl; +import org.eclipse.osgi.framework.internal.core.BundleHost; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.ccsdk.sli.core.sli.ConfigurationException; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +import org.osgi.framework.BundleContext; +import org.powermock.reflect.Whitebox; +import org.powermock.*; + +public class DGLoaderTest { + + @Test + public void testXMLGenerator() throws Exception { + DGXMLGenerator application = new DGXMLGenerator(); + String jsonPath = null; + String xmlPath = null; + String propertyPath = "somePath"; + // Generate, GenerateLoad, GenerateLoadActivate + String []args = new String[]{"src/test/resources/json","src/test/resources/xml"}; + //logger.info("DGXML Conversion Started with arguments :"+ args[0] +":"+ args[1]); + if(args != null && args.length >= 2){ + jsonPath = args[0]; + xmlPath = args[1]; + } + + application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath); + File dir=new File("src/test/resources/xml"); + String extensions[]=new String[] {"xml","XML"}; + List files = new ArrayList(); + files=(List) FileUtils.listFiles(dir, extensions, true); + assertNotNull(files.get(0)); + assertNotNull(files.get(0).getName()); + } + + @Test + public void testXMLGeneratorMain() throws Exception { + String []args = new String[]{"src/test/resources/json","src/test/resources/xml"}; + DGXMLGenerator.main(args); + File dir=new File("src/test/resources/xml"); + String extensions[]=new String[] {"xml","XML"}; + List files = new ArrayList(); + files=(List) FileUtils.listFiles(dir, extensions, true); + assertNotNull(files.get(0)); + assertNotNull(files.get(0).getName()); + } + + @Test + public void testDGLoader() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; + DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); + dgXMLLoad.loadDGXMLFile(xmlPath); + } + + @Test + public void testDGLoaderWithDir() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String xmlPath = "src/test/resources/xml"; + DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); + Whitebox.invokeMethod(dgXMLLoad, "loadDGXMLDir",xmlPath); + } + + @Test + public void testDGLoaderWithDirThrowsException() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String xmlPath = "src/test/resources/xml/xml"; + DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); + Whitebox.invokeMethod(dgXMLLoad, "loadDGXMLDir",xmlPath); + } + + @Test + public void testDGActivate() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String activateFilePath = "src/test/resources/dg_activate_test"; + DGXMLActivate dgXMLActivate = new MockDGXMLActivate(); + dgXMLActivate.activateDg(activateFilePath); + + } + + @Test + public void testDGActivateThrowsException() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String activateFilePath = "src/test/resources/someFile"; + DGXMLActivate dgXMLActivate = new MockDGXMLActivate(); + dgXMLActivate.activateDg(activateFilePath); + + } + + @Test + public void testDGLoadNActivate() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String activateFilePath = "src/test/resources/dg_activate_test"; + String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; + DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); + dgXMLLoadNActivate.loadDGXMLFile(xmlPath); + dgXMLLoadNActivate.activateDg(activateFilePath); + } + + @Test + public void testDGLoadNActivateThrowsException() throws Exception { + String propertyPath = "src/test/resources/dummy.properties"; + String activateFilePath = "src/test/resources/someFile"; + String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; + DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); + dgXMLLoadNActivate.loadDGXMLFile(xmlPath); + dgXMLLoadNActivate.activateDg(activateFilePath); + } + + @Test + public void testDGLoadNActivateloadDGXMLDir() throws Exception { + String xmlPath = "src/test/resources/xml"; + DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); + Whitebox.invokeMethod(dgXMLLoadNActivate,"loadDGXMLDir",xmlPath); + } + + + public void testDGLoadNActivateloadDGXMLDirThrowsException() throws Exception { + String xmlPath = "src/test/resources/someDir"; + DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); + Whitebox.invokeMethod(dgXMLLoadNActivate,"loadDGXMLDir",xmlPath); + } + + @Test + public void testDGLoaderActivator() throws Exception { + String xmlPath = "src/test/resources/xml"; + DGLoaderActivator dgLoaderActivator = new DGLoaderActivator(); + dgLoaderActivator.start(null); + dgLoaderActivator.stop(null); + assertTrue(true); + } + + @Test (expected=Exception.class) + public void testDGActivateConstructorThrowsException() throws Exception { + String somePath=""; + DGXMLActivate dgXMLActivate = new DGXMLActivate(somePath); + } + + @Test (expected=Exception.class) + public void testDGXMLLoadConstructorThrowsException() throws Exception { + String somePath=""; + DGXMLLoad dgXMLLoad = new DGXMLLoad(somePath); + } + + @Test (expected=Exception.class) + public void testDGLoadNActivateConstructorThrowsException() throws Exception { + String somePath=""; + DGXMLLoadNActivate dgXMLLoadNActivate = new DGXMLLoadNActivate(somePath); + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLActivate.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLActivate.java new file mode 100644 index 000000000..41f1d09f8 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLActivate.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; + +public class MockDGXMLActivate extends DGXMLActivate { + private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; + MockDGXMLActivate() throws Exception { + super(storeChild); + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoad.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoad.java new file mode 100644 index 000000000..27336d38d --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoad.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; + +public class MockDGXMLLoad extends DGXMLLoad{ + + private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; + MockDGXMLLoad() throws Exception { + super(storeChild); + } + +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoadNActivate.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoadNActivate.java new file mode 100644 index 000000000..f60e6ab12 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockDGXMLLoadNActivate.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; + +public class MockDGXMLLoadNActivate extends DGXMLLoadNActivate { + private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; + MockDGXMLLoadNActivate() throws Exception { + super(storeChild); + } +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicDblibStore.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicDblibStore.java new file mode 100644 index 000000000..fdfe0ab1b --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicDblibStore.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.SvcLogicDblibStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; + +public class MockSvcLogicDblibStore implements SvcLogicStore { + + @Override + public boolean hasGraph(String module, String rpc, String version, + String mode) { + return true; + } + @Override + public SvcLogicGraph fetch(String module, String rpc, String version, + String mode) throws SvcLogicException { + SvcLogicGraph retVal=new SvcLogicGraph(); + retVal.setMode("sync"); + retVal.setModule("Appc"); + retVal.setRpc("unitTestDG"); + retVal.setVersion("4.0.0"); + return retVal; + + } + @Override + public void store(SvcLogicGraph graph) throws SvcLogicException { + + } + @Override + public void init(Properties props) throws SvcLogicException { + // TODO Auto-generated method stub + + } + @Override + public void registerNodeType(String nodeType) throws SvcLogicException { + // TODO Auto-generated method stub + + } + @Override + public void unregisterNodeType(String nodeType) throws SvcLogicException { + // TODO Auto-generated method stub + + } + @Override + public boolean isValidNodeType(String nodeType) throws SvcLogicException { + // TODO Auto-generated method stub + return true; + } + @Override + public void delete(String module, String rpc, String version, String mode) throws SvcLogicException { + // TODO Auto-generated method stub + + } + @Override + public void activate(SvcLogicGraph graph) throws SvcLogicException { + // TODO Auto-generated method stub + + } +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicFactory.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicFactory.java new file mode 100644 index 000000000..82f75a0f8 --- /dev/null +++ b/appc-directed-graph/dg-loader/provider/src/test/java/org/onap/sdnc/dg/loader/MockSvcLogicFactory.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdnc.dg.loader; + +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicDblibStore; + +public class MockSvcLogicFactory extends SvcLogicStoreFactory { + static SvcLogicStore getMockSvcLogicStore() { + SvcLogicStore store=new MockSvcLogicDblibStore(); + return store; + } +} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/DGLoaderTest.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/DGLoaderTest.java deleted file mode 100644 index 084929bc7..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/DGLoaderTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import static org.junit.Assert.*; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.apache.commons.io.FileUtils; -import org.eclipse.osgi.framework.internal.core.BundleContextImpl; -import org.eclipse.osgi.framework.internal.core.BundleHost; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.ccsdk.sli.core.sli.ConfigurationException; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; -import org.osgi.framework.BundleContext; -import org.powermock.reflect.Whitebox; -import org.powermock.*; - -public class DGLoaderTest { - - @Test - public void testXMLGenerator() throws Exception { - DGXMLGenerator application = new DGXMLGenerator(); - String jsonPath = null; - String xmlPath = null; - String propertyPath = "somePath"; - // Generate, GenerateLoad, GenerateLoadActivate - String []args = new String[]{"src/test/resources/json","src/test/resources/xml"}; - //logger.info("DGXML Conversion Started with arguments :"+ args[0] +":"+ args[1]); - if(args != null && args.length >= 2){ - jsonPath = args[0]; - xmlPath = args[1]; - } - - application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath); - File dir=new File("src/test/resources/xml"); - String extensions[]=new String[] {"xml","XML"}; - List files = new ArrayList(); - files=(List) FileUtils.listFiles(dir, extensions, true); - assertNotNull(files.get(0)); - assertNotNull(files.get(0).getName()); - } - - @Test - public void testXMLGeneratorMain() throws Exception { - String []args = new String[]{"src/test/resources/json","src/test/resources/xml"}; - DGXMLGenerator.main(args); - File dir=new File("src/test/resources/xml"); - String extensions[]=new String[] {"xml","XML"}; - List files = new ArrayList(); - files=(List) FileUtils.listFiles(dir, extensions, true); - assertNotNull(files.get(0)); - assertNotNull(files.get(0).getName()); - } - - @Test - public void testDGLoader() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; - DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); - dgXMLLoad.loadDGXMLFile(xmlPath); - } - - @Test - public void testDGLoaderWithDir() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String xmlPath = "src/test/resources/xml"; - DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); - Whitebox.invokeMethod(dgXMLLoad, "loadDGXMLDir",xmlPath); - } - - @Test - public void testDGLoaderWithDirThrowsException() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String xmlPath = "src/test/resources/xml/xml"; - DGXMLLoad dgXMLLoad = new MockDGXMLLoad(); - Whitebox.invokeMethod(dgXMLLoad, "loadDGXMLDir",xmlPath); - } - - @Test - public void testDGActivate() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String activateFilePath = "src/test/resources/dg_activate_test"; - DGXMLActivate dgXMLActivate = new MockDGXMLActivate(); - dgXMLActivate.activateDg(activateFilePath); - - } - - @Test - public void testDGActivateThrowsException() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String activateFilePath = "src/test/resources/someFile"; - DGXMLActivate dgXMLActivate = new MockDGXMLActivate(); - dgXMLActivate.activateDg(activateFilePath); - - } - - @Test - public void testDGLoadNActivate() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String activateFilePath = "src/test/resources/dg_activate_test"; - String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; - DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); - dgXMLLoadNActivate.loadDGXMLFile(xmlPath); - dgXMLLoadNActivate.activateDg(activateFilePath); - } - - @Test - public void testDGLoadNActivateThrowsException() throws Exception { - String propertyPath = "src/test/resources/dummy.properties"; - String activateFilePath = "src/test/resources/someFile"; - String xmlPath = "src/test/resources/xml/Appc_UniTest.xml"; - DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); - dgXMLLoadNActivate.loadDGXMLFile(xmlPath); - dgXMLLoadNActivate.activateDg(activateFilePath); - } - - @Test - public void testDGLoadNActivateloadDGXMLDir() throws Exception { - String xmlPath = "src/test/resources/xml"; - DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); - Whitebox.invokeMethod(dgXMLLoadNActivate,"loadDGXMLDir",xmlPath); - } - - - public void testDGLoadNActivateloadDGXMLDirThrowsException() throws Exception { - String xmlPath = "src/test/resources/someDir"; - DGXMLLoadNActivate dgXMLLoadNActivate = new MockDGXMLLoadNActivate(); - Whitebox.invokeMethod(dgXMLLoadNActivate,"loadDGXMLDir",xmlPath); - } - - @Test - public void testDGLoaderActivator() throws Exception { - String xmlPath = "src/test/resources/xml"; - DGLoaderActivator dgLoaderActivator = new DGLoaderActivator(); - dgLoaderActivator.start(null); - dgLoaderActivator.stop(null); - assertTrue(true); - } - - @Test (expected=Exception.class) - public void testDGActivateConstructorThrowsException() throws Exception { - String somePath=""; - DGXMLActivate dgXMLActivate = new DGXMLActivate(somePath); - } - - @Test (expected=Exception.class) - public void testDGXMLLoadConstructorThrowsException() throws Exception { - String somePath=""; - DGXMLLoad dgXMLLoad = new DGXMLLoad(somePath); - } - - @Test (expected=Exception.class) - public void testDGLoadNActivateConstructorThrowsException() throws Exception { - String somePath=""; - DGXMLLoadNActivate dgXMLLoadNActivate = new DGXMLLoadNActivate(somePath); - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLActivate.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLActivate.java deleted file mode 100644 index 41f1d09f8..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLActivate.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; - -public class MockDGXMLActivate extends DGXMLActivate { - private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; - MockDGXMLActivate() throws Exception { - super(storeChild); - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoad.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoad.java deleted file mode 100644 index 27336d38d..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoad.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; - -public class MockDGXMLLoad extends DGXMLLoad{ - - private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; - MockDGXMLLoad() throws Exception { - super(storeChild); - } - -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoadNActivate.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoadNActivate.java deleted file mode 100644 index f60e6ab12..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockDGXMLLoadNActivate.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; - -public class MockDGXMLLoadNActivate extends DGXMLLoadNActivate { - private final static SvcLogicStore storeChild=MockSvcLogicFactory.getMockSvcLogicStore();; - MockDGXMLLoadNActivate() throws Exception { - super(storeChild); - } -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicDblibStore.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicDblibStore.java deleted file mode 100644 index fdfe0ab1b..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicDblibStore.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import java.util.Properties; - -import org.onap.ccsdk.sli.core.sli.SvcLogicDblibStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; - -public class MockSvcLogicDblibStore implements SvcLogicStore { - - @Override - public boolean hasGraph(String module, String rpc, String version, - String mode) { - return true; - } - @Override - public SvcLogicGraph fetch(String module, String rpc, String version, - String mode) throws SvcLogicException { - SvcLogicGraph retVal=new SvcLogicGraph(); - retVal.setMode("sync"); - retVal.setModule("Appc"); - retVal.setRpc("unitTestDG"); - retVal.setVersion("4.0.0"); - return retVal; - - } - @Override - public void store(SvcLogicGraph graph) throws SvcLogicException { - - } - @Override - public void init(Properties props) throws SvcLogicException { - // TODO Auto-generated method stub - - } - @Override - public void registerNodeType(String nodeType) throws SvcLogicException { - // TODO Auto-generated method stub - - } - @Override - public void unregisterNodeType(String nodeType) throws SvcLogicException { - // TODO Auto-generated method stub - - } - @Override - public boolean isValidNodeType(String nodeType) throws SvcLogicException { - // TODO Auto-generated method stub - return true; - } - @Override - public void delete(String module, String rpc, String version, String mode) throws SvcLogicException { - // TODO Auto-generated method stub - - } - @Override - public void activate(SvcLogicGraph graph) throws SvcLogicException { - // TODO Auto-generated method stub - - } -} diff --git a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicFactory.java b/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicFactory.java deleted file mode 100644 index 82f75a0f8..000000000 --- a/appc-directed-graph/dg-loader/provider/src/test/java/org/openecomp/sdnc/dg/loader/MockSvcLogicFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.dg.loader; - -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicDblibStore; - -public class MockSvcLogicFactory extends SvcLogicStoreFactory { - static SvcLogicStore getMockSvcLogicStore() { - SvcLogicStore store=new MockSvcLogicDblibStore(); - return store; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/CommandExecutor.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/CommandExecutor.java new file mode 100644 index 000000000..d6935b83a --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/CommandExecutor.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * + */ +package org.onap.appc.executor; + + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.exceptions.APPCException; + + + +public interface CommandExecutor { + /** + * Execute given command + * Create command request and enqueue it for execution. + * @param commandHeaderInput Contains CommandHeader, command , target Id , payload and conf ID (optional) + * @throws APPCException in case of error. + */ + void executeCommand(RuntimeContext commandHeaderInput) throws APPCException; +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/UnstableVNFException.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/UnstableVNFException.java new file mode 100644 index 000000000..634bd0f68 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/UnstableVNFException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor; + + +public class UnstableVNFException extends Exception{ + public UnstableVNFException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/conv/Converter.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/conv/Converter.java new file mode 100644 index 000000000..3cfc7ece7 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/conv/Converter.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.conv; + +import java.io.IOException; + +import org.onap.appc.executor.objects.Params; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class Converter { + + public static Params convJsonStringToParams(String inObj) throws IOException { + Params outObj = null; + if(inObj != null) { + outObj = new ObjectMapper().readValue(inObj, Params.class); + } + return outObj; + } + + public static String convParamsToJsonString(Params inObj) throws JsonProcessingException { + String outObj = null; + if(inObj != null) { + outObj = new ObjectMapper().writeValueAsString(inObj); + } + return outObj; + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/CommandResponse.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/CommandResponse.java new file mode 100644 index 000000000..4e7b9b17f --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/CommandResponse.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.objects; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; + + +public class CommandResponse { + + private final RuntimeContext runtimeContext; + + public CommandResponse(RuntimeContext runtimeContext) { + super(); + this.runtimeContext = runtimeContext; + } + + public RuntimeContext getRuntimeContext() { + return runtimeContext; + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/LCMCommandStatus.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/LCMCommandStatus.java new file mode 100644 index 000000000..be13fd0ff --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/LCMCommandStatus.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.objects; + + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.util.MessageFormatter; + +import java.util.Map; + +public enum LCMCommandStatus { + + ACCEPTED(100,"ACCEPTED - request accepted"), + + //ERROR(2xx) - request can't be handled due to some technical error + UNEXPECTED_ERROR(200,"UNEXPECTED ERROR - ${errorMsg}"), + + //REJECT(3xx) - request has been rejected due to some business reason (e.g. no such service-instance-id, command is not supported, etc) + REJECTED(300,"REJECTED - ${errorMsg}"), + INVALID_INPUT_PARAMETER(301,"INVALID INPUT PARAMETER - ${errorMsg}"),// TODO 77777777 to support "${paramName} with invalid value ${paramValue}" + MISSING_MANDATORY_PARAMETER(302,"MISSING MANDATORY PARAMETER - Parameter/s ${paramName} is/are missing" ), + REQUEST_PARSING_FAILED(303,"REQUEST PARSING FAILED - ${errorMsg}"), + NO_TRANSITION_DEFINE(304,"ACTION IS NOT ALLOWED - Action ${actionName} is not allowed for VNF in state ${currentState}"), + INVALID_VNF_STATE(305,"Request rejected because VNF status in A&AI is - ${currentState}" ), + VNF_NOT_FOUND(306,"VNF NOT FOUND - VNF with ID ${vnfId} was not found" ), + DG_WORKFLOW_NOT_FOUND(307,"DG WORKFLOW NOT FOUND - No DG workflow found for the combination of ${dgModule} module ${dgName} name and ${dgVersion} version"),//TODO need to support it + WORKFLOW_NOT_FOUND(308,"WORKFLOW NOT FOUND - No workflow found for VNF type ${vnfTypeVersion} and ${actionName} action"), + UNSTABLE_VNF(309,"UNSTABLE VNF - VNF ${vnfId} is not stable to accept the command"), + LOCKING_FAILURE(310,"LOCKING FAILURE - ${errorMsg}" ), + EXPIRED_REQUEST(311,"EXPIRED REQUEST"), + DUPLICATE_REQUEST(312,"DUPLICATE REQUEST"), + MISSING_VNF_DATA_IN_AAI(313,"MISSING VNF DATA IN A&AI - ${attributeName} not found for VNF ID = ${vnfId}"), + + SUCCESS(400,"SUCCESS - request has been processed successfully"), + + + // FAILURE(5xx) - request processing results with failure. The FAILURE response is always transmitted asynchronously, via DMaaP. + DG_FAILURE(401,"DG FAILURE - ${errorMsg}"), + NO_TRANSITION_DEFINE_FAILURE(402,"NO TRANSITION DEFINE - No Transition Defined for ${actionName} action and ${currentState} state"), + UPDATE_AAI_FAILURE(403,"UPDATE_AAI_FAILURE - failed to update AAI. ${errorMsg}"), + EXPIRED_REQUEST_FAILURE(404,"EXPIRED REQUEST FAILURE - failed after accepted because TTL expired"), + UNEXPECTED_FAILURE(405,"UNEXPECTED FAILURE - ${errorMsg}"), + UNSTABLE_VNF_FAILURE(406,"UNSTABLE VNF FAILURE - VNF ${vnfId} is not stable to accept the command"), + + ; + + + public static final String errorDgMessageParamName = "errorDgMessage"; + + private int responseCode; + private String responseMessage; + + + + + LCMCommandStatus(int responseCode, String responseMessage) { + this.responseCode = responseCode; + this.responseMessage = responseMessage; + } + + public String getResponseMessage() { + return responseMessage; + } + + public int getResponseCode() { + return responseCode; + } + + + /** + * + * @return messageTemplate + */ + + + public String getFormattedMessage(Params params){ + Map paramsMap = params != null ? params.getParams() : null; + return MessageFormatter.format(getResponseMessage(),paramsMap); + + } + + public String getFormattedMessageWithCode(Params params){ + return getResponseCode()+"-" + getFormattedMessage(params); + } + + @Override + public String toString() { + return "LCMCommandStatus{" + + "responseCode=" + responseCode + + ", responseMessage='" + responseMessage + '\'' + + '}'; + } + + public Status toStatus(Params params) { + return new Status(responseCode, getFormattedMessage(params)); + } +} + diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/Params.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/Params.java new file mode 100644 index 000000000..c3cae7bcd --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/Params.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.objects; + +import java.lang.Object; +import java.util.HashMap; +import java.util.Map; + + +public class Params { + public static final String paramDgNameSpace = "dg.status.message.param."; + public static final String errorDgMessageParamName = "errorDgMessage"; + private Map params; + + public Params() { + } + + public Map getParams() { + return params; + } + + public void setParams(Map params) { + this.params = params; + } + + public Params addParam(String paramName, java.lang.Object paramValue) { + params = params == null ? new HashMap() : params; + params.put(paramName, paramValue); + return this; + } + + @Override + public String toString() { + return "Params{" + + "params=" + params + + '}'; + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/UniqueRequestIdentifier.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/UniqueRequestIdentifier.java new file mode 100644 index 000000000..b2f2a1d89 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/onap/appc/executor/objects/UniqueRequestIdentifier.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.objects; + + +import org.apache.commons.lang3.StringUtils; + + +public class UniqueRequestIdentifier { + private static final String IDENTIFIER_DELIMITER = "@"; + + private String originatorID; + private String requestID; + private String subRequestID; + + private UniqueRequestIdentifier(){ + + } + public UniqueRequestIdentifier(String originatorID, + String requestID, + String subRequestID) { + this(); + this.originatorID = originatorID; + this.requestID = requestID; + this.subRequestID = subRequestID; + } + + public String toIdentifierString(){ + StringBuilder stringBuilder = new StringBuilder(); + if(originatorID != null){ + stringBuilder.append(originatorID); + } + stringBuilder.append(IDENTIFIER_DELIMITER); + + if(requestID != null){ + stringBuilder.append(requestID); + } + stringBuilder.append(IDENTIFIER_DELIMITER); + + if(subRequestID != null){ + stringBuilder.append(subRequestID); + } + return stringBuilder.toString(); + } + + public static UniqueRequestIdentifier getUniqueRequestIdentifier(String identifierString){ + String[] splitIdentifier = identifierString.split(IDENTIFIER_DELIMITER); + if(splitIdentifier == null || splitIdentifier.length <2){ + throw new IllegalArgumentException("input identifierString is not valid "+identifierString); + } + String originatorID = splitIdentifier[0]; + String requestID = StringUtils.isEmpty(splitIdentifier[1])? null :splitIdentifier[1]; + String subRequestID = splitIdentifier.length>=3 ? splitIdentifier[2] : null; + return new UniqueRequestIdentifier(originatorID,requestID,subRequestID); + } + public String toString(){ + return "originatorID = " + originatorID + + " , requestID = " + requestID + + " , subRequestID = " + subRequestID; + } + @Override + public boolean equals(Object obj){ + if(obj ==null){ + return false; + } + if(!(obj instanceof UniqueRequestIdentifier)){ + return false; + } + UniqueRequestIdentifier identifier = (UniqueRequestIdentifier)obj; + if(this.originatorID == null){ + if(identifier.originatorID !=null) + return false; + } + else if(!this.originatorID.equals(identifier.originatorID)) + return false; + + if(this.requestID == null){ + if(identifier.requestID !=null) + return false; + } + else if(!this.requestID.equals(identifier.requestID)) + return false; + + if(this.subRequestID == null){ + if(identifier.subRequestID !=null) + return false; + } + else if(!this.subRequestID.equals(identifier.subRequestID)) + return false; + + return true; + } + @Override + public int hashCode(){ + final int prime = 31; + int result = 1; + result = result * prime + (this.originatorID == null ? 0 :this.originatorID.hashCode()); + result = result * prime + (this.requestID == null ? 0 :this.requestID.hashCode()); + result = result * prime + (this.subRequestID == null ? 0 :this.subRequestID.hashCode()); + return result; + } + + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/CommandExecutor.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/CommandExecutor.java deleted file mode 100644 index d6935b83a..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/CommandExecutor.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.onap.appc.executor; - - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.exceptions.APPCException; - - - -public interface CommandExecutor { - /** - * Execute given command - * Create command request and enqueue it for execution. - * @param commandHeaderInput Contains CommandHeader, command , target Id , payload and conf ID (optional) - * @throws APPCException in case of error. - */ - void executeCommand(RuntimeContext commandHeaderInput) throws APPCException; -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/UnstableVNFException.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/UnstableVNFException.java deleted file mode 100644 index 634bd0f68..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/UnstableVNFException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor; - - -public class UnstableVNFException extends Exception{ - public UnstableVNFException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/conv/Converter.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/conv/Converter.java deleted file mode 100644 index 3cfc7ece7..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/conv/Converter.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.conv; - -import java.io.IOException; - -import org.onap.appc.executor.objects.Params; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - - -public class Converter { - - public static Params convJsonStringToParams(String inObj) throws IOException { - Params outObj = null; - if(inObj != null) { - outObj = new ObjectMapper().readValue(inObj, Params.class); - } - return outObj; - } - - public static String convParamsToJsonString(Params inObj) throws JsonProcessingException { - String outObj = null; - if(inObj != null) { - outObj = new ObjectMapper().writeValueAsString(inObj); - } - return outObj; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/CommandResponse.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/CommandResponse.java deleted file mode 100644 index 4e7b9b17f..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/CommandResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.objects; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; - - -public class CommandResponse { - - private final RuntimeContext runtimeContext; - - public CommandResponse(RuntimeContext runtimeContext) { - super(); - this.runtimeContext = runtimeContext; - } - - public RuntimeContext getRuntimeContext() { - return runtimeContext; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/LCMCommandStatus.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/LCMCommandStatus.java deleted file mode 100644 index be13fd0ff..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/LCMCommandStatus.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.objects; - - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.util.MessageFormatter; - -import java.util.Map; - -public enum LCMCommandStatus { - - ACCEPTED(100,"ACCEPTED - request accepted"), - - //ERROR(2xx) - request can't be handled due to some technical error - UNEXPECTED_ERROR(200,"UNEXPECTED ERROR - ${errorMsg}"), - - //REJECT(3xx) - request has been rejected due to some business reason (e.g. no such service-instance-id, command is not supported, etc) - REJECTED(300,"REJECTED - ${errorMsg}"), - INVALID_INPUT_PARAMETER(301,"INVALID INPUT PARAMETER - ${errorMsg}"),// TODO 77777777 to support "${paramName} with invalid value ${paramValue}" - MISSING_MANDATORY_PARAMETER(302,"MISSING MANDATORY PARAMETER - Parameter/s ${paramName} is/are missing" ), - REQUEST_PARSING_FAILED(303,"REQUEST PARSING FAILED - ${errorMsg}"), - NO_TRANSITION_DEFINE(304,"ACTION IS NOT ALLOWED - Action ${actionName} is not allowed for VNF in state ${currentState}"), - INVALID_VNF_STATE(305,"Request rejected because VNF status in A&AI is - ${currentState}" ), - VNF_NOT_FOUND(306,"VNF NOT FOUND - VNF with ID ${vnfId} was not found" ), - DG_WORKFLOW_NOT_FOUND(307,"DG WORKFLOW NOT FOUND - No DG workflow found for the combination of ${dgModule} module ${dgName} name and ${dgVersion} version"),//TODO need to support it - WORKFLOW_NOT_FOUND(308,"WORKFLOW NOT FOUND - No workflow found for VNF type ${vnfTypeVersion} and ${actionName} action"), - UNSTABLE_VNF(309,"UNSTABLE VNF - VNF ${vnfId} is not stable to accept the command"), - LOCKING_FAILURE(310,"LOCKING FAILURE - ${errorMsg}" ), - EXPIRED_REQUEST(311,"EXPIRED REQUEST"), - DUPLICATE_REQUEST(312,"DUPLICATE REQUEST"), - MISSING_VNF_DATA_IN_AAI(313,"MISSING VNF DATA IN A&AI - ${attributeName} not found for VNF ID = ${vnfId}"), - - SUCCESS(400,"SUCCESS - request has been processed successfully"), - - - // FAILURE(5xx) - request processing results with failure. The FAILURE response is always transmitted asynchronously, via DMaaP. - DG_FAILURE(401,"DG FAILURE - ${errorMsg}"), - NO_TRANSITION_DEFINE_FAILURE(402,"NO TRANSITION DEFINE - No Transition Defined for ${actionName} action and ${currentState} state"), - UPDATE_AAI_FAILURE(403,"UPDATE_AAI_FAILURE - failed to update AAI. ${errorMsg}"), - EXPIRED_REQUEST_FAILURE(404,"EXPIRED REQUEST FAILURE - failed after accepted because TTL expired"), - UNEXPECTED_FAILURE(405,"UNEXPECTED FAILURE - ${errorMsg}"), - UNSTABLE_VNF_FAILURE(406,"UNSTABLE VNF FAILURE - VNF ${vnfId} is not stable to accept the command"), - - ; - - - public static final String errorDgMessageParamName = "errorDgMessage"; - - private int responseCode; - private String responseMessage; - - - - - LCMCommandStatus(int responseCode, String responseMessage) { - this.responseCode = responseCode; - this.responseMessage = responseMessage; - } - - public String getResponseMessage() { - return responseMessage; - } - - public int getResponseCode() { - return responseCode; - } - - - /** - * - * @return messageTemplate - */ - - - public String getFormattedMessage(Params params){ - Map paramsMap = params != null ? params.getParams() : null; - return MessageFormatter.format(getResponseMessage(),paramsMap); - - } - - public String getFormattedMessageWithCode(Params params){ - return getResponseCode()+"-" + getFormattedMessage(params); - } - - @Override - public String toString() { - return "LCMCommandStatus{" + - "responseCode=" + responseCode + - ", responseMessage='" + responseMessage + '\'' + - '}'; - } - - public Status toStatus(Params params) { - return new Status(responseCode, getFormattedMessage(params)); - } -} - diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/Params.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/Params.java deleted file mode 100644 index c3cae7bcd..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/Params.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.objects; - -import java.lang.Object; -import java.util.HashMap; -import java.util.Map; - - -public class Params { - public static final String paramDgNameSpace = "dg.status.message.param."; - public static final String errorDgMessageParamName = "errorDgMessage"; - private Map params; - - public Params() { - } - - public Map getParams() { - return params; - } - - public void setParams(Map params) { - this.params = params; - } - - public Params addParam(String paramName, java.lang.Object paramValue) { - params = params == null ? new HashMap() : params; - params.put(paramName, paramValue); - return this; - } - - @Override - public String toString() { - return "Params{" + - "params=" + params + - '}'; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/UniqueRequestIdentifier.java b/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/UniqueRequestIdentifier.java deleted file mode 100644 index b2f2a1d89..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/UniqueRequestIdentifier.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.objects; - - -import org.apache.commons.lang3.StringUtils; - - -public class UniqueRequestIdentifier { - private static final String IDENTIFIER_DELIMITER = "@"; - - private String originatorID; - private String requestID; - private String subRequestID; - - private UniqueRequestIdentifier(){ - - } - public UniqueRequestIdentifier(String originatorID, - String requestID, - String subRequestID) { - this(); - this.originatorID = originatorID; - this.requestID = requestID; - this.subRequestID = subRequestID; - } - - public String toIdentifierString(){ - StringBuilder stringBuilder = new StringBuilder(); - if(originatorID != null){ - stringBuilder.append(originatorID); - } - stringBuilder.append(IDENTIFIER_DELIMITER); - - if(requestID != null){ - stringBuilder.append(requestID); - } - stringBuilder.append(IDENTIFIER_DELIMITER); - - if(subRequestID != null){ - stringBuilder.append(subRequestID); - } - return stringBuilder.toString(); - } - - public static UniqueRequestIdentifier getUniqueRequestIdentifier(String identifierString){ - String[] splitIdentifier = identifierString.split(IDENTIFIER_DELIMITER); - if(splitIdentifier == null || splitIdentifier.length <2){ - throw new IllegalArgumentException("input identifierString is not valid "+identifierString); - } - String originatorID = splitIdentifier[0]; - String requestID = StringUtils.isEmpty(splitIdentifier[1])? null :splitIdentifier[1]; - String subRequestID = splitIdentifier.length>=3 ? splitIdentifier[2] : null; - return new UniqueRequestIdentifier(originatorID,requestID,subRequestID); - } - public String toString(){ - return "originatorID = " + originatorID + - " , requestID = " + requestID + - " , subRequestID = " + subRequestID; - } - @Override - public boolean equals(Object obj){ - if(obj ==null){ - return false; - } - if(!(obj instanceof UniqueRequestIdentifier)){ - return false; - } - UniqueRequestIdentifier identifier = (UniqueRequestIdentifier)obj; - if(this.originatorID == null){ - if(identifier.originatorID !=null) - return false; - } - else if(!this.originatorID.equals(identifier.originatorID)) - return false; - - if(this.requestID == null){ - if(identifier.requestID !=null) - return false; - } - else if(!this.requestID.equals(identifier.requestID)) - return false; - - if(this.subRequestID == null){ - if(identifier.subRequestID !=null) - return false; - } - else if(!this.subRequestID.equals(identifier.subRequestID)) - return false; - - return true; - } - @Override - public int hashCode(){ - final int prime = 31; - int result = 1; - result = result * prime + (this.originatorID == null ? 0 :this.originatorID.hashCode()); - result = result * prime + (this.requestID == null ? 0 :this.requestID.hashCode()); - result = result * prime + (this.subRequestID == null ? 0 :this.subRequestID.hashCode()); - return result; - } - - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java new file mode 100644 index 000000000..d23a3fdd6 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * + */ +package org.onap.appc.executor.impl; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executionqueue.ExecutionQueueService; +import org.onap.appc.executor.CommandExecutor; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.concurrent.TimeUnit; + + +public class CommandExecutorImpl implements CommandExecutor { + + private CommandTaskFactory executionTaskFactory; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(CommandExecutorImpl.class); + + private ExecutionQueueService executionQueueService; + private ExpiredMessageHandler expiredMessageHandler; + + public CommandExecutorImpl() { + + } + + /** + * Injected by blueprint + * + * @param executionQueueService + */ + public void setExecutionQueueService(ExecutionQueueService executionQueueService) { + this.executionQueueService = executionQueueService; + } + + /** + * Injected by blueprint + * @param expiredMessageHandler + */ + public void setExpiredMessageHandler(ExpiredMessageHandler expiredMessageHandler) { + this.expiredMessageHandler = expiredMessageHandler; + } + + public void initialize() { + logger.info("initialization started of CommandExecutorImpl"); + executionQueueService.registerMessageExpirationListener(expiredMessageHandler); + } + + public void setExecutionTaskFactory(CommandTaskFactory executionTaskFactory) { + this.executionTaskFactory = executionTaskFactory; + } + + /** + * Execute given command + * Create command request and enqueue it for execution. + * + * @param commandExecutorInput Contains CommandHeader, command , target Id , payload and conf ID (optional) + * @throws APPCException in case of error. + */ + @Override + public void executeCommand(RuntimeContext commandExecutorInput) throws APPCException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to executeCommand with CommandExecutorInput = " + ObjectUtils.toString(commandExecutorInput)); + } + enqueRequest(commandExecutorInput); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from executeCommand"); + } + } + + private RuntimeContext getCommandRequest(RuntimeContext commandExecutorInput) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getCommandRequest with CommandExecutorInput = " + ObjectUtils.toString(commandExecutorInput)); + } + RuntimeContext commandRequest; + commandRequest = commandExecutorInput; + if (logger.isTraceEnabled()) { + logger.trace("Exiting from getCommandRequest with (CommandRequest = " + ObjectUtils.toString(commandRequest) + ")"); + } + return commandRequest; + } + + @SuppressWarnings("unchecked") + private void enqueRequest(RuntimeContext request) throws APPCException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to enqueRequest with CommandRequest = " + ObjectUtils.toString(request)); + } + try { + CommandTask commandTask = executionTaskFactory.getExecutionTask(request); + + long remainingTTL = getRemainingTTL(request); + + executionQueueService.putMessage(commandTask, remainingTTL, TimeUnit.MILLISECONDS); + } catch (Exception e) { + logger.error("Exception: " + e.getMessage()); + throw new APPCException(e); + } + + if (logger.isTraceEnabled()) { + logger.trace("Exiting from enqueRequest"); + } + } + + private long getRemainingTTL(RuntimeContext request) { + Instant requestTimestamp = request.getRequestContext().getCommonHeader().getTimeStamp(); + int ttl = request.getRequestContext().getCommonHeader().getFlags().getTtl(); + return ChronoUnit.MILLIS.between(Instant.now(), requestTimestamp.plusSeconds(ttl)); + } + + private CommandTask getMessageExecutor(RuntimeContext request) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getMessageExecutor with command = " + request); + } + CommandTask executionTask = executionTaskFactory.getExecutionTask(request); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from getMessageExecutor"); + } + return executionTask; + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java new file mode 100644 index 000000000..1df756efa --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.executor.objects.CommandResponse; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.appc.workflow.objects.WorkflowResponse; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This abstract class is base class for all Command tasks. All command task must inherit this class. + */ + +public abstract class CommandTask implements Runnable { + + protected final RequestHandler requestHandler; + protected final WorkFlowManager workflowManager; + protected final RuntimeContext commandRequest; + + protected CommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, + WorkFlowManager workflowManager) { + super(); + this.commandRequest = commandRequest; + this.requestHandler = requestHandler; + this.workflowManager = workflowManager; + } + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class); + + public void onRequestCompletion(CommandResponse response, boolean isAAIUpdated) { + logger.debug("Entry: onRequestCompletion()"); + requestHandler.onRequestExecutionEnd(commandRequest, isAAIUpdated); + } + + public abstract void onRequestCompletion(CommandResponse response); + + protected CommandResponse buildCommandResponse(WorkflowResponse response) { + + return new CommandResponse(commandRequest); + } + + + public void execute() { + final RuntimeContext runtimeContext = commandRequest; + WorkflowRequest workflowRequest = new WorkflowRequest(); + workflowRequest.setRequestContext(runtimeContext.getRequestContext()); + workflowRequest.setResponseContext(runtimeContext.getResponseContext()); + workflowRequest.setVnfContext(runtimeContext.getVnfContext()); + + WorkflowResponse response = workflowManager.executeWorkflow(workflowRequest); + + CommandResponse commandResponse = buildCommandResponse(response); + this.onRequestCompletion(commandResponse); + } + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTaskFactory.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTaskFactory.java new file mode 100644 index 000000000..bd7247854 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTaskFactory.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + + +import org.onap.appc.domainmodel.lcm.ActionLevel; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.workflow.WorkFlowManager; + + + + +public class CommandTaskFactory { + +// private LCMCommandTask lcmCommandTask; +// private LCMReadonlyCommandTask LCMReadonlyCommandTask; + + private RequestHandler vnfRequestHandler; + private RequestHandler vmRequestHandler; + private WorkFlowManager workflowManager; + private LifecycleManager lifecyclemanager; + + + public void setWorkflowManager(WorkFlowManager workflowManager) { + this.workflowManager = workflowManager; + } + + public void setVnfRequestHandler(RequestHandler vnfRequestHandler) { + this.vnfRequestHandler = vnfRequestHandler; + } + + public void setVmRequestHandler(RequestHandler vmRequestHandler) { + this.vmRequestHandler = vmRequestHandler; + } + + public void setLifecyclemanager(LifecycleManager lifecyclemanager) { + this.lifecyclemanager = lifecyclemanager; + } + + + public synchronized CommandTask getExecutionTask(RuntimeContext runtimeContext){ + String action = runtimeContext.getRequestContext().getAction().name(); + ActionLevel actionLevel = runtimeContext.getRequestContext().getActionLevel(); + RequestHandler requestHandler = readRequestHandler(actionLevel); + if(ActionLevel.VM.equals(actionLevel)){ + return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager); + } + switch (runtimeContext.getRequestContext().getAction().getOperationType()){ + case ReadOnly: + case OperationStatusUpdate: + return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager); + default: + return new LCMCommandTask(runtimeContext,requestHandler,workflowManager, + lifecyclemanager); + } + } + + private RequestHandler readRequestHandler(ActionLevel actionLevel) { + if (ActionLevel.VM.equals(actionLevel)) { + return vmRequestHandler; + } + return vnfRequestHandler; + } + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommonMethods.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommonMethods.java new file mode 100644 index 000000000..a032f3737 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommonMethods.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; + + +class CommonMethods { + + private static final HashMap m = new HashMap(); + + static { + m.put(34, """); // < - less-than + m.put(60, "<"); // < - less-than + m.put(62, ">"); // > - greater-than + m.put(38, "&"); // & - Ampersand + } + + static String escapeHtml(String source) { + try { + StringWriter writer = new StringWriter((int) (source.length() * 1.5)); + escape(writer, source); + return writer.toString(); + } catch (IOException ioe) { + ioe.printStackTrace(); + return null; + } + } + + private static void escape(Writer writer, String str) throws IOException { + int len = str.length(); + for (int i = 0; i < len; i++) { + char c = str.charAt(i); + int ascii = (int) c; + String entityName = (String) m.get(ascii); + if (entityName == null) { + if (c > 0x7F) { + writer.write("&#"); + writer.write(Integer.toString(c, 10)); + writer.write(';'); + } else { + writer.write(c); + } + } else { + writer.write(entityName); + } + } + } + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/ExpiredMessageHandler.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/ExpiredMessageHandler.java new file mode 100644 index 000000000..bd5773216 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/ExpiredMessageHandler.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.ActionLevel; +import org.onap.appc.executionqueue.MessageExpirationListener; +import org.onap.appc.requesthandler.RequestHandler; + + +public class ExpiredMessageHandler implements MessageExpirationListener{ + private RequestHandler vnfRequestHandler; + + private RequestHandler vmRequestHandler; + + public ExpiredMessageHandler(){ + + } + + public void setVnfRequestHandler(RequestHandler vnfRequestHandler) { + this.vnfRequestHandler = vnfRequestHandler; + } + + public void setVmRequestHandler(RequestHandler vmRequestHandler) { + this.vmRequestHandler = vmRequestHandler; + } + + @Override + public void onMessageExpiration(M message) { + RuntimeContext commandRequest = (RuntimeContext)message; + RequestHandler requestHandler = readRequestHandler(commandRequest); + requestHandler.onRequestTTLEnd(commandRequest, true); + } + + private RequestHandler readRequestHandler(RuntimeContext runtimeContext) { + if(ActionLevel.VM.equals(runtimeContext.getRequestContext().getActionLevel())){ + return vmRequestHandler; + } + return vnfRequestHandler; + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMCommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMCommandTask.java new file mode 100644 index 000000000..999957fc8 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMCommandTask.java @@ -0,0 +1,294 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.CommandResponse; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowResponse; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.MDC; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.net.InetAddress; +import static com.att.eelf.configuration.Configuration.*; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + + +public class LCMCommandTask extends CommandTask { + + private final AAIService aaiService; + private final LifecycleManager lifecyclemanager; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMCommandTask.class); + + public LCMCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, WorkFlowManager workflowManager, + LifecycleManager lifecyclemanager) { + super(commandRequest, requestHandler, workflowManager); + this.lifecyclemanager = lifecyclemanager; + + BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); + // Get AAIadapter reference + ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); + if (sref != null) { + logger.info("AAIService from bundlecontext"); + aaiService = (AAIService) bctx.getService(sref); + + } else { + logger.info("AAIService error from bundlecontext"); + logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); + aaiService = null; + } + } + + + @Override + public void onRequestCompletion(CommandResponse response) { + final RuntimeContext request = commandRequest; + boolean isAAIUpdated = false; + try { + + final int statusCode = request.getResponseContext().getStatus().getCode(); + + if (logger.isDebugEnabled()) { + logger.debug("Workflow Execution Status = "+ statusCode); + } + + boolean isSuccess = statusCode == 100 || statusCode == 400; + + if (isSuccess && VNFOperation.Terminate == request.getRequestContext().getAction()) { + SvcLogicContext ctx = new SvcLogicContext(); + ctx = getVnfdata(request.getVnfContext().getId(), "vnf", ctx); + isAAIUpdated = aaiService.deleteGenericVnfData(request.getVnfContext().getId(), ctx.getAttribute("vnf.resource-version")); + } + else{ + isAAIUpdated = updateAAI(request.getVnfContext().getId() , false, isSuccess); + } + logger.debug("isAAIUpdated = " + isAAIUpdated); + if(!isAAIUpdated){ + throw new Exception(); + } + } + catch(Exception e1) { + logger.error("Exception = " + e1); + // In case of any errors we are updating the response status code and message + Status updatedStatus = new Status(401, "Fail to update VNF status in A&AI"); + request.getResponseContext().setStatus(updatedStatus); + throw new RuntimeException(e1); + } + finally { + super.onRequestCompletion(response, isAAIUpdated); + } + } + + @Override + public void run() { + final RuntimeContext request = commandRequest; + setInitialLogProperties(request); + boolean isAAIUpdated = false; + final String vnfId = request.getVnfContext().getId(); + final String vnfType = request.getVnfContext().getType(); + try { + final CommonHeader commonHeader = request.getRequestContext().getCommonHeader(); + final boolean forceFlag = commonHeader.getFlags().isForce(); + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(), + commonHeader.getRequestId(), commonHeader.getSubRequestId()); + String requestIdentifierString = requestIdentifier.toIdentifierString(); + requestHandler.onRequestExecutionStart(vnfId,false, requestIdentifierString, forceFlag); + + final String currentStatus = request.getVnfContext().getStatus(); + final VNFOperation action = request.getRequestContext().getAction(); + + final String nextState = lifecyclemanager.getNextState(vnfType, currentStatus, action.name()); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx=getVnfdata(vnfId, "onRequestExecutionStart", ctx); + isAAIUpdated= postVnfdata(vnfId, nextState,"onRequestExecutionStart",ctx); + } catch (NoTransitionDefinedException e) { + logger.error("Error getting Next State for AAI Update: " + e.getMessage(), e); + Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState); + request.getResponseContext().setStatus(LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE.toStatus(params)); + isAAIUpdated = false; + } catch (UnstableVNFException e) { + logger.error(e.getMessage(), e); + Params params = new Params().addParam("vnfId",vnfId); + request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params)); + isAAIUpdated = false; + }catch (Exception e) { + logger.error("Error before Request Execution starts.", e); + String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage(); + Params params = new Params().addParam("errorMsg",errorMsg); + request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params)); + isAAIUpdated = false; + } + + if (isAAIUpdated){ + super.execute(); + }else{ + String errorMsg = "Error updating A& AI before Workflow execution"; + logger.error(errorMsg); + WorkflowResponse response = new WorkflowResponse(); + response.setResponseContext(request.getResponseContext()); + CommandResponse commandResponse = super.buildCommandResponse(response); + this.onRequestCompletion(commandResponse); + } + + clearRequestLogProperties(); + } + + + private boolean updateAAI(String vnf_id, boolean isTTLEnd, boolean executionStatus) + { + String orchestrationStatus = null; + String nextState; + boolean callbackResponse; + VNFOperationOutcome outcome; + SvcLogicContext ctx = new SvcLogicContext(); + try { + ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx); + orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status"); + + if(isTTLEnd){ + outcome = VNFOperationOutcome.FAILURE; + } + else if(executionStatus){ + outcome = VNFOperationOutcome.SUCCESS; + } + else{ + outcome = VNFOperationOutcome.FAILURE; + } + nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ; + callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx); + logger.debug("AAI posting status: " + callbackResponse); + + } catch (NoTransitionDefinedException e) { + logger.debug("Transition not defined for State = " + orchestrationStatus); + callbackResponse =false; + } catch (LifecycleException e) { + logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus); + callbackResponse =false; + } + return callbackResponse; + } + + + private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) { + String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'"; + logger.debug("inside getVnfdata=== "+key); + try { + SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx); + if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){ + logger.warn("VNF " + vnf_id + " not found while updating A&AI"); + throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id); + } + else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){ + throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id); + } + logger.info("AAIResponse: " + response.toString()); + } catch (SvcLogicException e) { + logger.error("Error in getVnfdata "+ e); + throw new RuntimeException(e); + } + return ctx; + } + + private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) { + String key="vnf-id = '"+ vnf_id+"'"; + logger.debug("inside postVnfdata=== "+key); + Map data = new HashMap<>(); + data.put("orchestration-status", status); + try { + SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix, ctx); + if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){ + logger.warn("VNF " + vnf_id + " not found while updating A&AI"); + return false; + } + logger.info("AAIResponse: " + response.toString()); + if(response.toString().equals("SUCCESS")) + { + return true; + } + } catch (SvcLogicException e) { + logger.error("Error in postVnfdata "+ e); + throw new RuntimeException(e); + } + return false; + } + + protected void setInitialLogProperties(RuntimeContext request) + { + MDC.put(MDC_KEY_REQUEST_ID, request.getRequestContext().getCommonHeader().getRequestId()); + if (request.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null) + MDC.put(MDC_SERVICE_INSTANCE_ID, request.getRequestContext().getActionIdentifiers().getServiceInstanceId()); + MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getRequestContext().getCommonHeader().getOriginatorId()); + MDC.put(MDC_SERVICE_NAME, request.getRequestContext().getAction().name()); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + logger.debug(e.getMessage()); + } + MDC.put(MDC_INSTANCE_UUID, ""); //TODO make instanse_UUID generation once during APPC-instanse deploying + } + + protected void clearRequestLogProperties() + { + try { + MDC.remove(MDC_KEY_REQUEST_ID); + MDC.remove(MDC_SERVICE_INSTANCE_ID); + MDC.remove(MDC_SERVICE_NAME); + MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); + } catch (Exception e) { + + } + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMReadonlyCommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMReadonlyCommandTask.java new file mode 100644 index 000000000..0eeefe540 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/LCMReadonlyCommandTask.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor.impl; + + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.CommandResponse; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.workflow.WorkFlowManager; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class LCMReadonlyCommandTask extends CommandTask { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMReadonlyCommandTask.class); + + public LCMReadonlyCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, + WorkFlowManager workflowManager) { + super(commandRequest, requestHandler, workflowManager); + } + + @Override + public void onRequestCompletion(CommandResponse response) { + super.onRequestCompletion(response, true); + } + + @Override + public void run() { + RuntimeContext request = commandRequest; + final CommonHeader commonHeader = request.getRequestContext().getCommonHeader(); + final boolean forceFlag = commonHeader.getFlags().isForce(); + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(), commonHeader.getRequestId(), commonHeader.getSubRequestId()); + String requestIdentifierString = requestIdentifier.toIdentifierString(); + final String vnfId = request.getVnfContext().getId(); + try { + requestHandler.onRequestExecutionStart(vnfId,true, requestIdentifierString, forceFlag); + super.execute(); + } catch (UnstableVNFException e) { + logger.error(e.getMessage(), e); + Params params = new Params().addParam("vnfId",vnfId); + request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params)); + }catch (Exception e) { + logger.error("Error during runing LCMReadonlyCommandTask.", e); + String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage(); + Params params = new Params().addParam("errorMsg",errorMsg); + request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params)); + } + } +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandExecutorImpl.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandExecutorImpl.java deleted file mode 100644 index d23a3fdd6..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandExecutorImpl.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.onap.appc.executor.impl; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executionqueue.ExecutionQueueService; -import org.onap.appc.executor.CommandExecutor; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.concurrent.TimeUnit; - - -public class CommandExecutorImpl implements CommandExecutor { - - private CommandTaskFactory executionTaskFactory; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CommandExecutorImpl.class); - - private ExecutionQueueService executionQueueService; - private ExpiredMessageHandler expiredMessageHandler; - - public CommandExecutorImpl() { - - } - - /** - * Injected by blueprint - * - * @param executionQueueService - */ - public void setExecutionQueueService(ExecutionQueueService executionQueueService) { - this.executionQueueService = executionQueueService; - } - - /** - * Injected by blueprint - * @param expiredMessageHandler - */ - public void setExpiredMessageHandler(ExpiredMessageHandler expiredMessageHandler) { - this.expiredMessageHandler = expiredMessageHandler; - } - - public void initialize() { - logger.info("initialization started of CommandExecutorImpl"); - executionQueueService.registerMessageExpirationListener(expiredMessageHandler); - } - - public void setExecutionTaskFactory(CommandTaskFactory executionTaskFactory) { - this.executionTaskFactory = executionTaskFactory; - } - - /** - * Execute given command - * Create command request and enqueue it for execution. - * - * @param commandExecutorInput Contains CommandHeader, command , target Id , payload and conf ID (optional) - * @throws APPCException in case of error. - */ - @Override - public void executeCommand(RuntimeContext commandExecutorInput) throws APPCException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to executeCommand with CommandExecutorInput = " + ObjectUtils.toString(commandExecutorInput)); - } - enqueRequest(commandExecutorInput); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from executeCommand"); - } - } - - private RuntimeContext getCommandRequest(RuntimeContext commandExecutorInput) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getCommandRequest with CommandExecutorInput = " + ObjectUtils.toString(commandExecutorInput)); - } - RuntimeContext commandRequest; - commandRequest = commandExecutorInput; - if (logger.isTraceEnabled()) { - logger.trace("Exiting from getCommandRequest with (CommandRequest = " + ObjectUtils.toString(commandRequest) + ")"); - } - return commandRequest; - } - - @SuppressWarnings("unchecked") - private void enqueRequest(RuntimeContext request) throws APPCException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to enqueRequest with CommandRequest = " + ObjectUtils.toString(request)); - } - try { - CommandTask commandTask = executionTaskFactory.getExecutionTask(request); - - long remainingTTL = getRemainingTTL(request); - - executionQueueService.putMessage(commandTask, remainingTTL, TimeUnit.MILLISECONDS); - } catch (Exception e) { - logger.error("Exception: " + e.getMessage()); - throw new APPCException(e); - } - - if (logger.isTraceEnabled()) { - logger.trace("Exiting from enqueRequest"); - } - } - - private long getRemainingTTL(RuntimeContext request) { - Instant requestTimestamp = request.getRequestContext().getCommonHeader().getTimeStamp(); - int ttl = request.getRequestContext().getCommonHeader().getFlags().getTtl(); - return ChronoUnit.MILLIS.between(Instant.now(), requestTimestamp.plusSeconds(ttl)); - } - - private CommandTask getMessageExecutor(RuntimeContext request) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getMessageExecutor with command = " + request); - } - CommandTask executionTask = executionTaskFactory.getExecutionTask(request); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from getMessageExecutor"); - } - return executionTask; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTask.java deleted file mode 100644 index 1df756efa..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTask.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.executor.objects.CommandResponse; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.appc.workflow.objects.WorkflowResponse; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * This abstract class is base class for all Command tasks. All command task must inherit this class. - */ - -public abstract class CommandTask implements Runnable { - - protected final RequestHandler requestHandler; - protected final WorkFlowManager workflowManager; - protected final RuntimeContext commandRequest; - - protected CommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, - WorkFlowManager workflowManager) { - super(); - this.commandRequest = commandRequest; - this.requestHandler = requestHandler; - this.workflowManager = workflowManager; - } - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class); - - public void onRequestCompletion(CommandResponse response, boolean isAAIUpdated) { - logger.debug("Entry: onRequestCompletion()"); - requestHandler.onRequestExecutionEnd(commandRequest, isAAIUpdated); - } - - public abstract void onRequestCompletion(CommandResponse response); - - protected CommandResponse buildCommandResponse(WorkflowResponse response) { - - return new CommandResponse(commandRequest); - } - - - public void execute() { - final RuntimeContext runtimeContext = commandRequest; - WorkflowRequest workflowRequest = new WorkflowRequest(); - workflowRequest.setRequestContext(runtimeContext.getRequestContext()); - workflowRequest.setResponseContext(runtimeContext.getResponseContext()); - workflowRequest.setVnfContext(runtimeContext.getVnfContext()); - - WorkflowResponse response = workflowManager.executeWorkflow(workflowRequest); - - CommandResponse commandResponse = buildCommandResponse(response); - this.onRequestCompletion(commandResponse); - } - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTaskFactory.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTaskFactory.java deleted file mode 100644 index bd7247854..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTaskFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - - -import org.onap.appc.domainmodel.lcm.ActionLevel; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.workflow.WorkFlowManager; - - - - -public class CommandTaskFactory { - -// private LCMCommandTask lcmCommandTask; -// private LCMReadonlyCommandTask LCMReadonlyCommandTask; - - private RequestHandler vnfRequestHandler; - private RequestHandler vmRequestHandler; - private WorkFlowManager workflowManager; - private LifecycleManager lifecyclemanager; - - - public void setWorkflowManager(WorkFlowManager workflowManager) { - this.workflowManager = workflowManager; - } - - public void setVnfRequestHandler(RequestHandler vnfRequestHandler) { - this.vnfRequestHandler = vnfRequestHandler; - } - - public void setVmRequestHandler(RequestHandler vmRequestHandler) { - this.vmRequestHandler = vmRequestHandler; - } - - public void setLifecyclemanager(LifecycleManager lifecyclemanager) { - this.lifecyclemanager = lifecyclemanager; - } - - - public synchronized CommandTask getExecutionTask(RuntimeContext runtimeContext){ - String action = runtimeContext.getRequestContext().getAction().name(); - ActionLevel actionLevel = runtimeContext.getRequestContext().getActionLevel(); - RequestHandler requestHandler = readRequestHandler(actionLevel); - if(ActionLevel.VM.equals(actionLevel)){ - return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager); - } - switch (runtimeContext.getRequestContext().getAction().getOperationType()){ - case ReadOnly: - case OperationStatusUpdate: - return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager); - default: - return new LCMCommandTask(runtimeContext,requestHandler,workflowManager, - lifecyclemanager); - } - } - - private RequestHandler readRequestHandler(ActionLevel actionLevel) { - if (ActionLevel.VM.equals(actionLevel)) { - return vmRequestHandler; - } - return vnfRequestHandler; - } - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommonMethods.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommonMethods.java deleted file mode 100644 index a032f3737..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommonMethods.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.HashMap; - - -class CommonMethods { - - private static final HashMap m = new HashMap(); - - static { - m.put(34, """); // < - less-than - m.put(60, "<"); // < - less-than - m.put(62, ">"); // > - greater-than - m.put(38, "&"); // & - Ampersand - } - - static String escapeHtml(String source) { - try { - StringWriter writer = new StringWriter((int) (source.length() * 1.5)); - escape(writer, source); - return writer.toString(); - } catch (IOException ioe) { - ioe.printStackTrace(); - return null; - } - } - - private static void escape(Writer writer, String str) throws IOException { - int len = str.length(); - for (int i = 0; i < len; i++) { - char c = str.charAt(i); - int ascii = (int) c; - String entityName = (String) m.get(ascii); - if (entityName == null) { - if (c > 0x7F) { - writer.write("&#"); - writer.write(Integer.toString(c, 10)); - writer.write(';'); - } else { - writer.write(c); - } - } else { - writer.write(entityName); - } - } - } - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/ExpiredMessageHandler.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/ExpiredMessageHandler.java deleted file mode 100644 index bd5773216..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/ExpiredMessageHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.ActionLevel; -import org.onap.appc.executionqueue.MessageExpirationListener; -import org.onap.appc.requesthandler.RequestHandler; - - -public class ExpiredMessageHandler implements MessageExpirationListener{ - private RequestHandler vnfRequestHandler; - - private RequestHandler vmRequestHandler; - - public ExpiredMessageHandler(){ - - } - - public void setVnfRequestHandler(RequestHandler vnfRequestHandler) { - this.vnfRequestHandler = vnfRequestHandler; - } - - public void setVmRequestHandler(RequestHandler vmRequestHandler) { - this.vmRequestHandler = vmRequestHandler; - } - - @Override - public void onMessageExpiration(M message) { - RuntimeContext commandRequest = (RuntimeContext)message; - RequestHandler requestHandler = readRequestHandler(commandRequest); - requestHandler.onRequestTTLEnd(commandRequest, true); - } - - private RequestHandler readRequestHandler(RuntimeContext runtimeContext) { - if(ActionLevel.VM.equals(runtimeContext.getRequestContext().getActionLevel())){ - return vmRequestHandler; - } - return vnfRequestHandler; - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMCommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMCommandTask.java deleted file mode 100644 index 999957fc8..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMCommandTask.java +++ /dev/null @@ -1,294 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.CommandResponse; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowResponse; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.MDC; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.net.InetAddress; -import static com.att.eelf.configuration.Configuration.*; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - - -public class LCMCommandTask extends CommandTask { - - private final AAIService aaiService; - private final LifecycleManager lifecyclemanager; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMCommandTask.class); - - public LCMCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, WorkFlowManager workflowManager, - LifecycleManager lifecyclemanager) { - super(commandRequest, requestHandler, workflowManager); - this.lifecyclemanager = lifecyclemanager; - - BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); - // Get AAIadapter reference - ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); - if (sref != null) { - logger.info("AAIService from bundlecontext"); - aaiService = (AAIService) bctx.getService(sref); - - } else { - logger.info("AAIService error from bundlecontext"); - logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); - aaiService = null; - } - } - - - @Override - public void onRequestCompletion(CommandResponse response) { - final RuntimeContext request = commandRequest; - boolean isAAIUpdated = false; - try { - - final int statusCode = request.getResponseContext().getStatus().getCode(); - - if (logger.isDebugEnabled()) { - logger.debug("Workflow Execution Status = "+ statusCode); - } - - boolean isSuccess = statusCode == 100 || statusCode == 400; - - if (isSuccess && VNFOperation.Terminate == request.getRequestContext().getAction()) { - SvcLogicContext ctx = new SvcLogicContext(); - ctx = getVnfdata(request.getVnfContext().getId(), "vnf", ctx); - isAAIUpdated = aaiService.deleteGenericVnfData(request.getVnfContext().getId(), ctx.getAttribute("vnf.resource-version")); - } - else{ - isAAIUpdated = updateAAI(request.getVnfContext().getId() , false, isSuccess); - } - logger.debug("isAAIUpdated = " + isAAIUpdated); - if(!isAAIUpdated){ - throw new Exception(); - } - } - catch(Exception e1) { - logger.error("Exception = " + e1); - // In case of any errors we are updating the response status code and message - Status updatedStatus = new Status(401, "Fail to update VNF status in A&AI"); - request.getResponseContext().setStatus(updatedStatus); - throw new RuntimeException(e1); - } - finally { - super.onRequestCompletion(response, isAAIUpdated); - } - } - - @Override - public void run() { - final RuntimeContext request = commandRequest; - setInitialLogProperties(request); - boolean isAAIUpdated = false; - final String vnfId = request.getVnfContext().getId(); - final String vnfType = request.getVnfContext().getType(); - try { - final CommonHeader commonHeader = request.getRequestContext().getCommonHeader(); - final boolean forceFlag = commonHeader.getFlags().isForce(); - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(), - commonHeader.getRequestId(), commonHeader.getSubRequestId()); - String requestIdentifierString = requestIdentifier.toIdentifierString(); - requestHandler.onRequestExecutionStart(vnfId,false, requestIdentifierString, forceFlag); - - final String currentStatus = request.getVnfContext().getStatus(); - final VNFOperation action = request.getRequestContext().getAction(); - - final String nextState = lifecyclemanager.getNextState(vnfType, currentStatus, action.name()); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx=getVnfdata(vnfId, "onRequestExecutionStart", ctx); - isAAIUpdated= postVnfdata(vnfId, nextState,"onRequestExecutionStart",ctx); - } catch (NoTransitionDefinedException e) { - logger.error("Error getting Next State for AAI Update: " + e.getMessage(), e); - Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState); - request.getResponseContext().setStatus(LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE.toStatus(params)); - isAAIUpdated = false; - } catch (UnstableVNFException e) { - logger.error(e.getMessage(), e); - Params params = new Params().addParam("vnfId",vnfId); - request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params)); - isAAIUpdated = false; - }catch (Exception e) { - logger.error("Error before Request Execution starts.", e); - String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage(); - Params params = new Params().addParam("errorMsg",errorMsg); - request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params)); - isAAIUpdated = false; - } - - if (isAAIUpdated){ - super.execute(); - }else{ - String errorMsg = "Error updating A& AI before Workflow execution"; - logger.error(errorMsg); - WorkflowResponse response = new WorkflowResponse(); - response.setResponseContext(request.getResponseContext()); - CommandResponse commandResponse = super.buildCommandResponse(response); - this.onRequestCompletion(commandResponse); - } - - clearRequestLogProperties(); - } - - - private boolean updateAAI(String vnf_id, boolean isTTLEnd, boolean executionStatus) - { - String orchestrationStatus = null; - String nextState; - boolean callbackResponse; - VNFOperationOutcome outcome; - SvcLogicContext ctx = new SvcLogicContext(); - try { - ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx); - orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status"); - - if(isTTLEnd){ - outcome = VNFOperationOutcome.FAILURE; - } - else if(executionStatus){ - outcome = VNFOperationOutcome.SUCCESS; - } - else{ - outcome = VNFOperationOutcome.FAILURE; - } - nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ; - callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx); - logger.debug("AAI posting status: " + callbackResponse); - - } catch (NoTransitionDefinedException e) { - logger.debug("Transition not defined for State = " + orchestrationStatus); - callbackResponse =false; - } catch (LifecycleException e) { - logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus); - callbackResponse =false; - } - return callbackResponse; - } - - - private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) { - String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'"; - logger.debug("inside getVnfdata=== "+key); - try { - SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx); - if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){ - logger.warn("VNF " + vnf_id + " not found while updating A&AI"); - throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id); - } - else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){ - throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id); - } - logger.info("AAIResponse: " + response.toString()); - } catch (SvcLogicException e) { - logger.error("Error in getVnfdata "+ e); - throw new RuntimeException(e); - } - return ctx; - } - - private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) { - String key="vnf-id = '"+ vnf_id+"'"; - logger.debug("inside postVnfdata=== "+key); - Map data = new HashMap<>(); - data.put("orchestration-status", status); - try { - SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix, ctx); - if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){ - logger.warn("VNF " + vnf_id + " not found while updating A&AI"); - return false; - } - logger.info("AAIResponse: " + response.toString()); - if(response.toString().equals("SUCCESS")) - { - return true; - } - } catch (SvcLogicException e) { - logger.error("Error in postVnfdata "+ e); - throw new RuntimeException(e); - } - return false; - } - - protected void setInitialLogProperties(RuntimeContext request) - { - MDC.put(MDC_KEY_REQUEST_ID, request.getRequestContext().getCommonHeader().getRequestId()); - if (request.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null) - MDC.put(MDC_SERVICE_INSTANCE_ID, request.getRequestContext().getActionIdentifiers().getServiceInstanceId()); - MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getRequestContext().getCommonHeader().getOriginatorId()); - MDC.put(MDC_SERVICE_NAME, request.getRequestContext().getAction().name()); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - logger.debug(e.getMessage()); - } - MDC.put(MDC_INSTANCE_UUID, ""); //TODO make instanse_UUID generation once during APPC-instanse deploying - } - - protected void clearRequestLogProperties() - { - try { - MDC.remove(MDC_KEY_REQUEST_ID); - MDC.remove(MDC_SERVICE_INSTANCE_ID); - MDC.remove(MDC_SERVICE_NAME); - MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); - } catch (Exception e) { - - } - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMReadonlyCommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMReadonlyCommandTask.java deleted file mode 100644 index 0eeefe540..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMReadonlyCommandTask.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor.impl; - - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.CommandResponse; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.workflow.WorkFlowManager; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class LCMReadonlyCommandTask extends CommandTask { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMReadonlyCommandTask.class); - - public LCMReadonlyCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, - WorkFlowManager workflowManager) { - super(commandRequest, requestHandler, workflowManager); - } - - @Override - public void onRequestCompletion(CommandResponse response) { - super.onRequestCompletion(response, true); - } - - @Override - public void run() { - RuntimeContext request = commandRequest; - final CommonHeader commonHeader = request.getRequestContext().getCommonHeader(); - final boolean forceFlag = commonHeader.getFlags().isForce(); - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(), commonHeader.getRequestId(), commonHeader.getSubRequestId()); - String requestIdentifierString = requestIdentifier.toIdentifierString(); - final String vnfId = request.getVnfContext().getId(); - try { - requestHandler.onRequestExecutionStart(vnfId,true, requestIdentifierString, forceFlag); - super.execute(); - } catch (UnstableVNFException e) { - logger.error(e.getMessage(), e); - Params params = new Params().addParam("vnfId",vnfId); - request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params)); - }catch (Exception e) { - logger.error("Error during runing LCMReadonlyCommandTask.", e); - String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage(); - Params params = new Params().addParam("errorMsg",errorMsg); - request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params)); - } - } -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..1a4f859db --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,38 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-CMD-EXECUTOR-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 1a4f859db..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,38 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-CMD-EXECUTOR-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/CommandExecutionTaskTest.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/CommandExecutionTaskTest.java new file mode 100644 index 000000000..af62a06f6 --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/CommandExecutionTaskTest.java @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.impl.CommandTask; +import org.onap.appc.executor.impl.CommandTaskFactory; +import org.onap.appc.executor.impl.LCMCommandTask; +import org.onap.appc.executor.impl.LCMReadonlyCommandTask; +import org.onap.appc.executor.objects.CommandResponse; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowResponse; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Instant; + +import static junit.framework.Assert.assertEquals; +import static org.mockito.Matchers.*; + +@SuppressWarnings("unchecked") +@RunWith(PowerMockRunner.class) +@PrepareForTest( {FrameworkUtil.class, CommandTask.class, LCMCommandTask.class}) +public class CommandExecutionTaskTest { + + private final String TTL_FLAG= "TTL"; + private final String API_VERSION= "2.0.0"; + private final String ORIGINATOR_ID= "1"; + private CommandTaskFactory factory ; + + private RequestHandler requestHandler; + private WorkFlowManager workflowManager; + private AAIService aaiService; + private LifecycleManager lifecyclemanager; + + private final BundleContext bundleContext=Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + @Before + public void init() throws SvcLogicException { + + // *** + AAIService aaiService = Mockito.mock(AAIService.class); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService); + PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(), + anyString(), anyObject())).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + SvcLogicContext ctx =(SvcLogicContext)args[6]; + String prefix = (String)args[4]; + String key = (String)args[3]; + if(key.contains("'28'")){ + return SvcLogicResource.QueryStatus.FAILURE ; + }else if ( key.contains("'8'")) { + return SvcLogicResource.QueryStatus.NOT_FOUND ; + }else { + ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); + ctx.setAttribute(prefix + ".orchestration-status", "INSTANTIATED"); + } + return SvcLogicResource.QueryStatus.SUCCESS ; + }); + PowerMockito.when(aaiService.update(anyString(), anyString(), anyObject(), anyString(), + anyObject())).thenReturn(SvcLogicResource.QueryStatus.SUCCESS); + + requestHandler = Mockito.mock(RequestHandler.class); + workflowManager = Mockito.mock(WorkFlowManager.class); + lifecyclemanager = Mockito.mock(LifecycleManager.class ); + + factory = new CommandTaskFactory(); + factory.setLifecyclemanager(lifecyclemanager); + factory.setWorkflowManager(workflowManager); + factory.setVnfRequestHandler(requestHandler); + Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse ()); + } + + + @Test + public void testFactory(){ + CommandTask task; + Instant timeStamp = Instant.now(); + String requestId = "1"; + RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; + task = factory.getExecutionTask(commandExecutorInputConfigure); + assertEquals(LCMCommandTask.class,task.getClass() ); + RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; + task = factory.getExecutionTask(commandExecutorInputSync); + assertEquals(LCMReadonlyCommandTask.class,task.getClass() ); + + } + + + + @Test + public void testOnRequestCompletion(){ + Mockito.doNothing().when(requestHandler).onRequestTTLEnd(anyObject(),anyBoolean()); + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Configure, + "1", ""); + CommandResponse response = getCommandResponse(VNFOperation.Configure, true, "11", + "","1"); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.onRequestCompletion(response); + } + + @Test + public void testRunGetConfig(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMReadonlyCommandTask readonlyCommandTask = new LCMReadonlyCommandTask( + request, requestHandler,workflowManager); + readonlyCommandTask.run(); + } + + @Test + public void testRun(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.run(); + } + + @Test + public void testRunNegative(){ + RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, + "1", ""); + LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); + executionTask.run(); + } + + + private CommandResponse getCommandResponse(VNFOperation action, + boolean success, + String responseId, + String payload, + String vnfId){ + RuntimeContext runtimeContext = new RuntimeContext(); + ResponseContext responseContext = new ResponseContext(); + runtimeContext.setResponseContext(responseContext); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + responseContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + requestContext.setAction(action); + runtimeContext.setRpcName(action.name().toLowerCase()); + commonHeader.setApiVer(API_VERSION); + responseContext.setStatus(new Status(100, null)); + commonHeader.setRequestId(responseId); + responseContext.setPayload(payload); + commonHeader.setTimestamp(Instant.now()); + vnfContext.setId(vnfId); + return new CommandResponse(runtimeContext); + } + + + + @Test + public void testPositiveFlow_configure() { + + String requestId = "1"; + + pouplateCommandExecutorInput("FIREWALL",30, + "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "", + VNFOperation.Configure, "33", ""); + } + + public WorkflowResponse getWorkflowResponse (){ + WorkflowResponse wfResponse = new WorkflowResponse(); + ResponseContext responseContext = createResponseContextWithSuObjects(); + wfResponse.setResponseContext(responseContext); + responseContext.setPayload(""); + wfResponse.getResponseContext().setStatus(new Status(100, null)); + return wfResponse; + } + + private RuntimeContext pouplateCommandExecutorInput(String vnfType, + int ttl, + String vnfVersion, + Instant timeStamp, + String apiVersion, + String requestId, + String originatorID, + String subRequestID, + VNFOperation action, + String vnfId, + String payload){ + RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); + RequestContext requestContext = commandExecutorInput.getRequestContext(); + ResponseContext responseContext = createResponseContextWithSuObjects(); + commandExecutorInput.setResponseContext(responseContext); + + requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); + requestContext.getCommonHeader().setApiVer(apiVersion); + requestContext.getCommonHeader().setTimestamp(timeStamp); + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestID); + requestContext.getCommonHeader().setOriginatorId(originatorID); + requestContext.setAction(action); + requestContext.setPayload(payload); + requestContext.getActionIdentifiers().setVnfId(vnfId); + VNFContext vnfContext = commandExecutorInput.getVnfContext(); + vnfContext.setType(vnfType); + vnfContext.setId(vnfId); + vnfContext.setVersion(vnfVersion); + return commandExecutorInput; + } + + private RuntimeContext createCommandExecutorInputWithSubObjects() { + return createRuntimeContextWithSubObjects(); + } + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/TestCommandExecutor.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/TestCommandExecutor.java new file mode 100644 index 000000000..cd02c260d --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/TestCommandExecutor.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executor; +/** + * + */ + + +import java.time.Instant; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executionqueue.ExecutionQueueService; +import org.onap.appc.executor.impl.*; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.workflow.WorkFlowManager; +import org.powermock.api.mockito.PowerMockito; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +import static junit.framework.Assert.assertTrue; +import static org.powermock.api.support.membermodification.MemberMatcher.method; + + +@SuppressWarnings("deprecation") +public class TestCommandExecutor { + + private static final String TTL_FLAG= "TTL"; + private static final String API_VERSION= "2.0.0"; + private static final String ORIGINATOR_ID= "1"; + + private CommandExecutorImpl commandExecutor; + + private CommandTaskFactory executionTaskFactory; + + private RequestHandler requestHandler; + private WorkFlowManager workflowManager; + private LifecycleManager lifecyclemanager; + + private ExecutionQueueService executionQueueService; + private Instant timeStamp = Instant.now(); + private String requestId = "1"; + private RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30000, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; + private RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", + timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; + + @Before + public void init()throws Exception { + requestHandler= Mockito.mock(RequestHandler.class); + lifecyclemanager= Mockito.mock(LifecycleManager.class); + workflowManager= Mockito.mock(WorkFlowManager.class); + + executionQueueService = Mockito.mock(ExecutionQueueService.class); + + commandExecutor = new CommandExecutorImpl(); + executionTaskFactory = Mockito.mock(CommandTaskFactory.class); + commandExecutor.setExecutionTaskFactory(executionTaskFactory); + commandExecutor.setExecutionQueueService(executionQueueService); + LCMCommandTask lcmCommandTask = Mockito.mock(LCMCommandTask.class); + LCMReadonlyCommandTask lCMReadonlyCommandTask = Mockito.mock(LCMReadonlyCommandTask.class); + + Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputConfigure)).thenReturn(lcmCommandTask); + Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputSync)).thenReturn(lCMReadonlyCommandTask); + +// Mockito.when(executionQueueService.putMessage((Runnable) Mockito.anyObject(),Mockito.anyLong(),(TimeUnit)Mockito.anyObject())).thenReturn(true); + + } + + + @Test + public void testPositiveFlow_LCM() throws Exception { + //Map flags = setTTLInFlags("30"); + String requestId = "1"; + RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure, "15", "") ; + try { + commandExecutor.executeCommand(commandExecutorInput); + } catch (APPCException e) { + Assert.fail(e.toString()); + } + + } + + @Test + public void testPositiveFlow_GetConfig(){ + String requestId = "1"; + + RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; + try { + commandExecutor.executeCommand(commandExecutorInput); + } catch (APPCException e) { + Assert.fail(e.toString()); + } + + } + + + private RuntimeContext pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Instant timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){ + RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); + RequestContext requestContext = commandExecutorInput.getRequestContext(); + requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); + requestContext.getCommonHeader().setApiVer(apiVersion); + requestContext.getCommonHeader().setTimestamp(timeStamp); + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestID); + requestContext.getCommonHeader().setOriginatorId(originatorID); + requestContext.setAction(action); + requestContext.setPayload(payload); + requestContext.getActionIdentifiers().setVnfId(vnfId); + VNFContext vnfContext = commandExecutorInput.getVnfContext(); + vnfContext.setType(vnfType); + vnfContext.setId(vnfId); + vnfContext.setVersion(vnfVersion); + return commandExecutorInput; + } + + private RuntimeContext createCommandExecutorInputWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + } + + + +} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java deleted file mode 100644 index af62a06f6..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/CommandExecutionTaskTest.java +++ /dev/null @@ -1,295 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.impl.CommandTask; -import org.onap.appc.executor.impl.CommandTaskFactory; -import org.onap.appc.executor.impl.LCMCommandTask; -import org.onap.appc.executor.impl.LCMReadonlyCommandTask; -import org.onap.appc.executor.objects.CommandResponse; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowResponse; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.time.Instant; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.*; - -@SuppressWarnings("unchecked") -@RunWith(PowerMockRunner.class) -@PrepareForTest( {FrameworkUtil.class, CommandTask.class, LCMCommandTask.class}) -public class CommandExecutionTaskTest { - - private final String TTL_FLAG= "TTL"; - private final String API_VERSION= "2.0.0"; - private final String ORIGINATOR_ID= "1"; - private CommandTaskFactory factory ; - - private RequestHandler requestHandler; - private WorkFlowManager workflowManager; - private AAIService aaiService; - private LifecycleManager lifecyclemanager; - - private final BundleContext bundleContext=Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - @Before - public void init() throws SvcLogicException { - - // *** - AAIService aaiService = Mockito.mock(AAIService.class); - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService); - PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(), - anyString(), anyObject())).thenAnswer(invocation -> { - Object[] args = invocation.getArguments(); - SvcLogicContext ctx =(SvcLogicContext)args[6]; - String prefix = (String)args[4]; - String key = (String)args[3]; - if(key.contains("'28'")){ - return SvcLogicResource.QueryStatus.FAILURE ; - }else if ( key.contains("'8'")) { - return SvcLogicResource.QueryStatus.NOT_FOUND ; - }else { - ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); - ctx.setAttribute(prefix + ".orchestration-status", "INSTANTIATED"); - } - return SvcLogicResource.QueryStatus.SUCCESS ; - }); - PowerMockito.when(aaiService.update(anyString(), anyString(), anyObject(), anyString(), - anyObject())).thenReturn(SvcLogicResource.QueryStatus.SUCCESS); - - requestHandler = Mockito.mock(RequestHandler.class); - workflowManager = Mockito.mock(WorkFlowManager.class); - lifecyclemanager = Mockito.mock(LifecycleManager.class ); - - factory = new CommandTaskFactory(); - factory.setLifecyclemanager(lifecyclemanager); - factory.setWorkflowManager(workflowManager); - factory.setVnfRequestHandler(requestHandler); - Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse ()); - } - - - @Test - public void testFactory(){ - CommandTask task; - Instant timeStamp = Instant.now(); - String requestId = "1"; - RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; - task = factory.getExecutionTask(commandExecutorInputConfigure); - assertEquals(LCMCommandTask.class,task.getClass() ); - RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; - task = factory.getExecutionTask(commandExecutorInputSync); - assertEquals(LCMReadonlyCommandTask.class,task.getClass() ); - - } - - - - @Test - public void testOnRequestCompletion(){ - Mockito.doNothing().when(requestHandler).onRequestTTLEnd(anyObject(),anyBoolean()); - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Configure, - "1", ""); - CommandResponse response = getCommandResponse(VNFOperation.Configure, true, "11", - "","1"); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.onRequestCompletion(response); - } - - @Test - public void testRunGetConfig(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, - "1", ""); - LCMReadonlyCommandTask readonlyCommandTask = new LCMReadonlyCommandTask( - request, requestHandler,workflowManager); - readonlyCommandTask.run(); - } - - @Test - public void testRun(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, - "1", ""); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.run(); - } - - @Test - public void testRunNegative(){ - RuntimeContext request = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - Instant.now(), API_VERSION, "11", ORIGINATOR_ID, "", VNFOperation.Sync, - "1", ""); - LCMCommandTask executionTask = new LCMCommandTask(request, requestHandler,workflowManager,lifecyclemanager); - executionTask.run(); - } - - - private CommandResponse getCommandResponse(VNFOperation action, - boolean success, - String responseId, - String payload, - String vnfId){ - RuntimeContext runtimeContext = new RuntimeContext(); - ResponseContext responseContext = new ResponseContext(); - runtimeContext.setResponseContext(responseContext); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - responseContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - requestContext.setAction(action); - runtimeContext.setRpcName(action.name().toLowerCase()); - commonHeader.setApiVer(API_VERSION); - responseContext.setStatus(new Status(100, null)); - commonHeader.setRequestId(responseId); - responseContext.setPayload(payload); - commonHeader.setTimestamp(Instant.now()); - vnfContext.setId(vnfId); - return new CommandResponse(runtimeContext); - } - - - - @Test - public void testPositiveFlow_configure() { - - String requestId = "1"; - - pouplateCommandExecutorInput("FIREWALL",30, - "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "", - VNFOperation.Configure, "33", ""); - } - - public WorkflowResponse getWorkflowResponse (){ - WorkflowResponse wfResponse = new WorkflowResponse(); - ResponseContext responseContext = createResponseContextWithSuObjects(); - wfResponse.setResponseContext(responseContext); - responseContext.setPayload(""); - wfResponse.getResponseContext().setStatus(new Status(100, null)); - return wfResponse; - } - - private RuntimeContext pouplateCommandExecutorInput(String vnfType, - int ttl, - String vnfVersion, - Instant timeStamp, - String apiVersion, - String requestId, - String originatorID, - String subRequestID, - VNFOperation action, - String vnfId, - String payload){ - RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); - RequestContext requestContext = commandExecutorInput.getRequestContext(); - ResponseContext responseContext = createResponseContextWithSuObjects(); - commandExecutorInput.setResponseContext(responseContext); - - requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); - requestContext.getCommonHeader().setApiVer(apiVersion); - requestContext.getCommonHeader().setTimestamp(timeStamp); - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestID); - requestContext.getCommonHeader().setOriginatorId(originatorID); - requestContext.setAction(action); - requestContext.setPayload(payload); - requestContext.getActionIdentifiers().setVnfId(vnfId); - VNFContext vnfContext = commandExecutorInput.getVnfContext(); - vnfContext.setType(vnfType); - vnfContext.setId(vnfId); - vnfContext.setVersion(vnfVersion); - return commandExecutorInput; - } - - private RuntimeContext createCommandExecutorInputWithSubObjects() { - return createRuntimeContextWithSubObjects(); - } - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutor.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutor.java deleted file mode 100644 index cd02c260d..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutor.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executor; -/** - * - */ - - -import java.time.Instant; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executionqueue.ExecutionQueueService; -import org.onap.appc.executor.impl.*; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.workflow.WorkFlowManager; -import org.powermock.api.mockito.PowerMockito; - -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import static junit.framework.Assert.assertTrue; -import static org.powermock.api.support.membermodification.MemberMatcher.method; - - -@SuppressWarnings("deprecation") -public class TestCommandExecutor { - - private static final String TTL_FLAG= "TTL"; - private static final String API_VERSION= "2.0.0"; - private static final String ORIGINATOR_ID= "1"; - - private CommandExecutorImpl commandExecutor; - - private CommandTaskFactory executionTaskFactory; - - private RequestHandler requestHandler; - private WorkFlowManager workflowManager; - private LifecycleManager lifecyclemanager; - - private ExecutionQueueService executionQueueService; - private Instant timeStamp = Instant.now(); - private String requestId = "1"; - private RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30000, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ; - private RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", - timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; - - @Before - public void init()throws Exception { - requestHandler= Mockito.mock(RequestHandler.class); - lifecyclemanager= Mockito.mock(LifecycleManager.class); - workflowManager= Mockito.mock(WorkFlowManager.class); - - executionQueueService = Mockito.mock(ExecutionQueueService.class); - - commandExecutor = new CommandExecutorImpl(); - executionTaskFactory = Mockito.mock(CommandTaskFactory.class); - commandExecutor.setExecutionTaskFactory(executionTaskFactory); - commandExecutor.setExecutionQueueService(executionQueueService); - LCMCommandTask lcmCommandTask = Mockito.mock(LCMCommandTask.class); - LCMReadonlyCommandTask lCMReadonlyCommandTask = Mockito.mock(LCMReadonlyCommandTask.class); - - Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputConfigure)).thenReturn(lcmCommandTask); - Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputSync)).thenReturn(lCMReadonlyCommandTask); - -// Mockito.when(executionQueueService.putMessage((Runnable) Mockito.anyObject(),Mockito.anyLong(),(TimeUnit)Mockito.anyObject())).thenReturn(true); - - } - - - @Test - public void testPositiveFlow_LCM() throws Exception { - //Map flags = setTTLInFlags("30"); - String requestId = "1"; - RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure, "15", "") ; - try { - commandExecutor.executeCommand(commandExecutorInput); - } catch (APPCException e) { - Assert.fail(e.toString()); - } - - } - - @Test - public void testPositiveFlow_GetConfig(){ - String requestId = "1"; - - RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ; - try { - commandExecutor.executeCommand(commandExecutorInput); - } catch (APPCException e) { - Assert.fail(e.toString()); - } - - } - - - private RuntimeContext pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Instant timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){ - RuntimeContext commandExecutorInput = createCommandExecutorInputWithSubObjects(); - RequestContext requestContext = commandExecutorInput.getRequestContext(); - requestContext.getCommonHeader().setFlags(new Flags(null, false, ttl)); - requestContext.getCommonHeader().setApiVer(apiVersion); - requestContext.getCommonHeader().setTimestamp(timeStamp); - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestID); - requestContext.getCommonHeader().setOriginatorId(originatorID); - requestContext.setAction(action); - requestContext.setPayload(payload); - requestContext.getActionIdentifiers().setVnfId(vnfId); - VNFContext vnfContext = commandExecutorInput.getVnfContext(); - vnfContext.setType(vnfType); - vnfContext.setId(vnfId); - vnfContext.setVersion(vnfVersion); - return commandExecutorInput; - } - - private RuntimeContext createCommandExecutorInputWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - } - - - -} diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..c5130b3ab --- /dev/null +++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,91 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +#org.onap.appc.bootstrap.file=executor-test.properties +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + + +# +# Certificate keystore and truststore +# +#org.openecomp.sdnc.sli.aai.ssl.trust= +#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin +#org.openecomp.sdnc.sli.aai.ssl.key= +#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin +org.openecomp.sdnc.sli.aai.host.certificate.ignore=true +org.openecomp.sdnc.sli.aai.certificate.trust.all=true + + +# +# Configuration file for A&AI Adapter +# + +# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT +org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 + +org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query + +# service instance +org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances +org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance + +# complex +org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes +org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} + +# vservers +org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers +org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} + +# generic-vnf +org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ +org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} + +# +# Formatting +# +org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s +org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type +org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id +org.openecomp.sdnc.sli.aai.param.service.type=service-type + +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + +org.onap.appc.db.url.%s", schema), ""); +org.onap.appc.db.user.%s", schema), ""); +org.onap.appc.db.pass.%s", schema), ""); + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-CMD-EXECUTOR-TEST +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index c5130b3ab..000000000 --- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,91 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -#org.onap.appc.bootstrap.file=executor-test.properties -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - - -# -# Certificate keystore and truststore -# -#org.openecomp.sdnc.sli.aai.ssl.trust= -#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin -#org.openecomp.sdnc.sli.aai.ssl.key= -#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin -org.openecomp.sdnc.sli.aai.host.certificate.ignore=true -org.openecomp.sdnc.sli.aai.certificate.trust.all=true - - -# -# Configuration file for A&AI Adapter -# - -# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT -org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 - -org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query - -# service instance -org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances -org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance - -# complex -org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes -org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} - -# vservers -org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers -org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} - -# generic-vnf -org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ -org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} - -# -# Formatting -# -org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s -org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type -org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id -org.openecomp.sdnc.sli.aai.param.service.type=service-type - -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - -org.onap.appc.db.url.%s", schema), ""); -org.onap.appc.db.user.%s", schema), ""); -org.onap.appc.db.pass.%s", schema), ""); - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-CMD-EXECUTOR-TEST -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcJdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcJdbcConnectionFactory.java new file mode 100644 index 000000000..e62f03da3 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcJdbcConnectionFactory.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +import java.sql.Connection; +import java.sql.SQLException; + +public class AppcJdbcConnectionFactory implements JdbcConnectionFactory { + + private String schema; + + public void setSchema(String schema) { + this.schema = schema; + } + + public Connection openDbConnection() { + try { + return DBUtils.getConnection(schema); + } catch(SQLException e) { + throw new JdbcRuntimeException(Messages.EXP_APPC_JDBC_CONNECT.format(schema), e); + } + } + + public void closeDbConnection(Connection connection) { + try { + connection.close(); + } catch(SQLException e) { + throw new JdbcRuntimeException(Messages.EXP_APPC_JDBC_DISCONNECT.format(schema), e); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DBUtils.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DBUtils.java new file mode 100644 index 000000000..447dce8fc --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DBUtils.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +import java.sql.*; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +@Deprecated +public class DBUtils { + private static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver"; + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + static { + try { + String driver = JDBC_DRIVER; + Class.forName(driver); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + public static Connection getConnection(String schema) throws SQLException { + DriverManager.registerDriver(new org.mariadb.jdbc.Driver()); + String dbURL = configuration.getProperty(String.format("org.onap.appc.db.url.%s", schema), ""); + String userName = configuration.getProperty(String.format("org.onap.appc.db.user.%s", schema), ""); + String password = configuration.getProperty(String.format("org.onap.appc.db.pass.%s", schema), ""); + return DriverManager.getConnection(dbURL, userName, password); + } + + public static boolean clearResources(ResultSet resultSet, PreparedStatement ptmt, Connection connection) { + boolean clearFlag = false; + try { + if (resultSet != null) + resultSet.close(); + if (ptmt != null) + ptmt.close(); + if (connection != null) + connection.close(); + clearFlag = true; + } catch (SQLException e) { + + } + return clearFlag; + + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DefaultJdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DefaultJdbcConnectionFactory.java new file mode 100644 index 000000000..88599ac72 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/DefaultJdbcConnectionFactory.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public abstract class DefaultJdbcConnectionFactory implements JdbcConnectionFactory { + + private static boolean driverRegistered = false; + + private String jdbcURL; + private String jdbcUserName; + private String jdbcPassword; + + public void setJdbcURL(String jdbcURL) { + this.jdbcURL = jdbcURL; + } + + public void setJdbcUserName(String jdbcUserName) { + this.jdbcUserName = jdbcUserName; + } + + public void setJdbcPassword(String jdbcPassword) { + this.jdbcPassword = jdbcPassword; + } + + + protected abstract void registedDriver() throws SQLException; + + @Override + public Connection openDbConnection() { + try { + if(!driverRegistered) { + registedDriver(); + driverRegistered = true; + } + return DriverManager.getConnection(jdbcURL, jdbcUserName, jdbcPassword); + } catch(SQLException e) { + throw new JdbcRuntimeException(Messages.EXP_JDBC_CONNECT.format(jdbcURL), e); + } + } + + @Override + public void closeDbConnection(Connection connection) { + try { + connection.close(); + } catch(SQLException e) { + throw new JdbcRuntimeException(Messages.EXP_JDBC_DISCONNECT.format(jdbcURL), e); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcConnectionFactory.java new file mode 100644 index 000000000..1a47db3f7 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcConnectionFactory.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +import java.sql.Connection; + +public interface JdbcConnectionFactory { + + Connection openDbConnection(); + void closeDbConnection(Connection connection); +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcRuntimeException.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcRuntimeException.java new file mode 100644 index 000000000..8e606fe94 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/JdbcRuntimeException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +public class JdbcRuntimeException extends RuntimeException { + + public JdbcRuntimeException(String message) { + super(message); + } + + public JdbcRuntimeException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/Messages.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/Messages.java new file mode 100644 index 000000000..6330793b7 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/Messages.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dao.util; + +public enum Messages { + EXP_JDBC_CONNECT("Error connecting to JDBC URL [%s]."), + EXP_JDBC_DISCONNECT("Error closing JDBC connection to URL [%s]."), + EXP_APPC_JDBC_CONNECT("Error connecting to JDBC using properties for schema [%s]"), + EXP_APPC_JDBC_DISCONNECT("Error closing JDBC connection for schema [%s]."); + + private String message; + + Messages(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public String format(Object... s) { + return String.format(message, s); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/AppcJdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/AppcJdbcConnectionFactory.java deleted file mode 100644 index e62f03da3..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/AppcJdbcConnectionFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -import java.sql.Connection; -import java.sql.SQLException; - -public class AppcJdbcConnectionFactory implements JdbcConnectionFactory { - - private String schema; - - public void setSchema(String schema) { - this.schema = schema; - } - - public Connection openDbConnection() { - try { - return DBUtils.getConnection(schema); - } catch(SQLException e) { - throw new JdbcRuntimeException(Messages.EXP_APPC_JDBC_CONNECT.format(schema), e); - } - } - - public void closeDbConnection(Connection connection) { - try { - connection.close(); - } catch(SQLException e) { - throw new JdbcRuntimeException(Messages.EXP_APPC_JDBC_DISCONNECT.format(schema), e); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DBUtils.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DBUtils.java deleted file mode 100644 index 447dce8fc..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DBUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -import java.sql.*; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -@Deprecated -public class DBUtils { - private static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver"; - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - static { - try { - String driver = JDBC_DRIVER; - Class.forName(driver); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - public static Connection getConnection(String schema) throws SQLException { - DriverManager.registerDriver(new org.mariadb.jdbc.Driver()); - String dbURL = configuration.getProperty(String.format("org.onap.appc.db.url.%s", schema), ""); - String userName = configuration.getProperty(String.format("org.onap.appc.db.user.%s", schema), ""); - String password = configuration.getProperty(String.format("org.onap.appc.db.pass.%s", schema), ""); - return DriverManager.getConnection(dbURL, userName, password); - } - - public static boolean clearResources(ResultSet resultSet, PreparedStatement ptmt, Connection connection) { - boolean clearFlag = false; - try { - if (resultSet != null) - resultSet.close(); - if (ptmt != null) - ptmt.close(); - if (connection != null) - connection.close(); - clearFlag = true; - } catch (SQLException e) { - - } - return clearFlag; - - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DefaultJdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DefaultJdbcConnectionFactory.java deleted file mode 100644 index 88599ac72..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/DefaultJdbcConnectionFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public abstract class DefaultJdbcConnectionFactory implements JdbcConnectionFactory { - - private static boolean driverRegistered = false; - - private String jdbcURL; - private String jdbcUserName; - private String jdbcPassword; - - public void setJdbcURL(String jdbcURL) { - this.jdbcURL = jdbcURL; - } - - public void setJdbcUserName(String jdbcUserName) { - this.jdbcUserName = jdbcUserName; - } - - public void setJdbcPassword(String jdbcPassword) { - this.jdbcPassword = jdbcPassword; - } - - - protected abstract void registedDriver() throws SQLException; - - @Override - public Connection openDbConnection() { - try { - if(!driverRegistered) { - registedDriver(); - driverRegistered = true; - } - return DriverManager.getConnection(jdbcURL, jdbcUserName, jdbcPassword); - } catch(SQLException e) { - throw new JdbcRuntimeException(Messages.EXP_JDBC_CONNECT.format(jdbcURL), e); - } - } - - @Override - public void closeDbConnection(Connection connection) { - try { - connection.close(); - } catch(SQLException e) { - throw new JdbcRuntimeException(Messages.EXP_JDBC_DISCONNECT.format(jdbcURL), e); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcConnectionFactory.java deleted file mode 100644 index 1a47db3f7..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcConnectionFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -import java.sql.Connection; - -public interface JdbcConnectionFactory { - - Connection openDbConnection(); - void closeDbConnection(Connection connection); -} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcRuntimeException.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcRuntimeException.java deleted file mode 100644 index 8e606fe94..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/JdbcRuntimeException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -public class JdbcRuntimeException extends RuntimeException { - - public JdbcRuntimeException(String message) { - super(message); - } - - public JdbcRuntimeException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/Messages.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/Messages.java deleted file mode 100644 index 6330793b7..000000000 --- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/openecomp/appc/dao/util/Messages.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dao.util; - -public enum Messages { - EXP_JDBC_CONNECT("Error connecting to JDBC URL [%s]."), - EXP_JDBC_DISCONNECT("Error closing JDBC connection to URL [%s]."), - EXP_APPC_JDBC_CONNECT("Error connecting to JDBC using properties for schema [%s]"), - EXP_APPC_JDBC_DISCONNECT("Error closing JDBC connection for schema [%s]."); - - private String message; - - Messages(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - - public String format(Object... s) { - return String.format(message, s); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionIdentifiers.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionIdentifiers.java new file mode 100644 index 000000000..bb5b4cdab --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionIdentifiers.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + + +public class ActionIdentifiers { + private String serviceInstanceId; + private String vnfId; + private String vnfcName; + private String vfModuleId; + private String vServerId; + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfcName() { + return vnfcName; + } + + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + public String getVserverId() { + return vServerId; + } + + public void setvServerId(String vServerId) { + this.vServerId = vServerId; + } + + public String getVfModuleId() { + return vfModuleId; + } + + public void setVfModuleId(String vfModuleId) { + this.vfModuleId = vfModuleId; + } + + @Override + public String toString() { + return "ActionIdentifiers{" + + "serviceInstanceId='" + serviceInstanceId + '\'' + + ", vnfId='" + vnfId + '\'' + + ", vfModuleId ='" + vfModuleId + '\'' + + ", vnfcName='" + vnfcName + '\'' + + ", vServerId='" + vServerId + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionLevel.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionLevel.java new file mode 100644 index 000000000..230812cef --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ActionLevel.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +public enum ActionLevel { + VNF,VM,VNFC +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/CommonHeader.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/CommonHeader.java new file mode 100644 index 000000000..7c44efecb --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/CommonHeader.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +import java.time.Instant; + + +public class CommonHeader { + + private Flags flags; + private Instant timestamp; + private String apiVer; + private String originatorId; + private String requestId; + private String subRequestId; + + public Flags getFlags() { + return flags; + } + + public void setFlags(Flags flags) { + this.flags = flags; + } + + public Instant getTimeStamp() { + return timestamp; + } + + public void setTimestamp(Instant timestamp) { + this.timestamp = timestamp; + } + + public String getApiVer() { + return apiVer; + } + + public void setApiVer(String apiVer) { + this.apiVer = apiVer; + } + + public String getOriginatorId() { + return originatorId; + } + + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getSubRequestId() { + return subRequestId; + } + + public void setSubRequestId(String subRequestId) { + this.subRequestId = subRequestId; + } + + @Override + public String toString() { + return "CommonHeader{" + + "flags=" + flags + + ", timestamp=" + timestamp + + ", apiVer='" + apiVer + '\'' + + ", originatorId='" + originatorId + '\'' + + ", requestId='" + requestId + '\'' + + ", subRequestId='" + subRequestId + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Flags.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Flags.java new file mode 100644 index 000000000..4102955f0 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Flags.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + + +public class Flags { + + private final boolean force; + private final int ttl; + private final Mode mode; + + public Flags(Mode mode, boolean force, int ttl) { + super(); + this.force = force; + this.ttl = ttl; + this.mode = mode; + } + + public boolean isForce() { + return force; + } + + public int getTtl() { + return ttl; + } + + public Mode getMode() { + return mode; + } + + @Override + public String toString() { + return "Flags{" + + "force=" + force + + ", ttl=" + ttl + + ", mode=" + mode + + '}'; + } + + public enum Mode { + EXCLUSIVE, + NORMAL + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/OperationType.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/OperationType.java new file mode 100644 index 000000000..b5b017e40 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/OperationType.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +public enum OperationType { + ReadOnly,BuiltIn,OrchestrationStatusUpdate,OperationStatusUpdate +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RequestContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RequestContext.java new file mode 100644 index 000000000..12ad5ae95 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RequestContext.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +import java.util.HashMap; +import java.util.Map; + + +public class RequestContext { + + private CommonHeader commonHeader; + private ActionIdentifiers actionIdentifiers; + private VNFOperation action; + private ActionLevel actionLevel; + private String payload; + private Map additionalContext; + + public CommonHeader getCommonHeader() { + return commonHeader; + } + + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + public VNFOperation getAction() { + return action; + } + + public void setAction(VNFOperation action) { + this.action = action; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Map getAdditionalContext() { + return additionalContext; + } + + public void setAdditionalContext(Map additionalContext) { + this.additionalContext = additionalContext; + } + + public void addKeyValueToAdditionalContext(String key, String value ){ + if (this.additionalContext == null) { + this.additionalContext = new HashMap<>(); + } + this.additionalContext.put(key, value); + } + + public ActionLevel getActionLevel() { + return actionLevel; + } + + public void setActionLevel(ActionLevel actionLevel) { + this.actionLevel = actionLevel; + } + + @Override + public String toString() { + return "RequestContext{" + + "commonHeader=" + commonHeader + + ", actionIdentifiers=" + actionIdentifiers + + ", action=" + action + + ", actionLevel = " + actionLevel + + ", payload='" + payload + '\'' + + ", additionalContext=" + additionalContext + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ResponseContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ResponseContext.java new file mode 100644 index 000000000..da3a6be69 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/ResponseContext.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +import java.util.HashMap; +import java.util.Map; + + +public class ResponseContext { + private CommonHeader commonHeader; + private Status status; + private String payload; + private Map additionalContext; + + public CommonHeader getCommonHeader() { + return commonHeader; + } + + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Map getAdditionalContext() { + return additionalContext; + } + + public void setAdditionalContext(Map additionalContext) { + this.additionalContext = additionalContext; + } + + public void addKeyValueToAdditionalContext(String key, String value ){ + if (this.additionalContext == null) { + this.additionalContext = new HashMap<>(); + } + this.additionalContext.put(key, value); + } + + @Override + public String toString() { + return "ResponseContext{" + + "commonHeader=" + commonHeader + + ", status=" + status + + ", payload='" + payload + '\'' + + ", additionalContext=" + additionalContext + + '}'; + } + +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RuntimeContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RuntimeContext.java new file mode 100644 index 000000000..2580f1830 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/RuntimeContext.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +import java.time.Instant; +import java.util.Date; + + +public class RuntimeContext { + + private RequestContext requestContext; + private ResponseContext responseContext; + private VNFContext vnfContext; + + //TODO move fields timeStart abd isLockAcquired to a better place + private Instant timeStart; + private boolean isLockAcquired; + private String rpcName; + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public Instant getTimeStart() { + return timeStart; + } + + public boolean isLockAcquired() { + return isLockAcquired; + } + + public void setIsLockAcquired(boolean isLockAcquired) { + this.isLockAcquired = isLockAcquired; + } + + public void setTimeStart(Instant timeStart) { + this.timeStart = timeStart; + } + + public RequestContext getRequestContext() { + return requestContext; + } + + public void setRequestContext(RequestContext requestContext) { + this.requestContext = requestContext; + } + + public ResponseContext getResponseContext() { + return responseContext; + } + + public void setResponseContext(ResponseContext responseContext) { + this.responseContext = responseContext; + } + + public VNFContext getVnfContext() { + return vnfContext; + } + + public void setVnfContext(VNFContext vnfContext) { + this.vnfContext = vnfContext; + } + + @Override + public String toString() { + return "RuntimeContext{" + + "requestContext=" + requestContext + + ", responseContext=" + responseContext + + ", vnfContext=" + vnfContext + + ", timeStart=" + timeStart + + ", isLockAcquired=" + isLockAcquired + + ", rpcName='" + rpcName + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Status.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Status.java new file mode 100644 index 000000000..2f8fd1950 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/Status.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + + +public class Status { + + private final int code; + private final String message; + + public Status(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "Status{" + + "code='" + code + '\'' + + ", message='" + message + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFContext.java new file mode 100644 index 000000000..bcc31fcec --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFContext.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + + +public class VNFContext { + private String id; + private String type; + private String version; + private String status; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + + @Override + public String toString() { + return "VNFContext{" + + "id='" + id + '\'' + + ", type='" + type + '\'' + + ", version='" + version + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFOperation.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFOperation.java new file mode 100644 index 000000000..228005d34 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/onap/appc/domainmodel/lcm/VNFOperation.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel.lcm; + +public enum VNFOperation { + Configure, Test, HealthCheck, Start, Terminate, Restart, Rebuild, Stop, ConfigModify, + ConfigScaleOut,ConfigRestore,Backup, Snapshot, + SoftwareUpload, LiveUpgrade, Rollback, Test_lic, Migrate, Evacuate,StopApplication, StartApplication, + Sync(OperationType.ReadOnly), Audit(OperationType.ReadOnly), + ConfigBackup(OperationType.ReadOnly),ConfigBackupDelete(OperationType.ReadOnly),ConfigExport(OperationType.ReadOnly), + Lock(OperationType.BuiltIn), Unlock(OperationType.BuiltIn), CheckLock(OperationType.BuiltIn); + + private OperationType operationType; + + VNFOperation(OperationType operationType){ + this.operationType=operationType; + } + + VNFOperation() { + this.operationType=OperationType.OrchestrationStatusUpdate; + } + /** + * Operations handled directly by the RequestHandler without further call to DG are built-in operations. + */ + public boolean isBuiltIn() { + return this.operationType.equals(OperationType.BuiltIn); + } + + public OperationType getOperationType() { + return operationType; + } + + public static VNFOperation findByString(String operationName) { + for(VNFOperation operation: VNFOperation.values()) { + if(operation.name().equals(operationName)) { + return operation; + } + } + return null; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionIdentifiers.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionIdentifiers.java deleted file mode 100644 index bb5b4cdab..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionIdentifiers.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - - -public class ActionIdentifiers { - private String serviceInstanceId; - private String vnfId; - private String vnfcName; - private String vfModuleId; - private String vServerId; - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getVnfId() { - return vnfId; - } - - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - public String getVnfcName() { - return vnfcName; - } - - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - public String getVserverId() { - return vServerId; - } - - public void setvServerId(String vServerId) { - this.vServerId = vServerId; - } - - public String getVfModuleId() { - return vfModuleId; - } - - public void setVfModuleId(String vfModuleId) { - this.vfModuleId = vfModuleId; - } - - @Override - public String toString() { - return "ActionIdentifiers{" + - "serviceInstanceId='" + serviceInstanceId + '\'' + - ", vnfId='" + vnfId + '\'' + - ", vfModuleId ='" + vfModuleId + '\'' + - ", vnfcName='" + vnfcName + '\'' + - ", vServerId='" + vServerId + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java deleted file mode 100644 index 230812cef..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -public enum ActionLevel { - VNF,VM,VNFC -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/CommonHeader.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/CommonHeader.java deleted file mode 100644 index 7c44efecb..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/CommonHeader.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -import java.time.Instant; - - -public class CommonHeader { - - private Flags flags; - private Instant timestamp; - private String apiVer; - private String originatorId; - private String requestId; - private String subRequestId; - - public Flags getFlags() { - return flags; - } - - public void setFlags(Flags flags) { - this.flags = flags; - } - - public Instant getTimeStamp() { - return timestamp; - } - - public void setTimestamp(Instant timestamp) { - this.timestamp = timestamp; - } - - public String getApiVer() { - return apiVer; - } - - public void setApiVer(String apiVer) { - this.apiVer = apiVer; - } - - public String getOriginatorId() { - return originatorId; - } - - public void setOriginatorId(String originatorId) { - this.originatorId = originatorId; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getSubRequestId() { - return subRequestId; - } - - public void setSubRequestId(String subRequestId) { - this.subRequestId = subRequestId; - } - - @Override - public String toString() { - return "CommonHeader{" + - "flags=" + flags + - ", timestamp=" + timestamp + - ", apiVer='" + apiVer + '\'' + - ", originatorId='" + originatorId + '\'' + - ", requestId='" + requestId + '\'' + - ", subRequestId='" + subRequestId + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Flags.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Flags.java deleted file mode 100644 index 4102955f0..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Flags.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - - -public class Flags { - - private final boolean force; - private final int ttl; - private final Mode mode; - - public Flags(Mode mode, boolean force, int ttl) { - super(); - this.force = force; - this.ttl = ttl; - this.mode = mode; - } - - public boolean isForce() { - return force; - } - - public int getTtl() { - return ttl; - } - - public Mode getMode() { - return mode; - } - - @Override - public String toString() { - return "Flags{" + - "force=" + force + - ", ttl=" + ttl + - ", mode=" + mode + - '}'; - } - - public enum Mode { - EXCLUSIVE, - NORMAL - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/OperationType.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/OperationType.java deleted file mode 100644 index b5b017e40..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/OperationType.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -public enum OperationType { - ReadOnly,BuiltIn,OrchestrationStatusUpdate,OperationStatusUpdate -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RequestContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RequestContext.java deleted file mode 100644 index 12ad5ae95..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RequestContext.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -import java.util.HashMap; -import java.util.Map; - - -public class RequestContext { - - private CommonHeader commonHeader; - private ActionIdentifiers actionIdentifiers; - private VNFOperation action; - private ActionLevel actionLevel; - private String payload; - private Map additionalContext; - - public CommonHeader getCommonHeader() { - return commonHeader; - } - - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - public VNFOperation getAction() { - return action; - } - - public void setAction(VNFOperation action) { - this.action = action; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public Map getAdditionalContext() { - return additionalContext; - } - - public void setAdditionalContext(Map additionalContext) { - this.additionalContext = additionalContext; - } - - public void addKeyValueToAdditionalContext(String key, String value ){ - if (this.additionalContext == null) { - this.additionalContext = new HashMap<>(); - } - this.additionalContext.put(key, value); - } - - public ActionLevel getActionLevel() { - return actionLevel; - } - - public void setActionLevel(ActionLevel actionLevel) { - this.actionLevel = actionLevel; - } - - @Override - public String toString() { - return "RequestContext{" + - "commonHeader=" + commonHeader + - ", actionIdentifiers=" + actionIdentifiers + - ", action=" + action + - ", actionLevel = " + actionLevel + - ", payload='" + payload + '\'' + - ", additionalContext=" + additionalContext + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ResponseContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ResponseContext.java deleted file mode 100644 index da3a6be69..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ResponseContext.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -import java.util.HashMap; -import java.util.Map; - - -public class ResponseContext { - private CommonHeader commonHeader; - private Status status; - private String payload; - private Map additionalContext; - - public CommonHeader getCommonHeader() { - return commonHeader; - } - - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public Map getAdditionalContext() { - return additionalContext; - } - - public void setAdditionalContext(Map additionalContext) { - this.additionalContext = additionalContext; - } - - public void addKeyValueToAdditionalContext(String key, String value ){ - if (this.additionalContext == null) { - this.additionalContext = new HashMap<>(); - } - this.additionalContext.put(key, value); - } - - @Override - public String toString() { - return "ResponseContext{" + - "commonHeader=" + commonHeader + - ", status=" + status + - ", payload='" + payload + '\'' + - ", additionalContext=" + additionalContext + - '}'; - } - -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RuntimeContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RuntimeContext.java deleted file mode 100644 index 2580f1830..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RuntimeContext.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -import java.time.Instant; -import java.util.Date; - - -public class RuntimeContext { - - private RequestContext requestContext; - private ResponseContext responseContext; - private VNFContext vnfContext; - - //TODO move fields timeStart abd isLockAcquired to a better place - private Instant timeStart; - private boolean isLockAcquired; - private String rpcName; - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public Instant getTimeStart() { - return timeStart; - } - - public boolean isLockAcquired() { - return isLockAcquired; - } - - public void setIsLockAcquired(boolean isLockAcquired) { - this.isLockAcquired = isLockAcquired; - } - - public void setTimeStart(Instant timeStart) { - this.timeStart = timeStart; - } - - public RequestContext getRequestContext() { - return requestContext; - } - - public void setRequestContext(RequestContext requestContext) { - this.requestContext = requestContext; - } - - public ResponseContext getResponseContext() { - return responseContext; - } - - public void setResponseContext(ResponseContext responseContext) { - this.responseContext = responseContext; - } - - public VNFContext getVnfContext() { - return vnfContext; - } - - public void setVnfContext(VNFContext vnfContext) { - this.vnfContext = vnfContext; - } - - @Override - public String toString() { - return "RuntimeContext{" + - "requestContext=" + requestContext + - ", responseContext=" + responseContext + - ", vnfContext=" + vnfContext + - ", timeStart=" + timeStart + - ", isLockAcquired=" + isLockAcquired + - ", rpcName='" + rpcName + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Status.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Status.java deleted file mode 100644 index 2f8fd1950..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/Status.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - - -public class Status { - - private final int code; - private final String message; - - public Status(int code, String message) { - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - @Override - public String toString() { - return "Status{" + - "code='" + code + '\'' + - ", message='" + message + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFContext.java deleted file mode 100644 index bcc31fcec..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFContext.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - - -public class VNFContext { - private String id; - private String type; - private String version; - private String status; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - - @Override - public String toString() { - return "VNFContext{" + - "id='" + id + '\'' + - ", type='" + type + '\'' + - ", version='" + version + '\'' + - ", status='" + status + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFOperation.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFOperation.java deleted file mode 100644 index 228005d34..000000000 --- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/VNFOperation.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel.lcm; - -public enum VNFOperation { - Configure, Test, HealthCheck, Start, Terminate, Restart, Rebuild, Stop, ConfigModify, - ConfigScaleOut,ConfigRestore,Backup, Snapshot, - SoftwareUpload, LiveUpgrade, Rollback, Test_lic, Migrate, Evacuate,StopApplication, StartApplication, - Sync(OperationType.ReadOnly), Audit(OperationType.ReadOnly), - ConfigBackup(OperationType.ReadOnly),ConfigBackupDelete(OperationType.ReadOnly),ConfigExport(OperationType.ReadOnly), - Lock(OperationType.BuiltIn), Unlock(OperationType.BuiltIn), CheckLock(OperationType.BuiltIn); - - private OperationType operationType; - - VNFOperation(OperationType operationType){ - this.operationType=operationType; - } - - VNFOperation() { - this.operationType=OperationType.OrchestrationStatusUpdate; - } - /** - * Operations handled directly by the RequestHandler without further call to DG are built-in operations. - */ - public boolean isBuiltIn() { - return this.operationType.equals(OperationType.BuiltIn); - } - - public OperationType getOperationType() { - return operationType; - } - - public static VNFOperation findByString(String operationName) { - for(VNFOperation operation: VNFOperation.values()) { - if(operation.name().equals(operationName)) { - return operation; - } - } - return null; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/ExecutionQueueService.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/ExecutionQueueService.java new file mode 100644 index 000000000..1423962ef --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/ExecutionQueueService.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue; + +import java.util.concurrent.TimeUnit; + +import org.onap.appc.exceptions.APPCException; + +public interface ExecutionQueueService { + void putMessage(M message) throws APPCException; + void putMessage(M message, long timeout, TimeUnit unit) throws APPCException; + void registerMessageExpirationListener(MessageExpirationListener listener); +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/MessageExpirationListener.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/MessageExpirationListener.java new file mode 100644 index 000000000..c1f3592c6 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/MessageExpirationListener.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue; + +public interface MessageExpirationListener { + void onMessageExpiration(M message); +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/helper/Util.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/helper/Util.java new file mode 100644 index 000000000..58279e8a7 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/helper/Util.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue.helper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.executionqueue.impl.QueueManager; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +public class Util { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(Util.class); + private final int default_queue_size = 10; + private final int default_threadpool_size = 10; + private final String queue_size_key = "appc.dispatcher.executionqueue.backlog.size"; + private final String threadpool_size_key = "appc.dispatcher.executionqueue.threadpool.size"; + + private Configuration configuration; + + /** + * Initialization. + *

Used by blueprint. + */ + public void init() { + + configuration = ConfigurationFactory.getConfiguration(); + } + + public int getExecutionQueueSize() { + String sizeStr = configuration.getProperty(queue_size_key, String.valueOf(default_queue_size)); + + int size = default_queue_size; + try { + size = Integer.parseInt(sizeStr); + } catch (NumberFormatException e) { + logger.error("Error while parse key:" + queue_size_key + " got from configuration " + e.getMessage(), e); + } + + return size; + } + + public int getThreadPoolSize() { + String sizeStr = configuration.getProperty(threadpool_size_key, String.valueOf(default_threadpool_size)); + + int size = default_threadpool_size; + try { + size = Integer.parseInt(sizeStr); + } catch (NumberFormatException e) { + logger.error("Error while parse key:" + threadpool_size_key + " got from configuration " + + e.getMessage(), e); + } + + return size; + } + + public ThreadFactory getThreadFactory(final boolean isDaemon, final String threadNamePrefix) { + return new ThreadFactory() { + private final String THREAD_NAME_PATTERN = "%s-%d"; + private final ThreadFactory factory = Executors.defaultThreadFactory(); + private final AtomicInteger counter = new AtomicInteger(); + + public Thread newThread(Runnable r) { + Thread t = factory.newThread(r); + t.setDaemon(isDaemon); + if (threadNamePrefix != null && !threadNamePrefix.isEmpty()) { + final String threadName = String.format(THREAD_NAME_PATTERN, threadNamePrefix, counter + .incrementAndGet()); + t.setName(threadName); + } + return t; + } + }; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceFactory.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceFactory.java new file mode 100644 index 000000000..f071be6f0 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceFactory.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue.impl; + +import org.onap.appc.executionqueue.ExecutionQueueService; + +public class ExecutionQueueServiceFactory { + + private static class ExecutionQueueServiceHolder { + public static final ExecutionQueueService executionQueueService = new ExecutionQueueServiceImpl(); + } + + public static ExecutionQueueService getExecutionQueueService() { + return ExecutionQueueServiceHolder.executionQueueService; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceImpl.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceImpl.java new file mode 100644 index 000000000..0634a0eb2 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/ExecutionQueueServiceImpl.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executionqueue.ExecutionQueueService; +import org.onap.appc.executionqueue.MessageExpirationListener; +import org.onap.appc.executionqueue.impl.object.QueueMessage; + +import java.time.Instant; +import java.util.concurrent.TimeUnit; + +public class ExecutionQueueServiceImpl implements ExecutionQueueService { + + private static final EELFLogger logger = + EELFManager.getInstance().getLogger(ExecutionQueueServiceImpl.class); + + private QueueManager queueManager; + + public ExecutionQueueServiceImpl() { + //do nothing + } + + /** + * Injected by blueprint + * + * @param queueManager queue manager to be set + */ + public void setQueueManager(QueueManager queueManager) { + this.queueManager = queueManager; + } + + @Override + public void putMessage(M message) throws APPCException { + this.putMessage(message, -1, null); + } + + @Override + public void putMessage(M message, long timeout, TimeUnit unit) throws APPCException { + Instant expirationTime = calculateExpirationTime(timeout, unit); + boolean enqueueTask = queueManager.enqueueTask(new QueueMessage<>(message, expirationTime)); + if (!enqueueTask) { + logger.error("Error in putMessage method of ExecutionQueueServiceImpl"); + throw new APPCException("Failed to put message in queue"); + } + } + + @Override + public void registerMessageExpirationListener(MessageExpirationListener listener) { + queueManager.setListener(listener); + } + + private Instant calculateExpirationTime(long timeToLive, TimeUnit unit) { + if (timeToLive > 0 && unit != null) { + // as of Java 8, there is no built-in conversion method from + // TimeUnit to ChronoUnit; do it manually + return Instant.now().plusMillis(unit.toMillis(timeToLive)); + } else { + // never expires + return Instant.MAX; + } + } + +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/QueueManager.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/QueueManager.java new file mode 100644 index 000000000..db0e3d4c5 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/QueueManager.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.executionqueue.MessageExpirationListener; +import org.onap.appc.executionqueue.helper.Util; +import org.onap.appc.executionqueue.impl.object.QueueMessage; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class QueueManager { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(QueueManager.class); + + private MessageExpirationListener listener; + private ExecutorService messageExecutor; + private int max_thread_size; + private int max_queue_size; + private Util executionQueueUtil; + + public QueueManager() { + //do nothing + } + + /** + * Initialization method used by blueprint + */ + public void init() { + max_thread_size = executionQueueUtil.getThreadPoolSize(); + max_queue_size = executionQueueUtil.getExecutionQueueSize(); + messageExecutor = new ThreadPoolExecutor( + max_thread_size, + max_thread_size, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(max_queue_size), + executionQueueUtil.getThreadFactory(true, "appc-dispatcher"), + new ThreadPoolExecutor.AbortPolicy()); + } + + /** + * Destory method used by blueprint + */ + public void stop() { + // Disable new tasks from being submitted + messageExecutor.shutdown(); + List rejectedRunnables = messageExecutor.shutdownNow(); + logger.info(String.format("Rejected %d waiting tasks include ", rejectedRunnables.size())); + + try { + messageExecutor.shutdownNow(); // Cancel currently executing tasks + // Wait a while for tasks to respond to being cancelled + while (!messageExecutor.awaitTermination(100, TimeUnit.MILLISECONDS)) { + logger.debug("QueueManager is being shut down because it still has threads not interrupted"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + messageExecutor.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } + + public void setListener(MessageExpirationListener listener) { + this.listener = listener; + } + + /** + * Injected by blueprint + * + * @param executionQueueUtil Util to be set + */ + public void setExecutionQueueUtil(Util executionQueueUtil) { + this.executionQueueUtil = executionQueueUtil; + } + + public boolean enqueueTask(QueueMessage queueMessage) { + boolean isEnqueued = true; + try { + messageExecutor.execute(() -> { + if (queueMessage.isExpired()) { + logger.debug("Message expired " + queueMessage.getMessage()); + if (listener != null) { + listener.onMessageExpiration(queueMessage.getMessage()); + } else { + logger.warn("Listener not available for expired message "); + } + } else { + queueMessage.getMessage().run(); + } + }); + } catch (RejectedExecutionException ree) { + isEnqueued = false; + } + + return isEnqueued; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/object/QueueMessage.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/object/QueueMessage.java new file mode 100644 index 000000000..bb48da7e5 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/onap/appc/executionqueue/impl/object/QueueMessage.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue.impl.object; + +import java.time.Instant; +import java.util.Objects; + + +public class QueueMessage { + private final M message; + private final Instant expirationTime; + public QueueMessage(M message, Instant expirationTime){ + this.message = message; + this.expirationTime = Objects.requireNonNull(expirationTime); + } + + public M getMessage() { + return message; + } + + public boolean isExpired() { + return expirationTime.isBefore(Instant.now()); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/ExecutionQueueService.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/ExecutionQueueService.java deleted file mode 100644 index 1423962ef..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/ExecutionQueueService.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue; - -import java.util.concurrent.TimeUnit; - -import org.onap.appc.exceptions.APPCException; - -public interface ExecutionQueueService { - void putMessage(M message) throws APPCException; - void putMessage(M message, long timeout, TimeUnit unit) throws APPCException; - void registerMessageExpirationListener(MessageExpirationListener listener); -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/MessageExpirationListener.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/MessageExpirationListener.java deleted file mode 100644 index c1f3592c6..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/MessageExpirationListener.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue; - -public interface MessageExpirationListener { - void onMessageExpiration(M message); -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/helper/Util.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/helper/Util.java deleted file mode 100644 index 58279e8a7..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/helper/Util.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue.helper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.executionqueue.impl.QueueManager; - -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -public class Util { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(Util.class); - private final int default_queue_size = 10; - private final int default_threadpool_size = 10; - private final String queue_size_key = "appc.dispatcher.executionqueue.backlog.size"; - private final String threadpool_size_key = "appc.dispatcher.executionqueue.threadpool.size"; - - private Configuration configuration; - - /** - * Initialization. - *

Used by blueprint. - */ - public void init() { - - configuration = ConfigurationFactory.getConfiguration(); - } - - public int getExecutionQueueSize() { - String sizeStr = configuration.getProperty(queue_size_key, String.valueOf(default_queue_size)); - - int size = default_queue_size; - try { - size = Integer.parseInt(sizeStr); - } catch (NumberFormatException e) { - logger.error("Error while parse key:" + queue_size_key + " got from configuration " + e.getMessage(), e); - } - - return size; - } - - public int getThreadPoolSize() { - String sizeStr = configuration.getProperty(threadpool_size_key, String.valueOf(default_threadpool_size)); - - int size = default_threadpool_size; - try { - size = Integer.parseInt(sizeStr); - } catch (NumberFormatException e) { - logger.error("Error while parse key:" + threadpool_size_key + " got from configuration " - + e.getMessage(), e); - } - - return size; - } - - public ThreadFactory getThreadFactory(final boolean isDaemon, final String threadNamePrefix) { - return new ThreadFactory() { - private final String THREAD_NAME_PATTERN = "%s-%d"; - private final ThreadFactory factory = Executors.defaultThreadFactory(); - private final AtomicInteger counter = new AtomicInteger(); - - public Thread newThread(Runnable r) { - Thread t = factory.newThread(r); - t.setDaemon(isDaemon); - if (threadNamePrefix != null && !threadNamePrefix.isEmpty()) { - final String threadName = String.format(THREAD_NAME_PATTERN, threadNamePrefix, counter - .incrementAndGet()); - t.setName(threadName); - } - return t; - } - }; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceFactory.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceFactory.java deleted file mode 100644 index f071be6f0..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue.impl; - -import org.onap.appc.executionqueue.ExecutionQueueService; - -public class ExecutionQueueServiceFactory { - - private static class ExecutionQueueServiceHolder { - public static final ExecutionQueueService executionQueueService = new ExecutionQueueServiceImpl(); - } - - public static ExecutionQueueService getExecutionQueueService() { - return ExecutionQueueServiceHolder.executionQueueService; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceImpl.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceImpl.java deleted file mode 100644 index 0634a0eb2..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/ExecutionQueueServiceImpl.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executionqueue.ExecutionQueueService; -import org.onap.appc.executionqueue.MessageExpirationListener; -import org.onap.appc.executionqueue.impl.object.QueueMessage; - -import java.time.Instant; -import java.util.concurrent.TimeUnit; - -public class ExecutionQueueServiceImpl implements ExecutionQueueService { - - private static final EELFLogger logger = - EELFManager.getInstance().getLogger(ExecutionQueueServiceImpl.class); - - private QueueManager queueManager; - - public ExecutionQueueServiceImpl() { - //do nothing - } - - /** - * Injected by blueprint - * - * @param queueManager queue manager to be set - */ - public void setQueueManager(QueueManager queueManager) { - this.queueManager = queueManager; - } - - @Override - public void putMessage(M message) throws APPCException { - this.putMessage(message, -1, null); - } - - @Override - public void putMessage(M message, long timeout, TimeUnit unit) throws APPCException { - Instant expirationTime = calculateExpirationTime(timeout, unit); - boolean enqueueTask = queueManager.enqueueTask(new QueueMessage<>(message, expirationTime)); - if (!enqueueTask) { - logger.error("Error in putMessage method of ExecutionQueueServiceImpl"); - throw new APPCException("Failed to put message in queue"); - } - } - - @Override - public void registerMessageExpirationListener(MessageExpirationListener listener) { - queueManager.setListener(listener); - } - - private Instant calculateExpirationTime(long timeToLive, TimeUnit unit) { - if (timeToLive > 0 && unit != null) { - // as of Java 8, there is no built-in conversion method from - // TimeUnit to ChronoUnit; do it manually - return Instant.now().plusMillis(unit.toMillis(timeToLive)); - } else { - // never expires - return Instant.MAX; - } - } - -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/QueueManager.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/QueueManager.java deleted file mode 100644 index db0e3d4c5..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/QueueManager.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.executionqueue.MessageExpirationListener; -import org.onap.appc.executionqueue.helper.Util; -import org.onap.appc.executionqueue.impl.object.QueueMessage; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -public class QueueManager { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(QueueManager.class); - - private MessageExpirationListener listener; - private ExecutorService messageExecutor; - private int max_thread_size; - private int max_queue_size; - private Util executionQueueUtil; - - public QueueManager() { - //do nothing - } - - /** - * Initialization method used by blueprint - */ - public void init() { - max_thread_size = executionQueueUtil.getThreadPoolSize(); - max_queue_size = executionQueueUtil.getExecutionQueueSize(); - messageExecutor = new ThreadPoolExecutor( - max_thread_size, - max_thread_size, - 0L, - TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(max_queue_size), - executionQueueUtil.getThreadFactory(true, "appc-dispatcher"), - new ThreadPoolExecutor.AbortPolicy()); - } - - /** - * Destory method used by blueprint - */ - public void stop() { - // Disable new tasks from being submitted - messageExecutor.shutdown(); - List rejectedRunnables = messageExecutor.shutdownNow(); - logger.info(String.format("Rejected %d waiting tasks include ", rejectedRunnables.size())); - - try { - messageExecutor.shutdownNow(); // Cancel currently executing tasks - // Wait a while for tasks to respond to being cancelled - while (!messageExecutor.awaitTermination(100, TimeUnit.MILLISECONDS)) { - logger.debug("QueueManager is being shut down because it still has threads not interrupted"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - messageExecutor.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } - - public void setListener(MessageExpirationListener listener) { - this.listener = listener; - } - - /** - * Injected by blueprint - * - * @param executionQueueUtil Util to be set - */ - public void setExecutionQueueUtil(Util executionQueueUtil) { - this.executionQueueUtil = executionQueueUtil; - } - - public boolean enqueueTask(QueueMessage queueMessage) { - boolean isEnqueued = true; - try { - messageExecutor.execute(() -> { - if (queueMessage.isExpired()) { - logger.debug("Message expired " + queueMessage.getMessage()); - if (listener != null) { - listener.onMessageExpiration(queueMessage.getMessage()); - } else { - logger.warn("Listener not available for expired message "); - } - } else { - queueMessage.getMessage().run(); - } - }); - } catch (RejectedExecutionException ree) { - isEnqueued = false; - } - - return isEnqueued; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/object/QueueMessage.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/object/QueueMessage.java deleted file mode 100644 index bb48da7e5..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/main/java/org/openecomp/appc/executionqueue/impl/object/QueueMessage.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue.impl.object; - -import java.time.Instant; -import java.util.Objects; - - -public class QueueMessage { - private final M message; - private final Instant expirationTime; - public QueueMessage(M message, Instant expirationTime){ - this.message = message; - this.expirationTime = Objects.requireNonNull(expirationTime); - } - - public M getMessage() { - return message; - } - - public boolean isExpired() { - return expirationTime.isBefore(Instant.now()); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/ExecutionQueueServiceTest.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/ExecutionQueueServiceTest.java new file mode 100644 index 000000000..67f480d47 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/ExecutionQueueServiceTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executionqueue.helper.Util; +import org.onap.appc.executionqueue.impl.ExecutionQueueServiceImpl; +import org.onap.appc.executionqueue.impl.QueueManager; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; + +@RunWith(PowerMockRunner.class) +public class ExecutionQueueServiceTest { + + @InjectMocks + private ExecutionQueueServiceImpl service; + @Spy + private QueueManager queueManager = new QueueManager(); + @Spy + private Util executionQueueUtil = new Util(); + + @Before + public void setup() { + Mockito.doReturn(true).when(queueManager).enqueueTask(any()); + } + + @Test + public void testPositiveFlow() { + Message message = new Message(); + try { + service.putMessage(message); + Mockito.verify(queueManager, times(1)).enqueueTask(any()); + } catch (APPCException e) { + Assert.fail(e.toString()); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Listener.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Listener.java new file mode 100644 index 000000000..ce26fd92a --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Listener.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue; + +import org.onap.appc.executionqueue.MessageExpirationListener; + + +public class Listener implements MessageExpirationListener { + + boolean listenerExecuted = false; + + public boolean isListenerExecuted() { + return listenerExecuted; + } + + @Override + public void onMessageExpiration(Object message) { + listenerExecuted = true; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Message.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Message.java new file mode 100644 index 000000000..43bd7077c --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/onap/appc/executionqueue/Message.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.executionqueue; + + +public class Message implements Runnable { + + boolean runExecuted = false; + + public boolean isRunExecuted() { + return runExecuted; + } + + @Override + public void run() { + this.runExecuted = true; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/ExecutionQueueServiceTest.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/ExecutionQueueServiceTest.java deleted file mode 100644 index 67f480d47..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/ExecutionQueueServiceTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.Spy; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executionqueue.helper.Util; -import org.onap.appc.executionqueue.impl.ExecutionQueueServiceImpl; -import org.onap.appc.executionqueue.impl.QueueManager; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; - -@RunWith(PowerMockRunner.class) -public class ExecutionQueueServiceTest { - - @InjectMocks - private ExecutionQueueServiceImpl service; - @Spy - private QueueManager queueManager = new QueueManager(); - @Spy - private Util executionQueueUtil = new Util(); - - @Before - public void setup() { - Mockito.doReturn(true).when(queueManager).enqueueTask(any()); - } - - @Test - public void testPositiveFlow() { - Message message = new Message(); - try { - service.putMessage(message); - Mockito.verify(queueManager, times(1)).enqueueTask(any()); - } catch (APPCException e) { - Assert.fail(e.toString()); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Listener.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Listener.java deleted file mode 100644 index ce26fd92a..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Listener.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue; - -import org.onap.appc.executionqueue.MessageExpirationListener; - - -public class Listener implements MessageExpirationListener { - - boolean listenerExecuted = false; - - public boolean isListenerExecuted() { - return listenerExecuted; - } - - @Override - public void onMessageExpiration(Object message) { - listenerExecuted = true; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Message.java b/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Message.java deleted file mode 100644 index 43bd7077c..000000000 --- a/appc-dispatcher/appc-dispatcher-common/execution-queue-management-lib/src/test/java/org/openecomp/appc/executionqueue/Message.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.executionqueue; - - -public class Message implements Runnable { - - boolean runExecuted = false; - - public boolean isRunExecuted() { - return runExecuted; - } - - @Override - public void run() { - this.runExecuted = true; - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockException.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockException.java new file mode 100644 index 000000000..ab5356325 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.api; + + +public class LockException extends Exception { + + public LockException(String message) { + super(message); + } + + public LockException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockManager.java new file mode 100644 index 000000000..e6a0fb778 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockManager.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.api; + +/** + * Enables locking and unlocking of a resource by id. + * If the resource is locked, only lock owner can reacquire the lock or unlock the resource. + */ +public interface LockManager { + + /** + * Lock resource without timeout. Lock never expires. + * + * @param resource resource id + * @param owner lock owner id + * @return true - if lock is acquired, false - if the resource was already locked by the owner + * @throws LockException thrown if resource is already locked by other owner + */ + boolean acquireLock(String resource, String owner) throws LockException; + + /** + * Lock resource with timeout. After the timeout resource becomes unlocked. + * + * @param resource resource id + * @param owner lock owner id + * @param timeout in milliseconds, after this timeout lock will expire and resource becomes unlocked, + * timeout == 0 means that the lock never expires - same as call acquireLock() without timeout parameter + * @return true - if lock is acquired, false - if the resource was already locked by the owner + * @throws LockException thrown if resource is already locked by other owner + */ + boolean acquireLock(String resource, String owner, long timeout) throws LockException; + + /** + * Unlock resource. + * + * @param resource resource id + * @param owner lock owner id + * @throws LockException thrown if resource is locked by other owner + */ + void releaseLock(String resource, String owner) throws LockException; + + /** + * check resource lock status. + * + * @param resource resource id + */ + + boolean isLocked(String resource); + +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockRuntimeException.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockRuntimeException.java new file mode 100644 index 000000000..99df74628 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/onap/appc/lockmanager/api/LockRuntimeException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.api; + +public class LockRuntimeException extends RuntimeException { + + public LockRuntimeException(String message) { + super(message); + } + + public LockRuntimeException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockException.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockException.java deleted file mode 100644 index ab5356325..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.api; - - -public class LockException extends Exception { - - public LockException(String message) { - super(message); - } - - public LockException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockManager.java deleted file mode 100644 index e6a0fb778..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockManager.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.api; - -/** - * Enables locking and unlocking of a resource by id. - * If the resource is locked, only lock owner can reacquire the lock or unlock the resource. - */ -public interface LockManager { - - /** - * Lock resource without timeout. Lock never expires. - * - * @param resource resource id - * @param owner lock owner id - * @return true - if lock is acquired, false - if the resource was already locked by the owner - * @throws LockException thrown if resource is already locked by other owner - */ - boolean acquireLock(String resource, String owner) throws LockException; - - /** - * Lock resource with timeout. After the timeout resource becomes unlocked. - * - * @param resource resource id - * @param owner lock owner id - * @param timeout in milliseconds, after this timeout lock will expire and resource becomes unlocked, - * timeout == 0 means that the lock never expires - same as call acquireLock() without timeout parameter - * @return true - if lock is acquired, false - if the resource was already locked by the owner - * @throws LockException thrown if resource is already locked by other owner - */ - boolean acquireLock(String resource, String owner, long timeout) throws LockException; - - /** - * Unlock resource. - * - * @param resource resource id - * @param owner lock owner id - * @throws LockException thrown if resource is locked by other owner - */ - void releaseLock(String resource, String owner) throws LockException; - - /** - * check resource lock status. - * - * @param resource resource id - */ - - boolean isLocked(String resource); - -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockRuntimeException.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockRuntimeException.java deleted file mode 100644 index 99df74628..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-api/src/main/java/org/openecomp/appc/lockmanager/api/LockRuntimeException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.api; - -public class LockRuntimeException extends RuntimeException { - - public LockRuntimeException(String message) { - super(message); - } - - public LockRuntimeException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java new file mode 100644 index 000000000..b141d9607 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.inmemory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class LockManagerInMemoryImpl implements LockManager { + + private static LockManagerInMemoryImpl instance = null; + private Map lockedVNFs; + + private static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + + private LockManagerInMemoryImpl() { + lockedVNFs = new ConcurrentHashMap<>(); + } + + public static LockManager getLockManager() { + if(instance == null) { + instance = new LockManagerInMemoryImpl(); + } + return instance; + } + + @Override + public boolean acquireLock(String resource, String owner) throws LockException { + return acquireLock(resource, owner, 0); + } + + @Override + public boolean acquireLock(String resource, String owner, long timeout) throws LockException { + debugLogger.debug("Try to acquire lock on resource " + resource + " with owner " + owner); + long now = System.currentTimeMillis(); + LockValue lockValue = lockedVNFs.get(resource); + if (lockValue != null) { + if (lockIsMine(lockValue, owner, now) || hasExpired(lockValue, now)) { + setExpirationTime(resource, owner, timeout, now); + debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms"); + return hasExpired(lockValue, now); + } + else { + debugLogger.debug("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner()); + throw new LockException("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner()); + } + } + else { + setExpirationTime(resource, owner, timeout, now); + debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms"); + return true; + } + } + + @Override + public void releaseLock(String resource, String owner) throws LockException { + debugLogger.debug("Try to release lock on resource " + resource + " with owner " + owner); + long now = System.currentTimeMillis(); + LockValue lockValue = lockedVNFs.get(resource); + if (lockValue != null) { + if (!hasExpired(lockValue, now)) { + if (isOwner(lockValue, owner)) { + debugLogger.debug("Unlocked successfully resource " + resource + " with owner " + owner); + lockedVNFs.remove(resource); + } + else { + debugLogger.debug("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner"); + throw new LockException("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner"); + } + } + else { + lockedVNFs.remove(resource); + debugLogger.debug("Unlock failed. lock on resource " + resource + " has expired"); + throw new LockException("Unlock failed. lock on resource " + resource + " has expired"); + } + + } + else { + debugLogger.debug("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource"); + throw new LockException("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource"); + } + } + + @Override + public boolean isLocked(String resource) { + return lockedVNFs.get(resource)!=null?true:false; + } + + private boolean lockIsMine(LockValue lockValue, String owner, long now) { + return isOwner(lockValue, owner) && !hasExpired(lockValue, now); + } + + private boolean isOwner(LockValue lockValue, String owner) { + return lockValue.getOwner() != null && lockValue.getOwner().equals(owner); + } + + private boolean hasExpired(LockValue lockValue, long now) { + return (lockValue.getExpirationTime() != 0 && now > lockValue.getExpirationTime()); + } + + private void setExpirationTime(String resource, String owner, long timeout, long now) { + long expirationTime = timeout == 0 ? 0 : now + timeout; + LockValue lockValue = new LockValue(owner, expirationTime); + lockedVNFs.put(resource, lockValue); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockValue.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockValue.java new file mode 100644 index 000000000..d83192c5a --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/inmemory/LockValue.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.inmemory; + + +public class LockValue { + + private String owner; + private long expirationTime; + + LockValue(String owner, long expirationTime) { + this.owner = owner; + this.expirationTime = expirationTime; + } + + String getOwner() { + return owner; + } + + long getExpirationTime() { + return expirationTime; + } + +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/JdbcLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/JdbcLockManager.java new file mode 100644 index 000000000..9b2083101 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/JdbcLockManager.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +import java.sql.Connection; + +import org.onap.appc.dao.util.JdbcConnectionFactory; +import org.onap.appc.lockmanager.api.LockManager; + +public abstract class JdbcLockManager implements LockManager { + + private static final String DEF_TABLE_LOCK_MANAGEMENT = "LOCK_MANAGEMENT"; + + private JdbcConnectionFactory connectionFactory; + protected String tableName = DEF_TABLE_LOCK_MANAGEMENT; + + public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + protected Connection openDbConnection() { + return connectionFactory.openDbConnection(); + } + + protected void closeDbConnection(Connection connection) { + connectionFactory.closeDbConnection(connection); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/Messages.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/Messages.java new file mode 100644 index 000000000..769d94257 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/Messages.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +public enum Messages { + + ERR_NULL_LOCK_OWNER("Cannot acquire lock for resource [%s]: lock owner must be specified"), + ERR_LOCK_LOCKED_BY_OTHER("Cannot lock resource [%s] for [%s]: already locked by [%s]"), + ERR_UNLOCK_NOT_LOCKED("Error unlocking resource [%s]: resource is not locked"), + ERR_UNLOCK_LOCKED_BY_OTHER("Error unlocking resource [%s] by [%s]: resource is locked by [%s]"), + EXP_LOCK("Error locking resource [%s]."), + EXP_CHECK_LOCK("Error check locking resource [%s]."),//for checklock operation + EXP_UNLOCK("Error unlocking resource [%s]."), + ; + + private String message; + + Messages(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public String format(Object... s) { + return String.format(message, s); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/MySqlConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/MySqlConnectionFactory.java new file mode 100644 index 000000000..4df89541d --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/MySqlConnectionFactory.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +import java.sql.DriverManager; +import java.sql.SQLException; + +import org.onap.appc.dao.util.DefaultJdbcConnectionFactory; + +public class MySqlConnectionFactory extends DefaultJdbcConnectionFactory { + + protected void registedDriver() throws SQLException { + DriverManager.registerDriver(new org.mariadb.jdbc.Driver()); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/LockRecord.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/LockRecord.java new file mode 100644 index 000000000..ff0e63b8d --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/LockRecord.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.optimistic; + +class LockRecord { + + private String resource; + private String owner; + private long updated; + private long timeout; + private long ver; + + LockRecord(String resource) { + this.resource = resource; + } + + public String getResource() { + return resource; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public long getUpdated() { + return updated; + } + + public void setUpdated(long updated) { + this.updated = updated; + } + + public long getTimeout() { + return timeout; + } + + public void setTimeout(long timeout) { + this.timeout = timeout; + } + + public long getVer() { + return ver; + } + + public void setVer(long ver) { + this.ver = ver; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java new file mode 100644 index 000000000..d1dd2c5a3 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.optimistic; + +import java.sql.SQLException; + +public class MySqlLockManager extends SqlLockManager { + + @Override + protected boolean isDuplicatePkError(SQLException e) { + return (e.getErrorCode() == 1062); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java new file mode 100644 index 000000000..26ec6a274 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.optimistic; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockRuntimeException; +import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; +import org.onap.appc.lockmanager.impl.sql.Messages; + +abstract class SqlLockManager extends JdbcLockManager { + + private static final String SQL_LOAD_LOCK_RECORD = "SELECT * FROM %s WHERE RESOURCE_ID=?"; + private static final String SQL_INSERT_LOCK_RECORD = "INSERT INTO %s (RESOURCE_ID, OWNER_ID, UPDATED, TIMEOUT, VER) VALUES (?, ?, ?, ?, ?)"; + private static final String SQL_UPDATE_LOCK_RECORD = "UPDATE %s SET OWNER_ID=?, UPDATED=?, TIMEOUT=?, VER=? WHERE RESOURCE_ID=? AND VER=?"; +// private static final String SQL_DELETE_LOCK_RECORD = "DELETE FROM %s WHERE RESOURCE_ID=? AND VER=?"; + private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; + + private String sqlLoadLockRecord; + private String sqlInsertLockRecord; + private String sqlUpdateLockRecord; +// private String sqlDeleteLockRecord; + + @Override + public boolean acquireLock(String resource, String owner) throws LockException { + return acquireLock(resource, owner, 0); + } + + @Override + public boolean acquireLock(String resource, String owner, long timeout) throws LockException { + if(owner == null) { + throw new LockRuntimeException(Messages.ERR_NULL_LOCK_OWNER.format(resource)); + } + boolean res = false; + Connection connection = openDbConnection(); + try { + res = lockResource(connection, resource, owner, timeout); + } finally { + closeDbConnection(connection); + } + return res; + } + + @Override + public void releaseLock(String resource, String owner) throws LockException { + Connection connection = openDbConnection(); + try { + unlockResource(connection, resource, owner); + } finally { + closeDbConnection(connection); + } + } + + @Override + public boolean isLocked(String resource) { + Connection connection=openDbConnection(); + try { + LockRecord lockRecord=loadLockRecord(connection,resource); + if(lockRecord==null){ + return false; + }else{ + if(lockRecord.getOwner()==null){ + return false; + }else if(isLockExpired(lockRecord, connection)){ + return false; + }else{ + return true; + } + } + } catch (SQLException e) { + throw new LockRuntimeException(Messages.EXP_CHECK_LOCK.format(resource)); + }finally { + closeDbConnection(connection); + } + } + + private boolean lockResource(Connection connection, String resource, String owner, long timeout) throws LockException { + try { + boolean res = false; + LockRecord lockRecord = loadLockRecord(connection, resource); + if(lockRecord != null) { + // lock record already exists + String currentOwner = lockRecord.getOwner(); + if(currentOwner != null) { + if(isLockExpired(lockRecord, connection)) { + currentOwner = null; + } else if(!owner.equals(currentOwner)) { + throw new LockException(Messages.ERR_LOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); + } + } + // set new owner on the resource lock record + if(!updateLockRecord(connection, resource, owner, timeout, lockRecord.getVer())) { + // try again - maybe same owner updated the record + lockResource(connection, resource, owner, timeout); + } + if(currentOwner == null) { + // no one locked the resource before + res = true; + } + } else { + // resource record does not exist in lock table => create new record + try { + addLockRecord(connection, resource, owner, timeout); + res = true; + } catch(SQLException e) { + if(isDuplicatePkError(e)) { + // try again - maybe same owner inserted the record + lockResource(connection, resource, owner, timeout); + } else { + throw e; + } + } + } + return res; + } catch(SQLException e) { + throw new LockRuntimeException(Messages.EXP_LOCK.format(resource), e); + } + } + + protected boolean isDuplicatePkError(SQLException e) { + return e.getSQLState().startsWith("23"); + } + + private void unlockResource(Connection connection, String resource, String owner) throws LockException { + try { + LockRecord lockRecord = loadLockRecord(connection, resource); + if(lockRecord != null) { + // check if expired + if(isLockExpired(lockRecord, connection)) { + // lock is expired => no lock + lockRecord = null; + } + } + if((lockRecord == null) || (lockRecord.getOwner() == null)) { + // resource is not locked + throw new LockException(Messages.ERR_UNLOCK_NOT_LOCKED.format(resource)); + } + String currentOwner = lockRecord.getOwner(); + if(!owner.equals(currentOwner)) { + throw new LockException(Messages.ERR_UNLOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); + } + if (!updateLockRecord(connection, resource, null, 0, lockRecord.getVer())) { + unlockResource(connection, resource, owner); + } + // TODO delete record from table on lock release? +// deleteLockRecord(connection, resource, lockRecord.getVer()); + } catch(SQLException e) { + throw new LockRuntimeException(Messages.EXP_UNLOCK.format(resource), e); + } + } + + protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { + LockRecord res = null; + if(sqlLoadLockRecord == null) { + sqlLoadLockRecord = String.format(SQL_LOAD_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlLoadLockRecord)) { + statement.setString(1, resource); + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = new LockRecord(resource); + res.setOwner(resultSet.getString(2)); + res.setUpdated(resultSet.getLong(3)); + res.setTimeout(resultSet.getLong(4)); + res.setVer(resultSet.getLong(5)); + } + } + } + return res; + } + + protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(sqlInsertLockRecord == null) { + sqlInsertLockRecord = String.format(SQL_INSERT_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlInsertLockRecord)) { + statement.setString(1, resource); + statement.setString(2, owner); + statement.setLong(3, getCurrentTime(connection)); + statement.setLong(4, timeout); + statement.setLong(5, 1); + statement.executeUpdate(); + } + } + + protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException { + if(sqlUpdateLockRecord == null) { + sqlUpdateLockRecord = String.format(SQL_UPDATE_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlUpdateLockRecord)) { + long newVer = (ver >= Long.MAX_VALUE) ? 1 : (ver + 1); + statement.setString(1, owner); + statement.setLong(2, getCurrentTime(connection)); + statement.setLong(3, timeout); + statement.setLong(4, newVer); + statement.setString(5, resource); + statement.setLong(6, ver); + return (statement.executeUpdate() != 0); + } + } + +// protected void deleteLockRecord(Connection connection, String resource, long ver) throws SQLException { +// if(sqlDeleteLockRecord == null) { +// sqlDeleteLockRecord = String.format(SQL_DELETE_LOCK_RECORD, tableName); +// } +// try(PreparedStatement statement = connection.prepareStatement(sqlDeleteLockRecord)) { +// statement.setString(1, resource); +// statement.setLong(2, ver); +// statement.executeUpdate(); +// } +// } + + private boolean isLockExpired(LockRecord lockRecord, Connection connection) throws SQLException { + long timeout = lockRecord.getTimeout(); + if(timeout == 0) { + return false; + } + long updated = lockRecord.getUpdated(); + long now = getCurrentTime(connection); + long expiration = updated + timeout; + return (now > expiration); + } + + private long getCurrentTime(Connection connection) throws SQLException { + long res = -1; + if(connection != null) { + try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = resultSet.getTimestamp(1).getTime(); + } + } + } + } + if(res == -1) { + res = System.currentTimeMillis(); + } + return res; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/LockRecord.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/LockRecord.java new file mode 100644 index 000000000..1960ba9a3 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/LockRecord.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.pessimistic; + +class LockRecord { + + private String resource; + private String owner; + private long updated; + private long timeout; + + LockRecord(String resource) { + this.resource = resource; + } + + public String getResource() { + return resource; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public long getUpdated() { + return updated; + } + + public void setUpdated(long updated) { + this.updated = updated; + } + + public long getTimeout() { + return timeout; + } + + public void setTimeout(long timeout) { + this.timeout = timeout; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java new file mode 100644 index 000000000..b76f15c8f --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.pessimistic; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.onap.appc.lockmanager.api.LockRuntimeException; + +public class MySqlLockManager extends SqlLockManager { + + private static final int DEF_CRITICAL_SECTION_WAIT_TIMEOUT = 3; + + protected int criticalSectionWaitTimeoutSecs = DEF_CRITICAL_SECTION_WAIT_TIMEOUT; + + public void setCriticalSectionWaitTimeoutSecs(int criticalSectionWaitTimeoutSecs) { + this.criticalSectionWaitTimeoutSecs = criticalSectionWaitTimeoutSecs; + } + + @Override + protected void enterCriticalSection(Connection connection, String resource) { + try { + CallableStatement statement = connection.prepareCall("SELECT COALESCE(GET_LOCK(?,?),0)"); + try { + statement.setString(1, resource); + statement.setInt(2, criticalSectionWaitTimeoutSecs); + boolean execRes = statement.execute(); + int result = 0; + if(execRes) { + ResultSet resultSet = statement.getResultSet(); + try { + if(resultSet.next()) { + result = resultSet.getInt(1); + } + } finally { + resultSet.close(); + } + } + if(result != 1) { // lock is not obtained + throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "]."); + } + } finally { + statement.close(); + } + } catch(SQLException e) { + throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "].", e); + } + } + + @Override + protected void leaveCriticalSection(Connection connection, String resource) { + try { + CallableStatement statement = connection.prepareCall("SELECT RELEASE_LOCK(?)"); + try { + statement.setString(1, resource); + statement.execute(); + } finally { + statement.close(); + } + } catch(SQLException e) { + throw new LockRuntimeException("Error releasing critical section lock.", e); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java new file mode 100644 index 000000000..a1536d969 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/onap/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.pessimistic; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockRuntimeException; +import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; +import org.onap.appc.lockmanager.impl.sql.Messages; + +abstract class SqlLockManager extends JdbcLockManager { + + private static final String SQL_LOAD_LOCK_RECORD = "SELECT * FROM %s WHERE RESOURCE_ID=?"; + private static final String SQL_INSERT_LOCK_RECORD = "INSERT INTO %s (RESOURCE_ID, OWNER_ID, UPDATED, TIMEOUT) VALUES (?, ?, ?, ?)"; + private static final String SQL_UPDATE_LOCK_RECORD = "UPDATE %s SET OWNER_ID=?, UPDATED=?, TIMEOUT=? WHERE RESOURCE_ID=?"; + private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; + + private String sqlLoadLockRecord; + private String sqlInsertLockRecord; + private String sqlUpdateLockRecord; + + @Override + public boolean acquireLock(String resource, String owner) throws LockException { + return acquireLock(resource, owner, 0); + } + + @Override + public boolean acquireLock(String resource, String owner, long timeout) throws LockException { + if(owner == null) { + throw new LockRuntimeException(Messages.ERR_NULL_LOCK_OWNER.format(resource)); + } + boolean res = false; + Connection connection = openDbConnection(); + try { + enterCriticalSection(connection, resource); + try { + res = lockResource(connection, resource, owner, timeout); + } finally { + leaveCriticalSection(connection, resource); + } + } finally { + closeDbConnection(connection); + } + return res; + } + + @Override + public void releaseLock(String resource, String owner) throws LockException { + Connection connection = openDbConnection(); + try { + enterCriticalSection(connection, resource); + try { + unlockResource(connection, resource, owner); + } finally { + leaveCriticalSection(connection, resource); + } + } finally { + closeDbConnection(connection); + } + } + + @Override + public boolean isLocked(String resource) { + Connection connection=openDbConnection(); + try { + LockRecord lockRecord=loadLockRecord(connection,resource); + if(lockRecord==null){ + return false; + }else{ + if(lockRecord.getOwner()==null){ + return false; + }else if(isLockExpired(lockRecord, connection)){ + return false; + }else{ + return true; + } + } + } catch (SQLException e) { + throw new LockRuntimeException(Messages.EXP_CHECK_LOCK.format(resource)); + }finally { + closeDbConnection(connection); + } + } + + private boolean lockResource(Connection connection, String resource, String owner, long timeout) throws LockException { + try { + boolean res = false; + LockRecord lockRecord = loadLockRecord(connection, resource); + if(lockRecord != null) { + // lock record already exists + String currentOwner = lockRecord.getOwner(); + if(currentOwner != null) { + if(isLockExpired(lockRecord, connection)) { + currentOwner = null; + } else if(!owner.equals(currentOwner)) { + throw new LockException(Messages.ERR_LOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); + } + } + // set new owner on the resource lock record + updateLockRecord(connection, resource, owner, timeout); + if(currentOwner == null) { + // no one locked the resource before + res = true; + } + } else { + // resource record does not exist in lock table => create new record + addLockRecord(connection, resource, owner, timeout); + res = true; + } + return res; + } catch(SQLException e) { + throw new LockRuntimeException(Messages.EXP_LOCK.format(resource), e); + } + } + + private void unlockResource(Connection connection, String resource, String owner) throws LockException { + try { + LockRecord lockRecord = loadLockRecord(connection, resource); + if(lockRecord != null) { + // check if expired + if(isLockExpired(lockRecord, connection)) { + // lock is expired => no lock + lockRecord = null; + } + } + if((lockRecord == null) || (lockRecord.getOwner() == null)) { + // resource is not locked + throw new LockException(Messages.ERR_UNLOCK_NOT_LOCKED.format(resource)); + } + String currentOwner = lockRecord.getOwner(); + if(!owner.equals(currentOwner)) { + throw new LockException(Messages.ERR_UNLOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); + } + updateLockRecord(connection, resource, null, 0); + // TODO delete record from table on lock release? +// deleteLockRecord(connection, resource); + } catch(SQLException e) { + throw new LockRuntimeException(Messages.EXP_UNLOCK.format(resource), e); + } + } + + protected abstract void enterCriticalSection(Connection connection, String resource); + + protected abstract void leaveCriticalSection(Connection connection, String resource); + + protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { + LockRecord res = null; + if(sqlLoadLockRecord == null) { + sqlLoadLockRecord = String.format(SQL_LOAD_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlLoadLockRecord)) { + statement.setString(1, resource); + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = new LockRecord(resource); + res.setOwner(resultSet.getString(2)); + res.setUpdated(resultSet.getLong(3)); + res.setTimeout(resultSet.getLong(4)); + } + } + } + return res; + } + + protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(sqlInsertLockRecord == null) { + sqlInsertLockRecord = String.format(SQL_INSERT_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlInsertLockRecord)) { + statement.setString(1, resource); + statement.setString(2, owner); + statement.setLong(3, getCurrentTime(connection)); + statement.setLong(4, timeout); + statement.executeUpdate(); + } + } + + protected void updateLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(sqlUpdateLockRecord == null) { + sqlUpdateLockRecord = String.format(SQL_UPDATE_LOCK_RECORD, tableName); + } + try(PreparedStatement statement = connection.prepareStatement(sqlUpdateLockRecord)) { + statement.setString(1, owner); + statement.setLong(2, getCurrentTime(connection)); + statement.setLong(3, timeout); + statement.setString(4, resource); + statement.executeUpdate(); + } + } + +// protected void deleteLockRecord(Connection connection, String resource) throws SQLException { +// if(sqlDeleteLockRecord == null) { +// sqlDeleteLockRecord = String.format(SQL_DELETE_LOCK_RECORD, tableName); +// } +// try(PreparedStatement statement = connection.prepareStatement(sqlDeleteLockRecord)) { +// statement.setString(1, resource); +// statement.executeUpdate(); +// } +// } + + private boolean isLockExpired(LockRecord lockRecord, Connection connection) throws SQLException { + long timeout = lockRecord.getTimeout(); + if(timeout == 0) { + return false; + } + long updated = lockRecord.getUpdated(); + long now = getCurrentTime(connection); + long expiration = updated + timeout; + return (now > expiration); + } + + private long getCurrentTime(Connection connection) throws SQLException { + long res = -1; + if(connection != null) { + try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = resultSet.getTimestamp(1).getTime(); + } + } + } + } + if(res == -1) { + res = System.currentTimeMillis(); + } + return res; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java deleted file mode 100644 index b141d9607..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.inmemory; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class LockManagerInMemoryImpl implements LockManager { - - private static LockManagerInMemoryImpl instance = null; - private Map lockedVNFs; - - private static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); - - private LockManagerInMemoryImpl() { - lockedVNFs = new ConcurrentHashMap<>(); - } - - public static LockManager getLockManager() { - if(instance == null) { - instance = new LockManagerInMemoryImpl(); - } - return instance; - } - - @Override - public boolean acquireLock(String resource, String owner) throws LockException { - return acquireLock(resource, owner, 0); - } - - @Override - public boolean acquireLock(String resource, String owner, long timeout) throws LockException { - debugLogger.debug("Try to acquire lock on resource " + resource + " with owner " + owner); - long now = System.currentTimeMillis(); - LockValue lockValue = lockedVNFs.get(resource); - if (lockValue != null) { - if (lockIsMine(lockValue, owner, now) || hasExpired(lockValue, now)) { - setExpirationTime(resource, owner, timeout, now); - debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms"); - return hasExpired(lockValue, now); - } - else { - debugLogger.debug("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner()); - throw new LockException("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner()); - } - } - else { - setExpirationTime(resource, owner, timeout, now); - debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms"); - return true; - } - } - - @Override - public void releaseLock(String resource, String owner) throws LockException { - debugLogger.debug("Try to release lock on resource " + resource + " with owner " + owner); - long now = System.currentTimeMillis(); - LockValue lockValue = lockedVNFs.get(resource); - if (lockValue != null) { - if (!hasExpired(lockValue, now)) { - if (isOwner(lockValue, owner)) { - debugLogger.debug("Unlocked successfully resource " + resource + " with owner " + owner); - lockedVNFs.remove(resource); - } - else { - debugLogger.debug("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner"); - throw new LockException("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner"); - } - } - else { - lockedVNFs.remove(resource); - debugLogger.debug("Unlock failed. lock on resource " + resource + " has expired"); - throw new LockException("Unlock failed. lock on resource " + resource + " has expired"); - } - - } - else { - debugLogger.debug("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource"); - throw new LockException("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource"); - } - } - - @Override - public boolean isLocked(String resource) { - return lockedVNFs.get(resource)!=null?true:false; - } - - private boolean lockIsMine(LockValue lockValue, String owner, long now) { - return isOwner(lockValue, owner) && !hasExpired(lockValue, now); - } - - private boolean isOwner(LockValue lockValue, String owner) { - return lockValue.getOwner() != null && lockValue.getOwner().equals(owner); - } - - private boolean hasExpired(LockValue lockValue, long now) { - return (lockValue.getExpirationTime() != 0 && now > lockValue.getExpirationTime()); - } - - private void setExpirationTime(String resource, String owner, long timeout, long now) { - long expirationTime = timeout == 0 ? 0 : now + timeout; - LockValue lockValue = new LockValue(owner, expirationTime); - lockedVNFs.put(resource, lockValue); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java deleted file mode 100644 index d83192c5a..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.inmemory; - - -public class LockValue { - - private String owner; - private long expirationTime; - - LockValue(String owner, long expirationTime) { - this.owner = owner; - this.expirationTime = expirationTime; - } - - String getOwner() { - return owner; - } - - long getExpirationTime() { - return expirationTime; - } - -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java deleted file mode 100644 index 9b2083101..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -import java.sql.Connection; - -import org.onap.appc.dao.util.JdbcConnectionFactory; -import org.onap.appc.lockmanager.api.LockManager; - -public abstract class JdbcLockManager implements LockManager { - - private static final String DEF_TABLE_LOCK_MANAGEMENT = "LOCK_MANAGEMENT"; - - private JdbcConnectionFactory connectionFactory; - protected String tableName = DEF_TABLE_LOCK_MANAGEMENT; - - public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - protected Connection openDbConnection() { - return connectionFactory.openDbConnection(); - } - - protected void closeDbConnection(Connection connection) { - connectionFactory.closeDbConnection(connection); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java deleted file mode 100644 index 769d94257..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -public enum Messages { - - ERR_NULL_LOCK_OWNER("Cannot acquire lock for resource [%s]: lock owner must be specified"), - ERR_LOCK_LOCKED_BY_OTHER("Cannot lock resource [%s] for [%s]: already locked by [%s]"), - ERR_UNLOCK_NOT_LOCKED("Error unlocking resource [%s]: resource is not locked"), - ERR_UNLOCK_LOCKED_BY_OTHER("Error unlocking resource [%s] by [%s]: resource is locked by [%s]"), - EXP_LOCK("Error locking resource [%s]."), - EXP_CHECK_LOCK("Error check locking resource [%s]."),//for checklock operation - EXP_UNLOCK("Error unlocking resource [%s]."), - ; - - private String message; - - Messages(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - - public String format(Object... s) { - return String.format(message, s); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java deleted file mode 100644 index 4df89541d..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.onap.appc.dao.util.DefaultJdbcConnectionFactory; - -public class MySqlConnectionFactory extends DefaultJdbcConnectionFactory { - - protected void registedDriver() throws SQLException { - DriverManager.registerDriver(new org.mariadb.jdbc.Driver()); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java deleted file mode 100644 index ff0e63b8d..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.optimistic; - -class LockRecord { - - private String resource; - private String owner; - private long updated; - private long timeout; - private long ver; - - LockRecord(String resource) { - this.resource = resource; - } - - public String getResource() { - return resource; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public long getUpdated() { - return updated; - } - - public void setUpdated(long updated) { - this.updated = updated; - } - - public long getTimeout() { - return timeout; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } - - public long getVer() { - return ver; - } - - public void setVer(long ver) { - this.ver = ver; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java deleted file mode 100644 index d1dd2c5a3..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.optimistic; - -import java.sql.SQLException; - -public class MySqlLockManager extends SqlLockManager { - - @Override - protected boolean isDuplicatePkError(SQLException e) { - return (e.getErrorCode() == 1062); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java deleted file mode 100644 index 26ec6a274..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java +++ /dev/null @@ -1,266 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.optimistic; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockRuntimeException; -import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; -import org.onap.appc.lockmanager.impl.sql.Messages; - -abstract class SqlLockManager extends JdbcLockManager { - - private static final String SQL_LOAD_LOCK_RECORD = "SELECT * FROM %s WHERE RESOURCE_ID=?"; - private static final String SQL_INSERT_LOCK_RECORD = "INSERT INTO %s (RESOURCE_ID, OWNER_ID, UPDATED, TIMEOUT, VER) VALUES (?, ?, ?, ?, ?)"; - private static final String SQL_UPDATE_LOCK_RECORD = "UPDATE %s SET OWNER_ID=?, UPDATED=?, TIMEOUT=?, VER=? WHERE RESOURCE_ID=? AND VER=?"; -// private static final String SQL_DELETE_LOCK_RECORD = "DELETE FROM %s WHERE RESOURCE_ID=? AND VER=?"; - private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; - - private String sqlLoadLockRecord; - private String sqlInsertLockRecord; - private String sqlUpdateLockRecord; -// private String sqlDeleteLockRecord; - - @Override - public boolean acquireLock(String resource, String owner) throws LockException { - return acquireLock(resource, owner, 0); - } - - @Override - public boolean acquireLock(String resource, String owner, long timeout) throws LockException { - if(owner == null) { - throw new LockRuntimeException(Messages.ERR_NULL_LOCK_OWNER.format(resource)); - } - boolean res = false; - Connection connection = openDbConnection(); - try { - res = lockResource(connection, resource, owner, timeout); - } finally { - closeDbConnection(connection); - } - return res; - } - - @Override - public void releaseLock(String resource, String owner) throws LockException { - Connection connection = openDbConnection(); - try { - unlockResource(connection, resource, owner); - } finally { - closeDbConnection(connection); - } - } - - @Override - public boolean isLocked(String resource) { - Connection connection=openDbConnection(); - try { - LockRecord lockRecord=loadLockRecord(connection,resource); - if(lockRecord==null){ - return false; - }else{ - if(lockRecord.getOwner()==null){ - return false; - }else if(isLockExpired(lockRecord, connection)){ - return false; - }else{ - return true; - } - } - } catch (SQLException e) { - throw new LockRuntimeException(Messages.EXP_CHECK_LOCK.format(resource)); - }finally { - closeDbConnection(connection); - } - } - - private boolean lockResource(Connection connection, String resource, String owner, long timeout) throws LockException { - try { - boolean res = false; - LockRecord lockRecord = loadLockRecord(connection, resource); - if(lockRecord != null) { - // lock record already exists - String currentOwner = lockRecord.getOwner(); - if(currentOwner != null) { - if(isLockExpired(lockRecord, connection)) { - currentOwner = null; - } else if(!owner.equals(currentOwner)) { - throw new LockException(Messages.ERR_LOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); - } - } - // set new owner on the resource lock record - if(!updateLockRecord(connection, resource, owner, timeout, lockRecord.getVer())) { - // try again - maybe same owner updated the record - lockResource(connection, resource, owner, timeout); - } - if(currentOwner == null) { - // no one locked the resource before - res = true; - } - } else { - // resource record does not exist in lock table => create new record - try { - addLockRecord(connection, resource, owner, timeout); - res = true; - } catch(SQLException e) { - if(isDuplicatePkError(e)) { - // try again - maybe same owner inserted the record - lockResource(connection, resource, owner, timeout); - } else { - throw e; - } - } - } - return res; - } catch(SQLException e) { - throw new LockRuntimeException(Messages.EXP_LOCK.format(resource), e); - } - } - - protected boolean isDuplicatePkError(SQLException e) { - return e.getSQLState().startsWith("23"); - } - - private void unlockResource(Connection connection, String resource, String owner) throws LockException { - try { - LockRecord lockRecord = loadLockRecord(connection, resource); - if(lockRecord != null) { - // check if expired - if(isLockExpired(lockRecord, connection)) { - // lock is expired => no lock - lockRecord = null; - } - } - if((lockRecord == null) || (lockRecord.getOwner() == null)) { - // resource is not locked - throw new LockException(Messages.ERR_UNLOCK_NOT_LOCKED.format(resource)); - } - String currentOwner = lockRecord.getOwner(); - if(!owner.equals(currentOwner)) { - throw new LockException(Messages.ERR_UNLOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); - } - if (!updateLockRecord(connection, resource, null, 0, lockRecord.getVer())) { - unlockResource(connection, resource, owner); - } - // TODO delete record from table on lock release? -// deleteLockRecord(connection, resource, lockRecord.getVer()); - } catch(SQLException e) { - throw new LockRuntimeException(Messages.EXP_UNLOCK.format(resource), e); - } - } - - protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { - LockRecord res = null; - if(sqlLoadLockRecord == null) { - sqlLoadLockRecord = String.format(SQL_LOAD_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlLoadLockRecord)) { - statement.setString(1, resource); - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = new LockRecord(resource); - res.setOwner(resultSet.getString(2)); - res.setUpdated(resultSet.getLong(3)); - res.setTimeout(resultSet.getLong(4)); - res.setVer(resultSet.getLong(5)); - } - } - } - return res; - } - - protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(sqlInsertLockRecord == null) { - sqlInsertLockRecord = String.format(SQL_INSERT_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlInsertLockRecord)) { - statement.setString(1, resource); - statement.setString(2, owner); - statement.setLong(3, getCurrentTime(connection)); - statement.setLong(4, timeout); - statement.setLong(5, 1); - statement.executeUpdate(); - } - } - - protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException { - if(sqlUpdateLockRecord == null) { - sqlUpdateLockRecord = String.format(SQL_UPDATE_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlUpdateLockRecord)) { - long newVer = (ver >= Long.MAX_VALUE) ? 1 : (ver + 1); - statement.setString(1, owner); - statement.setLong(2, getCurrentTime(connection)); - statement.setLong(3, timeout); - statement.setLong(4, newVer); - statement.setString(5, resource); - statement.setLong(6, ver); - return (statement.executeUpdate() != 0); - } - } - -// protected void deleteLockRecord(Connection connection, String resource, long ver) throws SQLException { -// if(sqlDeleteLockRecord == null) { -// sqlDeleteLockRecord = String.format(SQL_DELETE_LOCK_RECORD, tableName); -// } -// try(PreparedStatement statement = connection.prepareStatement(sqlDeleteLockRecord)) { -// statement.setString(1, resource); -// statement.setLong(2, ver); -// statement.executeUpdate(); -// } -// } - - private boolean isLockExpired(LockRecord lockRecord, Connection connection) throws SQLException { - long timeout = lockRecord.getTimeout(); - if(timeout == 0) { - return false; - } - long updated = lockRecord.getUpdated(); - long now = getCurrentTime(connection); - long expiration = updated + timeout; - return (now > expiration); - } - - private long getCurrentTime(Connection connection) throws SQLException { - long res = -1; - if(connection != null) { - try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = resultSet.getTimestamp(1).getTime(); - } - } - } - } - if(res == -1) { - res = System.currentTimeMillis(); - } - return res; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/LockRecord.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/LockRecord.java deleted file mode 100644 index 1960ba9a3..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/LockRecord.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.pessimistic; - -class LockRecord { - - private String resource; - private String owner; - private long updated; - private long timeout; - - LockRecord(String resource) { - this.resource = resource; - } - - public String getResource() { - return resource; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public long getUpdated() { - return updated; - } - - public void setUpdated(long updated) { - this.updated = updated; - } - - public long getTimeout() { - return timeout; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java deleted file mode 100644 index b76f15c8f..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManager.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.pessimistic; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.onap.appc.lockmanager.api.LockRuntimeException; - -public class MySqlLockManager extends SqlLockManager { - - private static final int DEF_CRITICAL_SECTION_WAIT_TIMEOUT = 3; - - protected int criticalSectionWaitTimeoutSecs = DEF_CRITICAL_SECTION_WAIT_TIMEOUT; - - public void setCriticalSectionWaitTimeoutSecs(int criticalSectionWaitTimeoutSecs) { - this.criticalSectionWaitTimeoutSecs = criticalSectionWaitTimeoutSecs; - } - - @Override - protected void enterCriticalSection(Connection connection, String resource) { - try { - CallableStatement statement = connection.prepareCall("SELECT COALESCE(GET_LOCK(?,?),0)"); - try { - statement.setString(1, resource); - statement.setInt(2, criticalSectionWaitTimeoutSecs); - boolean execRes = statement.execute(); - int result = 0; - if(execRes) { - ResultSet resultSet = statement.getResultSet(); - try { - if(resultSet.next()) { - result = resultSet.getInt(1); - } - } finally { - resultSet.close(); - } - } - if(result != 1) { // lock is not obtained - throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "]."); - } - } finally { - statement.close(); - } - } catch(SQLException e) { - throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "].", e); - } - } - - @Override - protected void leaveCriticalSection(Connection connection, String resource) { - try { - CallableStatement statement = connection.prepareCall("SELECT RELEASE_LOCK(?)"); - try { - statement.setString(1, resource); - statement.execute(); - } finally { - statement.close(); - } - } catch(SQLException e) { - throw new LockRuntimeException("Error releasing critical section lock.", e); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java deleted file mode 100644 index a1536d969..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/SqlLockManager.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.pessimistic; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockRuntimeException; -import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; -import org.onap.appc.lockmanager.impl.sql.Messages; - -abstract class SqlLockManager extends JdbcLockManager { - - private static final String SQL_LOAD_LOCK_RECORD = "SELECT * FROM %s WHERE RESOURCE_ID=?"; - private static final String SQL_INSERT_LOCK_RECORD = "INSERT INTO %s (RESOURCE_ID, OWNER_ID, UPDATED, TIMEOUT) VALUES (?, ?, ?, ?)"; - private static final String SQL_UPDATE_LOCK_RECORD = "UPDATE %s SET OWNER_ID=?, UPDATED=?, TIMEOUT=? WHERE RESOURCE_ID=?"; - private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; - - private String sqlLoadLockRecord; - private String sqlInsertLockRecord; - private String sqlUpdateLockRecord; - - @Override - public boolean acquireLock(String resource, String owner) throws LockException { - return acquireLock(resource, owner, 0); - } - - @Override - public boolean acquireLock(String resource, String owner, long timeout) throws LockException { - if(owner == null) { - throw new LockRuntimeException(Messages.ERR_NULL_LOCK_OWNER.format(resource)); - } - boolean res = false; - Connection connection = openDbConnection(); - try { - enterCriticalSection(connection, resource); - try { - res = lockResource(connection, resource, owner, timeout); - } finally { - leaveCriticalSection(connection, resource); - } - } finally { - closeDbConnection(connection); - } - return res; - } - - @Override - public void releaseLock(String resource, String owner) throws LockException { - Connection connection = openDbConnection(); - try { - enterCriticalSection(connection, resource); - try { - unlockResource(connection, resource, owner); - } finally { - leaveCriticalSection(connection, resource); - } - } finally { - closeDbConnection(connection); - } - } - - @Override - public boolean isLocked(String resource) { - Connection connection=openDbConnection(); - try { - LockRecord lockRecord=loadLockRecord(connection,resource); - if(lockRecord==null){ - return false; - }else{ - if(lockRecord.getOwner()==null){ - return false; - }else if(isLockExpired(lockRecord, connection)){ - return false; - }else{ - return true; - } - } - } catch (SQLException e) { - throw new LockRuntimeException(Messages.EXP_CHECK_LOCK.format(resource)); - }finally { - closeDbConnection(connection); - } - } - - private boolean lockResource(Connection connection, String resource, String owner, long timeout) throws LockException { - try { - boolean res = false; - LockRecord lockRecord = loadLockRecord(connection, resource); - if(lockRecord != null) { - // lock record already exists - String currentOwner = lockRecord.getOwner(); - if(currentOwner != null) { - if(isLockExpired(lockRecord, connection)) { - currentOwner = null; - } else if(!owner.equals(currentOwner)) { - throw new LockException(Messages.ERR_LOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); - } - } - // set new owner on the resource lock record - updateLockRecord(connection, resource, owner, timeout); - if(currentOwner == null) { - // no one locked the resource before - res = true; - } - } else { - // resource record does not exist in lock table => create new record - addLockRecord(connection, resource, owner, timeout); - res = true; - } - return res; - } catch(SQLException e) { - throw new LockRuntimeException(Messages.EXP_LOCK.format(resource), e); - } - } - - private void unlockResource(Connection connection, String resource, String owner) throws LockException { - try { - LockRecord lockRecord = loadLockRecord(connection, resource); - if(lockRecord != null) { - // check if expired - if(isLockExpired(lockRecord, connection)) { - // lock is expired => no lock - lockRecord = null; - } - } - if((lockRecord == null) || (lockRecord.getOwner() == null)) { - // resource is not locked - throw new LockException(Messages.ERR_UNLOCK_NOT_LOCKED.format(resource)); - } - String currentOwner = lockRecord.getOwner(); - if(!owner.equals(currentOwner)) { - throw new LockException(Messages.ERR_UNLOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner)); - } - updateLockRecord(connection, resource, null, 0); - // TODO delete record from table on lock release? -// deleteLockRecord(connection, resource); - } catch(SQLException e) { - throw new LockRuntimeException(Messages.EXP_UNLOCK.format(resource), e); - } - } - - protected abstract void enterCriticalSection(Connection connection, String resource); - - protected abstract void leaveCriticalSection(Connection connection, String resource); - - protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { - LockRecord res = null; - if(sqlLoadLockRecord == null) { - sqlLoadLockRecord = String.format(SQL_LOAD_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlLoadLockRecord)) { - statement.setString(1, resource); - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = new LockRecord(resource); - res.setOwner(resultSet.getString(2)); - res.setUpdated(resultSet.getLong(3)); - res.setTimeout(resultSet.getLong(4)); - } - } - } - return res; - } - - protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(sqlInsertLockRecord == null) { - sqlInsertLockRecord = String.format(SQL_INSERT_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlInsertLockRecord)) { - statement.setString(1, resource); - statement.setString(2, owner); - statement.setLong(3, getCurrentTime(connection)); - statement.setLong(4, timeout); - statement.executeUpdate(); - } - } - - protected void updateLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(sqlUpdateLockRecord == null) { - sqlUpdateLockRecord = String.format(SQL_UPDATE_LOCK_RECORD, tableName); - } - try(PreparedStatement statement = connection.prepareStatement(sqlUpdateLockRecord)) { - statement.setString(1, owner); - statement.setLong(2, getCurrentTime(connection)); - statement.setLong(3, timeout); - statement.setString(4, resource); - statement.executeUpdate(); - } - } - -// protected void deleteLockRecord(Connection connection, String resource) throws SQLException { -// if(sqlDeleteLockRecord == null) { -// sqlDeleteLockRecord = String.format(SQL_DELETE_LOCK_RECORD, tableName); -// } -// try(PreparedStatement statement = connection.prepareStatement(sqlDeleteLockRecord)) { -// statement.setString(1, resource); -// statement.executeUpdate(); -// } -// } - - private boolean isLockExpired(LockRecord lockRecord, Connection connection) throws SQLException { - long timeout = lockRecord.getTimeout(); - if(timeout == 0) { - return false; - } - long updated = lockRecord.getUpdated(); - long now = getCurrentTime(connection); - long expiration = updated + timeout; - return (now > expiration); - } - - private long getCurrentTime(Connection connection) throws SQLException { - long res = -1; - if(connection != null) { - try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = resultSet.getTimestamp(1).getTime(); - } - } - } - } - if(res == -1) { - res = System.currentTimeMillis(); - } - return res; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/api/LockManagerBaseTests.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/api/LockManagerBaseTests.java new file mode 100644 index 000000000..9f7e84c43 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/api/LockManagerBaseTests.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.api; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; + +public abstract class LockManagerBaseTests { + + protected enum Resource {Resource1, Resource2}; + protected enum Owner {A, B}; + + protected LockManager lockManager; + + @Before + public void beforeTest() { + lockManager = createLockManager(); + } + + protected abstract LockManager createLockManager(); + + @Test + public void testAcquireLock() throws LockException { + boolean lockRes = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + try { + Assert.assertTrue(lockRes); + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test + public void testAcquireLock_AlreadyLockedBySameOwner() throws LockException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + try { + Assert.assertTrue(lockRes1); + boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + Assert.assertFalse(lockRes2); + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test(expected = LockException.class) + public void testAcquireLock_AlreadyLockedByOtherOwner() throws LockException { + String owner2 = "B"; + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + try { + Assert.assertTrue(lockRes1); + boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), owner2); + Assert.assertFalse(lockRes2); + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test + public void testAcquireLock_LockDifferentResources() throws LockException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + try { + Assert.assertTrue(lockRes1); + boolean lockRes2 = lockManager.acquireLock(Resource.Resource2.name(), Owner.B.name()); + try { + Assert.assertTrue(lockRes2); + } finally { + lockManager.releaseLock(Resource.Resource2.name(), Owner.B.name()); + } + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test(expected = LockException.class) + public void testReleaseLock_NotLockedResource() throws LockException { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + + @Test(expected = LockException.class) + public void testReleaseLock_LockedByOtherOwnerResource() throws LockException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + try { + Assert.assertTrue(lockRes1); + lockManager.releaseLock(Resource.Resource1.name(), Owner.B.name()); + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test(expected = LockException.class) + public void testAcquireLock_LockExpired() throws LockException, InterruptedException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); + Assert.assertTrue(lockRes1); + Thread.sleep(1000); + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + + @Test + public void testAcquireLock_OtherLockExpired() throws LockException, InterruptedException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); + Assert.assertTrue(lockRes1); + Thread.sleep(1000); + boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), Owner.B.name()); + try { + Assert.assertTrue(lockRes2); + }finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.B.name()); + } + } + + @Test + public void testIsLocked_WhenLocked() throws LockException, InterruptedException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); + try { + Assert.assertTrue(lockManager.isLocked(Resource.Resource1.name())); + }finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + + @Test(expected = LockException.class) + public void testIsLocked_LockExpired() throws LockException, InterruptedException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); + Assert.assertTrue(lockRes1); + Assert.assertTrue(lockManager.isLocked(Resource.Resource1.name())); + Thread.sleep(1000); + try { + Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); + }finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test + public void testIsLocked_LockReleased() throws LockException, InterruptedException { + boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); + } + + @Test + public void testIsLocked_NoLock() throws LockException, InterruptedException { + Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java new file mode 100644 index 000000000..8d2dd7516 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.inmemory; + +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.lockmanager.api.LockManagerBaseTests; +import org.onap.appc.lockmanager.impl.inmemory.LockManagerInMemoryImpl; + + +public class LockManagerInMemoryImplTest extends LockManagerBaseTests { + + @Override + protected LockManager createLockManager() { + return LockManagerInMemoryImpl.getLockManager(); + } + +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java new file mode 100644 index 000000000..b8cd95b94 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.onap.appc.dao.util.DefaultJdbcConnectionFactory; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.lockmanager.api.LockManagerBaseTests; +import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; +import org.onap.appc.lockmanager.impl.sql.MySqlConnectionFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public abstract class MySqlLockManagerBaseTests extends LockManagerBaseTests { + + private static final boolean USE_REAL_DB = Boolean.getBoolean("lockmanager.tests.useRealDb"); + private static final String TABLE_LOCK_MANAGEMENT = "TEST_LOCK_MANAGEMENT"; + private static final String JDBC_URL = System.getProperty("lockmanager.tests.jdbcUrl", "jdbc:mysql://192.168.1.2/test"); + private static final String JDBC_USERNAME = System.getProperty("lockmanager.tests.jdbcUsername", "test"); + private static final String JDBC_PASSWORD = System.getProperty("lockmanager.tests.jdbcPassword", "123456"); + + protected static final int CONCURRENT_TEST_WAIT_TIME = 10; // secs + + @Rule + public TestName testName = new TestName(); + + @Override + protected LockManager createLockManager() { + JdbcLockManager jdbcLockManager = createJdbcLockManager(USE_REAL_DB); + DefaultJdbcConnectionFactory connectionFactory = new MySqlConnectionFactory(); + connectionFactory.setJdbcURL(JDBC_URL); + connectionFactory.setJdbcUserName(JDBC_USERNAME); + connectionFactory.setJdbcPassword(JDBC_PASSWORD); + jdbcLockManager.setConnectionFactory(connectionFactory); + jdbcLockManager.setTableName(TABLE_LOCK_MANAGEMENT); + System.out.println("=> Running LockManager test [" + jdbcLockManager.getClass().getName() + "." + testName.getMethodName() + "]" + (USE_REAL_DB ? ". JDBC URL is [" + JDBC_URL + "]" : "")); + clearTestLocks(jdbcLockManager); + return jdbcLockManager; + } + + protected abstract JdbcLockManager createJdbcLockManager(boolean useRealDb); + + protected boolean setSynchronizer(Synchronizer synchronizer) { + if(!(lockManager instanceof SynchronizerReceiver)) { + System.err.println("Skipping concurrency test [" + testName.getMethodName() + "] for LockManager of type " + lockManager.getClass()); + return false; + } + ((SynchronizerReceiver)lockManager).setSynchronizer(synchronizer); + return true; + } + + private static final String SQL_DELETE_LOCK_RECORD = String.format("DELETE FROM %s WHERE RESOURCE_ID=?", TABLE_LOCK_MANAGEMENT); + private void clearTestLocks(JdbcLockManager jdbcLockManager) { + Connection connection = jdbcLockManager.openDbConnection(); + if(connection == null) { + return; + } + try { + for(Resource resource: Resource.values()) { + try(PreparedStatement statement = connection.prepareStatement(SQL_DELETE_LOCK_RECORD)) { + statement.setString(1, resource.name()); + statement.executeUpdate(); + } + } + } catch(SQLException e) { + throw new RuntimeException("Cannot clear test resources in table", e); + } finally { + jdbcLockManager.closeDbConnection(connection); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/Synchronizer.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/Synchronizer.java new file mode 100644 index 000000000..ae92a4a9d --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/Synchronizer.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +public class Synchronizer { + + private int participantNo; + private int participantCount; + + public Synchronizer(int participantNo) { + this.participantNo = participantNo; + } + + public int getParticipantCount() { + return participantCount; + } + + public void postLoadLockRecord(String resource, String owner) { + synchronized(this) { + waitForAllParticipants(this, participantNo, ++participantCount); + } + } + + public void preAddLockRecord(String resource, String owner) { + } + + public void postAddLockRecord(String resource, String owner) { + } + + public void preUpdateLockRecord(String resource, String owner) { + } + + public void postUpdateLockRecord(String resource, String owner) { + } + + public void releaseWait() { + synchronized(this) { + this.notifyAll(); + } + } + + protected void waitOn(Object obj, long timeout) { + try { + obj.wait(timeout); + } catch(InterruptedException e) { + throw new RuntimeException(e); + } + } + + protected void waitOn(Object obj) { + waitOn(obj, 0); + } + + protected void waitForAllParticipants(Object waitObj, int totalParticipantsNo, int currentParticipantsNo) { + if(totalParticipantsNo > currentParticipantsNo) { + waitOn(waitObj); + } else { + waitObj.notifyAll(); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/SynchronizerReceiver.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/SynchronizerReceiver.java new file mode 100644 index 000000000..e6caad564 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/SynchronizerReceiver.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql; + +public interface SynchronizerReceiver { + + void setSynchronizer(Synchronizer synchronizer); +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java new file mode 100644 index 000000000..f9c072e6c --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.optimistic; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.onap.appc.lockmanager.impl.sql.Synchronizer; +import org.onap.appc.lockmanager.impl.sql.SynchronizerReceiver; +import org.onap.appc.lockmanager.impl.sql.optimistic.LockRecord; +import org.onap.appc.lockmanager.impl.sql.optimistic.MySqlLockManager; + +class MySqlLockManagerMock extends MySqlLockManager implements SynchronizerReceiver { + + private final ConcurrentMap locks = new ConcurrentHashMap<>(); + private boolean useReal; + private Synchronizer synchronizer; + + MySqlLockManagerMock(boolean useReal) { + this.useReal = useReal; + } + + @Override + public void setSynchronizer(Synchronizer synchronizer) { + this.synchronizer = synchronizer; + } + + @Override + protected Connection openDbConnection() { + if(useReal) { + return super.openDbConnection(); + } + return null; + } + + @Override + protected void closeDbConnection(Connection connection) { + if(useReal) { + super.closeDbConnection(connection); + } + } + + @Override + protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { + LockRecord res; + if(useReal) { + res = super.loadLockRecord(connection, resource); + } else { + res = locks.get(resource); + } + if(synchronizer != null) { + synchronizer.postLoadLockRecord(resource, (res == null) ? null : res.getOwner()); + } + return res; + } + + @Override + protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(synchronizer != null) { + synchronizer.preAddLockRecord(resource, owner); + } + try { + if(useReal) { + super.addLockRecord(connection, resource, owner, timeout); + return; + } + LockRecord lockRecord = new LockRecord(resource); + lockRecord.setOwner(owner); + lockRecord.setUpdated(System.currentTimeMillis()); + lockRecord.setTimeout(timeout); + lockRecord.setVer(1); + LockRecord prevLockRecord = locks.putIfAbsent(resource, lockRecord); + if(prevLockRecord != null) { + // simulate unique constraint violation + throw new SQLException("Duplicate PK exception", "23000", 1062); + } + } finally { + if(synchronizer != null) { + synchronizer.postAddLockRecord(resource, owner); + } + } + } + + @Override + protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException { + if(synchronizer != null) { + synchronizer.preUpdateLockRecord(resource, owner); + } + try { + if(useReal) { + return super.updateLockRecord(connection, resource, owner, timeout, ver); + } + LockRecord lockRecord = loadLockRecord(connection, resource); + synchronized(lockRecord) { + // should be atomic operation + if(ver != lockRecord.getVer()) { + return false; + } + lockRecord.setOwner(owner); + lockRecord.setUpdated(System.currentTimeMillis()); + lockRecord.setTimeout(timeout); + lockRecord.setVer(ver + 1); + } + return true; + } finally { + if(synchronizer != null) { + synchronizer.postUpdateLockRecord(resource, owner); + } + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java new file mode 100644 index 000000000..d652c7523 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java @@ -0,0 +1,230 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.optimistic; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; +import org.onap.appc.lockmanager.impl.sql.MySqlLockManagerBaseTests; +import org.onap.appc.lockmanager.impl.sql.Synchronizer; + +import java.util.concurrent.*; + +public class TestMySqlLockManager extends MySqlLockManagerBaseTests { + + @Override + protected JdbcLockManager createJdbcLockManager(boolean useReal) { + return new MySqlLockManagerMock(useReal); + } + + @Test + public void testConcurrentLockDifferentOwners() throws LockException, InterruptedException, ExecutionException, TimeoutException { + + final int participantsNo = 2; + Synchronizer synchronizer = new Synchronizer(participantsNo) { + + private boolean wait = true; + + @Override + public void preAddLockRecord(String resource, String owner) { + if(Owner.A.name().equals(owner)) { + synchronized(this) { + if(wait) { + waitOn(this); + } + } + } + } + + @Override + public void postAddLockRecord(String resource, String owner) { + if(!Owner.A.name().equals(owner)) { + synchronized(this) { + notifyAll(); + wait = false; + } + } + } + + @Override + public void preUpdateLockRecord(String resource, String owner) { + preAddLockRecord(resource, owner); + } + + @Override + public void postUpdateLockRecord(String resource, String owner) { + postAddLockRecord(resource, owner); + } + }; + if(!setSynchronizer(synchronizer)) { + return; + } + ExecutorService executor = Executors.newFixedThreadPool(participantsNo); + // acquireLock by owner A should fail as it will wait for acquireLock by owner B + Future future1 = executor.submit(new Callable() { + @Override + public Boolean call() throws Exception { + try { + lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + return false; + } catch(LockException e) { + // this call should fail as Synchronizer delays its lock to make sure the second call locks the resource first + Assert.assertEquals("Cannot lock resource [" + Resource.Resource1.name() + "] for [" + Owner.A.name() + "]: already locked by [" + Owner.B.name() + "]", e.getMessage()); + return true; + } + } + }); + try { + // acquireLock by owner B should success + Future future2 = executor.submit(new Callable() { + @Override + public Boolean call() throws Exception { + // this call should success as Synchronizer delays the above lock to make sure this call success to lock the resource + return lockManager.acquireLock(Resource.Resource1.name(), Owner.B.name()); + } + }); + try { + Assert.assertTrue(future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS)); + Assert.assertTrue(future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS)); + } finally { + future2.cancel(true); + } + } finally { + future1.cancel(true); + } + } + + @Test + public void testConcurrentLockSameOwner() throws LockException, InterruptedException, ExecutionException, TimeoutException { + final int participantsNo = 2; + Synchronizer synchronizer = new Synchronizer(participantsNo) { + + private boolean wait = true; + + @Override + public void preAddLockRecord(String resource, String owner) { + synchronized(this) { + if(wait) { + wait = false; + waitOn(this); + } + } + } + + @Override + public void postAddLockRecord(String resource, String owner) { + synchronized(this) { + notifyAll(); + } + } + }; + if(!setSynchronizer(synchronizer)) { + return; + } + ExecutorService executor = Executors.newFixedThreadPool(participantsNo); + // one acquireLock should return true and the other should return false + Callable callable = new Callable() { + @Override + public Boolean call() throws Exception { + return lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + } + }; + Future future1 = executor.submit(callable); + try { + Future future2 = executor.submit(callable); + try { + boolean future1Res = future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); + boolean future2Res = future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); + // one of the lock requests should return true, the other one false as lock is requested simultaneously from 2 threads by same owner + Assert.assertNotEquals(future1Res, future2Res); + } finally { + future2.cancel(true); + } + } finally { + future1.cancel(true); + } + } + + @Test + public void testConcurrentUnlockSameOwner() throws LockException, InterruptedException, ExecutionException, TimeoutException { + lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + final int participantsNo = 2; + Synchronizer synchronizer = new Synchronizer(participantsNo) { + + private boolean wait = true; + + @Override + public void preUpdateLockRecord(String resource, String owner) { + synchronized(this) { + // make sure second call updates the LockRecord first + if(wait) { + wait = false; + waitOn(this); + } + } + } + + @Override + public void postUpdateLockRecord(String resource, String owner) { + synchronized(this) { + notifyAll(); + } + } + }; + if(!setSynchronizer(synchronizer)) { + return; + } + ExecutorService executor = Executors.newFixedThreadPool(participantsNo); + Callable callable = new Callable() { + @Override + public Boolean call() throws Exception { + try { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + // one of the unlock calls should success + return true; + } catch(LockException e) { + // one of the unlock calls should throw the LockException as the resource should already be unlocked by other call + Assert.assertEquals("Error unlocking resource [" + Resource.Resource1.name() + "]: resource is not locked", e.getMessage()); + return false; + } + } + }; + Future future1 = executor.submit(callable); + try { + Future future2 = executor.submit(callable); + try { + boolean future1Res = future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); + boolean future2Res = future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); + // one of the unlock calls should return true, the other one false as unlock is requested simultaneously from 2 threads by same owner + Assert.assertNotEquals(future1Res, future2Res); + } finally { + future2.cancel(true); + } + } finally { + future1.cancel(true); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java new file mode 100644 index 000000000..a4bbd3406 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.pessimistic; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.onap.appc.lockmanager.api.LockRuntimeException; +import org.onap.appc.lockmanager.impl.sql.Synchronizer; +import org.onap.appc.lockmanager.impl.sql.SynchronizerReceiver; +import org.onap.appc.lockmanager.impl.sql.pessimistic.LockRecord; +import org.onap.appc.lockmanager.impl.sql.pessimistic.MySqlLockManager; + +class MySqlLockManagerMock extends MySqlLockManager implements SynchronizerReceiver { + + private final Map locks = new HashMap<>(); + private final Lock lock = new ReentrantLock(); + private boolean useReal; + private Synchronizer synchronizer; + + MySqlLockManagerMock(boolean useReal) { + this.useReal = useReal; + } + + @Override + public void setSynchronizer(Synchronizer synchronizer) { + this.synchronizer = synchronizer; + } + + @Override + protected Connection openDbConnection() { + if(useReal) { + return super.openDbConnection(); + } + return null; + } + + @Override + protected void closeDbConnection(Connection connection) { + if(useReal) { + super.closeDbConnection(connection); + } + } + + @Override + protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { + LockRecord res; + if(useReal) { + res = super.loadLockRecord(connection, resource); + } else { + res = locks.get(resource); + } + if(synchronizer != null) { + synchronizer.postLoadLockRecord(resource, (res == null) ? null : res.getOwner()); + } + return res; + } + + @Override + protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(synchronizer != null) { + synchronizer.preAddLockRecord(resource, owner); + } + try { + if(useReal) { + super.addLockRecord(connection, resource, owner, timeout); + return; + } + LockRecord lockRecord = new LockRecord(resource); + lockRecord.setOwner(owner); + lockRecord.setUpdated(System.currentTimeMillis()); + lockRecord.setTimeout(timeout); + locks.put(resource, lockRecord); + } finally { + if(synchronizer != null) { + synchronizer.postAddLockRecord(resource, owner); + } + } + } + + @Override + protected void updateLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { + if(synchronizer != null) { + synchronizer.preUpdateLockRecord(resource, owner); + } + try { + if(useReal) { + super.updateLockRecord(connection, resource, owner, timeout); + return; + } + LockRecord lockRecord = loadLockRecord(connection, resource); + lockRecord.setOwner(owner); + lockRecord.setUpdated(System.currentTimeMillis()); + lockRecord.setTimeout(timeout); + locks.put(resource, lockRecord); + } finally { + if(synchronizer != null) { + synchronizer.postUpdateLockRecord(resource, owner); + } + } + } + + @Override + protected void enterCriticalSection(Connection connection, String resource) { + if(useReal) { + super.enterCriticalSection(connection, resource); + return; + } + try { + if(!lock.tryLock(criticalSectionWaitTimeoutSecs, TimeUnit.SECONDS)) { + throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "]."); + } + } catch(InterruptedException e) { + throw new LockRuntimeException("Cannot obtain critical section lock.", e); + } + } + + @Override + protected void leaveCriticalSection(Connection connection, String resource) { + if(useReal) { + super.leaveCriticalSection(connection, resource); + return; + } + lock.unlock(); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java new file mode 100644 index 000000000..c54cfc81a --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/onap/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lockmanager.impl.sql.pessimistic; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockRuntimeException; +import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; +import org.onap.appc.lockmanager.impl.sql.MySqlLockManagerBaseTests; +import org.onap.appc.lockmanager.impl.sql.Synchronizer; +import org.onap.appc.lockmanager.impl.sql.pessimistic.MySqlLockManager; + +import java.util.concurrent.*; + +public class TestMySqlLockManager extends MySqlLockManagerBaseTests { + + private static int CRITICAL_SECTION_WAIT_TIMEOUT = 1; // in secs + + @Override + protected JdbcLockManager createJdbcLockManager(boolean useReal) { + return new MySqlLockManagerMock(useReal); + } + + @Test + public void testConcurrentLock() throws LockException, InterruptedException, ExecutionException, TimeoutException { + try { + callConcurrentTest(new Callable() { + @Override + public Boolean call() throws Exception { + try { + Assert.assertTrue(lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name())); + return true; + } catch(LockRuntimeException e) { + Assert.assertEquals("Cannot obtain critical section lock for resource [" + Resource.Resource1.name() + "].", e.getMessage()); + return false; + } + } + }); + } finally { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + } + } + + @Test + public void testConcurrentUnlock() throws LockException, InterruptedException, ExecutionException, TimeoutException { + lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); + callConcurrentTest(new Callable() { + @Override + public Boolean call() throws Exception { + try { + lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); + return true; + } catch(LockRuntimeException e) { + Assert.assertEquals("Cannot obtain critical section lock for resource [" + Resource.Resource1.name() + "].", e.getMessage()); + return false; + } + } + }); + } + + private void callConcurrentTest(Callable callable) throws LockException, InterruptedException, ExecutionException, TimeoutException { + final int participantsNo = 2; + Synchronizer synchronizer = new Synchronizer(participantsNo) { + + @Override + protected void waitForAllParticipants(Object waitObj, int totalParticipantsNo, int currentParticipantsNo) { + waitOn(this, TimeUnit.MILLISECONDS.convert(1 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); // add 1 sec to make sure timeout occured + } + }; + if(!setSynchronizer(synchronizer)) { + return; + } + ((MySqlLockManager)lockManager).setCriticalSectionWaitTimeoutSecs(CRITICAL_SECTION_WAIT_TIMEOUT); + ExecutorService executor = Executors.newFixedThreadPool(participantsNo); + Future future1 = executor.submit(callable); + try { + for(int i = 0; i < 10; i++) { + Thread.sleep(100); + if(synchronizer.getParticipantCount() > 0) { + break; + } + } + // make sure 1st thread gets inside critical section + if(synchronizer.getParticipantCount() < 1) { + Assert.fail(getClass().getName() + " first thread failed to acquireLock()"); + } + Future future2 = executor.submit(callable); + try { + // 1st thread should acquire the lock + Assert.assertTrue(future1.get(3 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); + // 2nd thread should fail waiting for critical section + Assert.assertFalse(future2.get(2 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); + } finally { + future2.cancel(true); + } + } finally { + future1.cancel(true); + setSynchronizer(null); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/api/LockManagerBaseTests.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/api/LockManagerBaseTests.java deleted file mode 100644 index 9f7e84c43..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/api/LockManagerBaseTests.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.api; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; - -public abstract class LockManagerBaseTests { - - protected enum Resource {Resource1, Resource2}; - protected enum Owner {A, B}; - - protected LockManager lockManager; - - @Before - public void beforeTest() { - lockManager = createLockManager(); - } - - protected abstract LockManager createLockManager(); - - @Test - public void testAcquireLock() throws LockException { - boolean lockRes = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - try { - Assert.assertTrue(lockRes); - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test - public void testAcquireLock_AlreadyLockedBySameOwner() throws LockException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - try { - Assert.assertTrue(lockRes1); - boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - Assert.assertFalse(lockRes2); - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test(expected = LockException.class) - public void testAcquireLock_AlreadyLockedByOtherOwner() throws LockException { - String owner2 = "B"; - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - try { - Assert.assertTrue(lockRes1); - boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), owner2); - Assert.assertFalse(lockRes2); - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test - public void testAcquireLock_LockDifferentResources() throws LockException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - try { - Assert.assertTrue(lockRes1); - boolean lockRes2 = lockManager.acquireLock(Resource.Resource2.name(), Owner.B.name()); - try { - Assert.assertTrue(lockRes2); - } finally { - lockManager.releaseLock(Resource.Resource2.name(), Owner.B.name()); - } - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test(expected = LockException.class) - public void testReleaseLock_NotLockedResource() throws LockException { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - - @Test(expected = LockException.class) - public void testReleaseLock_LockedByOtherOwnerResource() throws LockException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - try { - Assert.assertTrue(lockRes1); - lockManager.releaseLock(Resource.Resource1.name(), Owner.B.name()); - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test(expected = LockException.class) - public void testAcquireLock_LockExpired() throws LockException, InterruptedException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); - Assert.assertTrue(lockRes1); - Thread.sleep(1000); - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - - @Test - public void testAcquireLock_OtherLockExpired() throws LockException, InterruptedException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); - Assert.assertTrue(lockRes1); - Thread.sleep(1000); - boolean lockRes2 = lockManager.acquireLock(Resource.Resource1.name(), Owner.B.name()); - try { - Assert.assertTrue(lockRes2); - }finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.B.name()); - } - } - - @Test - public void testIsLocked_WhenLocked() throws LockException, InterruptedException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); - try { - Assert.assertTrue(lockManager.isLocked(Resource.Resource1.name())); - }finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - - @Test(expected = LockException.class) - public void testIsLocked_LockExpired() throws LockException, InterruptedException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); - Assert.assertTrue(lockRes1); - Assert.assertTrue(lockManager.isLocked(Resource.Resource1.name())); - Thread.sleep(1000); - try { - Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); - }finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test - public void testIsLocked_LockReleased() throws LockException, InterruptedException { - boolean lockRes1 = lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name(), 50); - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); - } - - @Test - public void testIsLocked_NoLock() throws LockException, InterruptedException { - Assert.assertFalse(lockManager.isLocked(Resource.Resource1.name())); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java deleted file mode 100644 index 8d2dd7516..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImplTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.inmemory; - -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.lockmanager.api.LockManagerBaseTests; -import org.onap.appc.lockmanager.impl.inmemory.LockManagerInMemoryImpl; - - -public class LockManagerInMemoryImplTest extends LockManagerBaseTests { - - @Override - protected LockManager createLockManager() { - return LockManagerInMemoryImpl.getLockManager(); - } - -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java deleted file mode 100644 index b8cd95b94..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/MySqlLockManagerBaseTests.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.onap.appc.dao.util.DefaultJdbcConnectionFactory; -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.lockmanager.api.LockManagerBaseTests; -import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; -import org.onap.appc.lockmanager.impl.sql.MySqlConnectionFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public abstract class MySqlLockManagerBaseTests extends LockManagerBaseTests { - - private static final boolean USE_REAL_DB = Boolean.getBoolean("lockmanager.tests.useRealDb"); - private static final String TABLE_LOCK_MANAGEMENT = "TEST_LOCK_MANAGEMENT"; - private static final String JDBC_URL = System.getProperty("lockmanager.tests.jdbcUrl", "jdbc:mysql://192.168.1.2/test"); - private static final String JDBC_USERNAME = System.getProperty("lockmanager.tests.jdbcUsername", "test"); - private static final String JDBC_PASSWORD = System.getProperty("lockmanager.tests.jdbcPassword", "123456"); - - protected static final int CONCURRENT_TEST_WAIT_TIME = 10; // secs - - @Rule - public TestName testName = new TestName(); - - @Override - protected LockManager createLockManager() { - JdbcLockManager jdbcLockManager = createJdbcLockManager(USE_REAL_DB); - DefaultJdbcConnectionFactory connectionFactory = new MySqlConnectionFactory(); - connectionFactory.setJdbcURL(JDBC_URL); - connectionFactory.setJdbcUserName(JDBC_USERNAME); - connectionFactory.setJdbcPassword(JDBC_PASSWORD); - jdbcLockManager.setConnectionFactory(connectionFactory); - jdbcLockManager.setTableName(TABLE_LOCK_MANAGEMENT); - System.out.println("=> Running LockManager test [" + jdbcLockManager.getClass().getName() + "." + testName.getMethodName() + "]" + (USE_REAL_DB ? ". JDBC URL is [" + JDBC_URL + "]" : "")); - clearTestLocks(jdbcLockManager); - return jdbcLockManager; - } - - protected abstract JdbcLockManager createJdbcLockManager(boolean useRealDb); - - protected boolean setSynchronizer(Synchronizer synchronizer) { - if(!(lockManager instanceof SynchronizerReceiver)) { - System.err.println("Skipping concurrency test [" + testName.getMethodName() + "] for LockManager of type " + lockManager.getClass()); - return false; - } - ((SynchronizerReceiver)lockManager).setSynchronizer(synchronizer); - return true; - } - - private static final String SQL_DELETE_LOCK_RECORD = String.format("DELETE FROM %s WHERE RESOURCE_ID=?", TABLE_LOCK_MANAGEMENT); - private void clearTestLocks(JdbcLockManager jdbcLockManager) { - Connection connection = jdbcLockManager.openDbConnection(); - if(connection == null) { - return; - } - try { - for(Resource resource: Resource.values()) { - try(PreparedStatement statement = connection.prepareStatement(SQL_DELETE_LOCK_RECORD)) { - statement.setString(1, resource.name()); - statement.executeUpdate(); - } - } - } catch(SQLException e) { - throw new RuntimeException("Cannot clear test resources in table", e); - } finally { - jdbcLockManager.closeDbConnection(connection); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/Synchronizer.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/Synchronizer.java deleted file mode 100644 index ae92a4a9d..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/Synchronizer.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -public class Synchronizer { - - private int participantNo; - private int participantCount; - - public Synchronizer(int participantNo) { - this.participantNo = participantNo; - } - - public int getParticipantCount() { - return participantCount; - } - - public void postLoadLockRecord(String resource, String owner) { - synchronized(this) { - waitForAllParticipants(this, participantNo, ++participantCount); - } - } - - public void preAddLockRecord(String resource, String owner) { - } - - public void postAddLockRecord(String resource, String owner) { - } - - public void preUpdateLockRecord(String resource, String owner) { - } - - public void postUpdateLockRecord(String resource, String owner) { - } - - public void releaseWait() { - synchronized(this) { - this.notifyAll(); - } - } - - protected void waitOn(Object obj, long timeout) { - try { - obj.wait(timeout); - } catch(InterruptedException e) { - throw new RuntimeException(e); - } - } - - protected void waitOn(Object obj) { - waitOn(obj, 0); - } - - protected void waitForAllParticipants(Object waitObj, int totalParticipantsNo, int currentParticipantsNo) { - if(totalParticipantsNo > currentParticipantsNo) { - waitOn(waitObj); - } else { - waitObj.notifyAll(); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/SynchronizerReceiver.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/SynchronizerReceiver.java deleted file mode 100644 index e6caad564..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/SynchronizerReceiver.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql; - -public interface SynchronizerReceiver { - - void setSynchronizer(Synchronizer synchronizer); -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java deleted file mode 100644 index f9c072e6c..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManagerMock.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.optimistic; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.onap.appc.lockmanager.impl.sql.Synchronizer; -import org.onap.appc.lockmanager.impl.sql.SynchronizerReceiver; -import org.onap.appc.lockmanager.impl.sql.optimistic.LockRecord; -import org.onap.appc.lockmanager.impl.sql.optimistic.MySqlLockManager; - -class MySqlLockManagerMock extends MySqlLockManager implements SynchronizerReceiver { - - private final ConcurrentMap locks = new ConcurrentHashMap<>(); - private boolean useReal; - private Synchronizer synchronizer; - - MySqlLockManagerMock(boolean useReal) { - this.useReal = useReal; - } - - @Override - public void setSynchronizer(Synchronizer synchronizer) { - this.synchronizer = synchronizer; - } - - @Override - protected Connection openDbConnection() { - if(useReal) { - return super.openDbConnection(); - } - return null; - } - - @Override - protected void closeDbConnection(Connection connection) { - if(useReal) { - super.closeDbConnection(connection); - } - } - - @Override - protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { - LockRecord res; - if(useReal) { - res = super.loadLockRecord(connection, resource); - } else { - res = locks.get(resource); - } - if(synchronizer != null) { - synchronizer.postLoadLockRecord(resource, (res == null) ? null : res.getOwner()); - } - return res; - } - - @Override - protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(synchronizer != null) { - synchronizer.preAddLockRecord(resource, owner); - } - try { - if(useReal) { - super.addLockRecord(connection, resource, owner, timeout); - return; - } - LockRecord lockRecord = new LockRecord(resource); - lockRecord.setOwner(owner); - lockRecord.setUpdated(System.currentTimeMillis()); - lockRecord.setTimeout(timeout); - lockRecord.setVer(1); - LockRecord prevLockRecord = locks.putIfAbsent(resource, lockRecord); - if(prevLockRecord != null) { - // simulate unique constraint violation - throw new SQLException("Duplicate PK exception", "23000", 1062); - } - } finally { - if(synchronizer != null) { - synchronizer.postAddLockRecord(resource, owner); - } - } - } - - @Override - protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException { - if(synchronizer != null) { - synchronizer.preUpdateLockRecord(resource, owner); - } - try { - if(useReal) { - return super.updateLockRecord(connection, resource, owner, timeout, ver); - } - LockRecord lockRecord = loadLockRecord(connection, resource); - synchronized(lockRecord) { - // should be atomic operation - if(ver != lockRecord.getVer()) { - return false; - } - lockRecord.setOwner(owner); - lockRecord.setUpdated(System.currentTimeMillis()); - lockRecord.setTimeout(timeout); - lockRecord.setVer(ver + 1); - } - return true; - } finally { - if(synchronizer != null) { - synchronizer.postUpdateLockRecord(resource, owner); - } - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java deleted file mode 100644 index d652c7523..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/TestMySqlLockManager.java +++ /dev/null @@ -1,230 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.optimistic; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; -import org.onap.appc.lockmanager.impl.sql.MySqlLockManagerBaseTests; -import org.onap.appc.lockmanager.impl.sql.Synchronizer; - -import java.util.concurrent.*; - -public class TestMySqlLockManager extends MySqlLockManagerBaseTests { - - @Override - protected JdbcLockManager createJdbcLockManager(boolean useReal) { - return new MySqlLockManagerMock(useReal); - } - - @Test - public void testConcurrentLockDifferentOwners() throws LockException, InterruptedException, ExecutionException, TimeoutException { - - final int participantsNo = 2; - Synchronizer synchronizer = new Synchronizer(participantsNo) { - - private boolean wait = true; - - @Override - public void preAddLockRecord(String resource, String owner) { - if(Owner.A.name().equals(owner)) { - synchronized(this) { - if(wait) { - waitOn(this); - } - } - } - } - - @Override - public void postAddLockRecord(String resource, String owner) { - if(!Owner.A.name().equals(owner)) { - synchronized(this) { - notifyAll(); - wait = false; - } - } - } - - @Override - public void preUpdateLockRecord(String resource, String owner) { - preAddLockRecord(resource, owner); - } - - @Override - public void postUpdateLockRecord(String resource, String owner) { - postAddLockRecord(resource, owner); - } - }; - if(!setSynchronizer(synchronizer)) { - return; - } - ExecutorService executor = Executors.newFixedThreadPool(participantsNo); - // acquireLock by owner A should fail as it will wait for acquireLock by owner B - Future future1 = executor.submit(new Callable() { - @Override - public Boolean call() throws Exception { - try { - lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - return false; - } catch(LockException e) { - // this call should fail as Synchronizer delays its lock to make sure the second call locks the resource first - Assert.assertEquals("Cannot lock resource [" + Resource.Resource1.name() + "] for [" + Owner.A.name() + "]: already locked by [" + Owner.B.name() + "]", e.getMessage()); - return true; - } - } - }); - try { - // acquireLock by owner B should success - Future future2 = executor.submit(new Callable() { - @Override - public Boolean call() throws Exception { - // this call should success as Synchronizer delays the above lock to make sure this call success to lock the resource - return lockManager.acquireLock(Resource.Resource1.name(), Owner.B.name()); - } - }); - try { - Assert.assertTrue(future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS)); - Assert.assertTrue(future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS)); - } finally { - future2.cancel(true); - } - } finally { - future1.cancel(true); - } - } - - @Test - public void testConcurrentLockSameOwner() throws LockException, InterruptedException, ExecutionException, TimeoutException { - final int participantsNo = 2; - Synchronizer synchronizer = new Synchronizer(participantsNo) { - - private boolean wait = true; - - @Override - public void preAddLockRecord(String resource, String owner) { - synchronized(this) { - if(wait) { - wait = false; - waitOn(this); - } - } - } - - @Override - public void postAddLockRecord(String resource, String owner) { - synchronized(this) { - notifyAll(); - } - } - }; - if(!setSynchronizer(synchronizer)) { - return; - } - ExecutorService executor = Executors.newFixedThreadPool(participantsNo); - // one acquireLock should return true and the other should return false - Callable callable = new Callable() { - @Override - public Boolean call() throws Exception { - return lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - } - }; - Future future1 = executor.submit(callable); - try { - Future future2 = executor.submit(callable); - try { - boolean future1Res = future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); - boolean future2Res = future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); - // one of the lock requests should return true, the other one false as lock is requested simultaneously from 2 threads by same owner - Assert.assertNotEquals(future1Res, future2Res); - } finally { - future2.cancel(true); - } - } finally { - future1.cancel(true); - } - } - - @Test - public void testConcurrentUnlockSameOwner() throws LockException, InterruptedException, ExecutionException, TimeoutException { - lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - final int participantsNo = 2; - Synchronizer synchronizer = new Synchronizer(participantsNo) { - - private boolean wait = true; - - @Override - public void preUpdateLockRecord(String resource, String owner) { - synchronized(this) { - // make sure second call updates the LockRecord first - if(wait) { - wait = false; - waitOn(this); - } - } - } - - @Override - public void postUpdateLockRecord(String resource, String owner) { - synchronized(this) { - notifyAll(); - } - } - }; - if(!setSynchronizer(synchronizer)) { - return; - } - ExecutorService executor = Executors.newFixedThreadPool(participantsNo); - Callable callable = new Callable() { - @Override - public Boolean call() throws Exception { - try { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - // one of the unlock calls should success - return true; - } catch(LockException e) { - // one of the unlock calls should throw the LockException as the resource should already be unlocked by other call - Assert.assertEquals("Error unlocking resource [" + Resource.Resource1.name() + "]: resource is not locked", e.getMessage()); - return false; - } - } - }; - Future future1 = executor.submit(callable); - try { - Future future2 = executor.submit(callable); - try { - boolean future1Res = future1.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); - boolean future2Res = future2.get(CONCURRENT_TEST_WAIT_TIME, TimeUnit.SECONDS); - // one of the unlock calls should return true, the other one false as unlock is requested simultaneously from 2 threads by same owner - Assert.assertNotEquals(future1Res, future2Res); - } finally { - future2.cancel(true); - } - } finally { - future1.cancel(true); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java deleted file mode 100644 index a4bbd3406..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/MySqlLockManagerMock.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.pessimistic; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.onap.appc.lockmanager.api.LockRuntimeException; -import org.onap.appc.lockmanager.impl.sql.Synchronizer; -import org.onap.appc.lockmanager.impl.sql.SynchronizerReceiver; -import org.onap.appc.lockmanager.impl.sql.pessimistic.LockRecord; -import org.onap.appc.lockmanager.impl.sql.pessimistic.MySqlLockManager; - -class MySqlLockManagerMock extends MySqlLockManager implements SynchronizerReceiver { - - private final Map locks = new HashMap<>(); - private final Lock lock = new ReentrantLock(); - private boolean useReal; - private Synchronizer synchronizer; - - MySqlLockManagerMock(boolean useReal) { - this.useReal = useReal; - } - - @Override - public void setSynchronizer(Synchronizer synchronizer) { - this.synchronizer = synchronizer; - } - - @Override - protected Connection openDbConnection() { - if(useReal) { - return super.openDbConnection(); - } - return null; - } - - @Override - protected void closeDbConnection(Connection connection) { - if(useReal) { - super.closeDbConnection(connection); - } - } - - @Override - protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException { - LockRecord res; - if(useReal) { - res = super.loadLockRecord(connection, resource); - } else { - res = locks.get(resource); - } - if(synchronizer != null) { - synchronizer.postLoadLockRecord(resource, (res == null) ? null : res.getOwner()); - } - return res; - } - - @Override - protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(synchronizer != null) { - synchronizer.preAddLockRecord(resource, owner); - } - try { - if(useReal) { - super.addLockRecord(connection, resource, owner, timeout); - return; - } - LockRecord lockRecord = new LockRecord(resource); - lockRecord.setOwner(owner); - lockRecord.setUpdated(System.currentTimeMillis()); - lockRecord.setTimeout(timeout); - locks.put(resource, lockRecord); - } finally { - if(synchronizer != null) { - synchronizer.postAddLockRecord(resource, owner); - } - } - } - - @Override - protected void updateLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException { - if(synchronizer != null) { - synchronizer.preUpdateLockRecord(resource, owner); - } - try { - if(useReal) { - super.updateLockRecord(connection, resource, owner, timeout); - return; - } - LockRecord lockRecord = loadLockRecord(connection, resource); - lockRecord.setOwner(owner); - lockRecord.setUpdated(System.currentTimeMillis()); - lockRecord.setTimeout(timeout); - locks.put(resource, lockRecord); - } finally { - if(synchronizer != null) { - synchronizer.postUpdateLockRecord(resource, owner); - } - } - } - - @Override - protected void enterCriticalSection(Connection connection, String resource) { - if(useReal) { - super.enterCriticalSection(connection, resource); - return; - } - try { - if(!lock.tryLock(criticalSectionWaitTimeoutSecs, TimeUnit.SECONDS)) { - throw new LockRuntimeException("Cannot obtain critical section lock for resource [" + resource + "]."); - } - } catch(InterruptedException e) { - throw new LockRuntimeException("Cannot obtain critical section lock.", e); - } - } - - @Override - protected void leaveCriticalSection(Connection connection, String resource) { - if(useReal) { - super.leaveCriticalSection(connection, resource); - return; - } - lock.unlock(); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java deleted file mode 100644 index c54cfc81a..000000000 --- a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/test/java/org/openecomp/appc/lockmanager/impl/sql/pessimistic/TestMySqlLockManager.java +++ /dev/null @@ -1,124 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lockmanager.impl.sql.pessimistic; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockRuntimeException; -import org.onap.appc.lockmanager.impl.sql.JdbcLockManager; -import org.onap.appc.lockmanager.impl.sql.MySqlLockManagerBaseTests; -import org.onap.appc.lockmanager.impl.sql.Synchronizer; -import org.onap.appc.lockmanager.impl.sql.pessimistic.MySqlLockManager; - -import java.util.concurrent.*; - -public class TestMySqlLockManager extends MySqlLockManagerBaseTests { - - private static int CRITICAL_SECTION_WAIT_TIMEOUT = 1; // in secs - - @Override - protected JdbcLockManager createJdbcLockManager(boolean useReal) { - return new MySqlLockManagerMock(useReal); - } - - @Test - public void testConcurrentLock() throws LockException, InterruptedException, ExecutionException, TimeoutException { - try { - callConcurrentTest(new Callable() { - @Override - public Boolean call() throws Exception { - try { - Assert.assertTrue(lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name())); - return true; - } catch(LockRuntimeException e) { - Assert.assertEquals("Cannot obtain critical section lock for resource [" + Resource.Resource1.name() + "].", e.getMessage()); - return false; - } - } - }); - } finally { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - } - } - - @Test - public void testConcurrentUnlock() throws LockException, InterruptedException, ExecutionException, TimeoutException { - lockManager.acquireLock(Resource.Resource1.name(), Owner.A.name()); - callConcurrentTest(new Callable() { - @Override - public Boolean call() throws Exception { - try { - lockManager.releaseLock(Resource.Resource1.name(), Owner.A.name()); - return true; - } catch(LockRuntimeException e) { - Assert.assertEquals("Cannot obtain critical section lock for resource [" + Resource.Resource1.name() + "].", e.getMessage()); - return false; - } - } - }); - } - - private void callConcurrentTest(Callable callable) throws LockException, InterruptedException, ExecutionException, TimeoutException { - final int participantsNo = 2; - Synchronizer synchronizer = new Synchronizer(participantsNo) { - - @Override - protected void waitForAllParticipants(Object waitObj, int totalParticipantsNo, int currentParticipantsNo) { - waitOn(this, TimeUnit.MILLISECONDS.convert(1 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); // add 1 sec to make sure timeout occured - } - }; - if(!setSynchronizer(synchronizer)) { - return; - } - ((MySqlLockManager)lockManager).setCriticalSectionWaitTimeoutSecs(CRITICAL_SECTION_WAIT_TIMEOUT); - ExecutorService executor = Executors.newFixedThreadPool(participantsNo); - Future future1 = executor.submit(callable); - try { - for(int i = 0; i < 10; i++) { - Thread.sleep(100); - if(synchronizer.getParticipantCount() > 0) { - break; - } - } - // make sure 1st thread gets inside critical section - if(synchronizer.getParticipantCount() < 1) { - Assert.fail(getClass().getName() + " first thread failed to acquireLock()"); - } - Future future2 = executor.submit(callable); - try { - // 1st thread should acquire the lock - Assert.assertTrue(future1.get(3 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); - // 2nd thread should fail waiting for critical section - Assert.assertFalse(future2.get(2 + CRITICAL_SECTION_WAIT_TIMEOUT, TimeUnit.SECONDS)); - } finally { - future2.cancel(true); - } - } finally { - future1.cancel(true); - setSynchronizer(null); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/AbstractRankedAttributesResolverFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/AbstractRankedAttributesResolverFactory.java new file mode 100644 index 000000000..99ac8a74e --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/AbstractRankedAttributesResolverFactory.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +import org.onap.appc.rankingframework.impl.DefaultRankedAttributesTreeFactory; + +public abstract class AbstractRankedAttributesResolverFactory implements RankedAttributesResolverFactory { + + private static class ReferenceHolder { + private static final RankedAttributesResolverFactory INSTANCE = new DefaultRankedAttributesTreeFactory(); + } + + public static RankedAttributesResolverFactory getInstance() { + return ReferenceHolder.INSTANCE; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationEntry.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationEntry.java new file mode 100644 index 000000000..66c4ce7da --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationEntry.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +public interface ConfigurationEntry { + Object getAttributeValue(String name); + R getResult(); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationSet.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationSet.java new file mode 100644 index 000000000..461d197e7 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/ConfigurationSet.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +import java.util.Collection; + +public interface ConfigurationSet { + Collection getRankedAttributeNames(); + + Iterable> getEntries(); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesContext.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesContext.java new file mode 100644 index 000000000..09e749852 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesContext.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +public interface RankedAttributesContext { + Object getAttributeValue(String name); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolver.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolver.java new file mode 100644 index 000000000..bd9da0911 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolver.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +public interface RankedAttributesResolver { + R resolve(RankedAttributesContext context); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolverFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolverFactory.java new file mode 100644 index 000000000..4f5a85299 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/RankedAttributesResolverFactory.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +public interface RankedAttributesResolverFactory { + RankedAttributesResolver create(ConfigurationSet config); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/BacktraceStrategy.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/BacktraceStrategy.java new file mode 100644 index 000000000..6523fef65 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/BacktraceStrategy.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.onap.appc.rankingframework.RankedAttributesContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +class BacktraceStrategy implements Strategy { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(BacktraceStrategy.class); + + @Override + public R resolve(CompositeNode rootNode, List rankedNames, RankedAttributesContext context) { + + if (logger.isDebugEnabled()) { + StringBuilder buff = new StringBuilder(128); + for (String name : rankedNames) { + buff.append("/{").append(name).append(" = ").append(Utils.value(context.getAttributeValue(name))).append('}'); + } + logger.debug(String.format("Trying to resolve path: %s", buff)); + } + + Set visited = new HashSet<>(); + + CompositeNode parentNode = rootNode; + int depth = 0; + boolean stop = false; + R result = null; + + String attribute = null; + Object value = null; + + do { + if (value == null) { + attribute = rankedNames.get(depth); + value = Utils.value(context.getAttributeValue(attribute)); + } + + Node childNode = parentNode.children().get(value); + + if (childNode != null) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Found matching node '%s' - checking it out", childNode)); + } + + if (!visited.add(childNode.id())) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("The matching node '%s' was checked before - ignoring it", childNode)); + } + childNode = null; + } + } else { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Node '%s/{%s = %s}' not found - falling back", parentNode, attribute, value != null ? value : "NULL")); + } + } + + if (childNode != null) { + switch (childNode.type()) { + case COMPOSITE: + depth++; + value = null; + parentNode = (CompositeNode) childNode; + break; + case LEAF: + if (logger.isDebugEnabled()) { + logger.debug( String.format("Result node has been resolved succesfully - '%s'", childNode)); + } + result = ((LeafNode) childNode).result(); + stop = true; + break; + default: + throw new IllegalStateException(childNode.type().name()); + } + } else { + if (!value.equals(Constants.DEFAULT_MATCH)) { + logger.debug("Exact match didn't work, trying the default option, if any"); + value = Constants.DEFAULT_MATCH; + } else if (depth > 0) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Exact match didn't work and no default option available beneath '%s' - moving out", parentNode)); + } + depth--; + value = null; + parentNode = parentNode.parent(); + } else { + logger.debug("Didn't success to resolve the path - stopping without result"); + stop = true; + } + } + } while (!stop); + + return result; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/CompositeNode.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/CompositeNode.java new file mode 100644 index 000000000..8d15c5632 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/CompositeNode.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.Map; + +class CompositeNode extends NodeBase { + + private final Map> children; + + CompositeNode(String name, Object value, CompositeNode parent, Map> children) { + super(name, value, parent, Type.COMPOSITE); + this.children = children; + } + + Map> children() { + return children; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Constants.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Constants.java new file mode 100644 index 000000000..2e4ffd8e1 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Constants.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +class Constants { + + private Constants() { + } + + static final String DEFAULT_MATCH = "*"; +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java new file mode 100644 index 000000000..4d59735b5 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.onap.appc.rankingframework.ConfigurationSet; +import org.onap.appc.rankingframework.RankedAttributesResolver; +import org.onap.appc.rankingframework.RankedAttributesResolverFactory; + +public final class DefaultRankedAttributesTreeFactory implements RankedAttributesResolverFactory { + + private final Strategy DEFAULT_STRATEGY = new BacktraceStrategy(); + + @Override + public RankedAttributesResolver create(ConfigurationSet config) { + + CompositeNode root = RankedAttributesTreeBuilder.build(config); + RankedAttributesResolver tree = new RankedAttributesTree(root, toList(config.getRankedAttributeNames()), + DEFAULT_STRATEGY); + return tree; + } + + private static List toList(Collection col) { + return Collections.unmodifiableList(new ArrayList<>(col)); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/LeafNode.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/LeafNode.java new file mode 100644 index 000000000..c6bb97378 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/LeafNode.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +class LeafNode extends NodeBase { + + private final R result; + + LeafNode(String name, Object value, CompositeNode parent, R result) { + super(name, value, parent, Type.LEAF); + this.result = result; + } + + R result() { + return result; + } + + @Override + public String toString() { + StringBuffer buff = new StringBuffer(128); + buff.append(super.toString()); + buff.append(" --> "); + buff.append(result.toString()); + return buff.toString(); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Node.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Node.java new file mode 100644 index 000000000..940e50972 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Node.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +interface Node { + enum Type { + LEAF, COMPOSITE + } + + String id(); + + String name(); + + Object value(); + + CompositeNode parent(); + + Type type(); + + boolean isDefaultMatch(); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/NodeBase.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/NodeBase.java new file mode 100644 index 000000000..1075cca50 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/NodeBase.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.UUID; + +abstract class NodeBase implements Node { + + private final String name; + private final Object value; + private final Type type; + private final CompositeNode parent; + private final String id = UUID.randomUUID().toString(); + + NodeBase(String name, Object value, CompositeNode parent, Type type) { + this.name = name; + this.value = value; + this.parent = parent; + this.type = type; + } + + @Override + public String id() { + return id; + } + + @Override + public Type type() { + return type; + } + + @Override + public String name() { + return name; + } + + @Override + public Object value() { + return value; + } + + @Override + public CompositeNode parent() { + return parent; + } + + @Override + public boolean isDefaultMatch() { + return value.equals(Constants.DEFAULT_MATCH); + } + + @Override + public String toString() { + if (!name.equals("ROOT")) { + StringBuffer buff = new StringBuffer(128); + if (parent != null) { + buff.append(parent.toString()); + } + buff.append("/{"); + buff.append(name).append(" = ").append(value); + buff.append("}"); + + return buff.toString(); + } else { + return ""; + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTree.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTree.java new file mode 100644 index 000000000..f3e3191ec --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTree.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.List; + +import org.onap.appc.rankingframework.RankedAttributesContext; +import org.onap.appc.rankingframework.RankedAttributesResolver; + +class RankedAttributesTree implements RankedAttributesResolver { + + private final CompositeNode root; + private final Strategy strategy; + private final List rankedNames; + + RankedAttributesTree(CompositeNode root, List rankedNames, Strategy strategy) { + this.root = root; + this.rankedNames = rankedNames; + this.strategy = strategy; + } + + @Override + public R resolve(RankedAttributesContext context) { + return strategy.resolve(root, rankedNames, context); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTreeBuilder.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTreeBuilder.java new file mode 100644 index 000000000..2a7cfbfe0 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/RankedAttributesTreeBuilder.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.HashMap; + +import org.onap.appc.rankingframework.ConfigurationEntry; +import org.onap.appc.rankingframework.ConfigurationSet; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +class RankedAttributesTreeBuilder { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RankedAttributesTreeBuilder.class); + + private RankedAttributesTreeBuilder() { + } + + static CompositeNode build(ConfigurationSet config) { + + Object[] names = config.getRankedAttributeNames().toArray(); + + CompositeNode root = new CompositeNode<>("ROOT", Constants.DEFAULT_MATCH, null, + new HashMap>()); + + if (logger.isDebugEnabled()) { + logger.debug(String.format("Building decision tree for ranked attributes: %s", config.getRankedAttributeNames())); + } + + for (ConfigurationEntry entry : config.getEntries()) { + process(entry, names, root); + } + + return root; + } + + private static void process(ConfigurationEntry entry, Object[] names, CompositeNode root) { + CompositeNode parentNode = null; + for (int i = 0; i < names.length; i++) { + + if (i == 0) { + parentNode = root; + } + + final String name = (String) names[i]; + + final Object value = value(entry, name); + + if (i < names.length - 1) { + CompositeNode currentNode = (CompositeNode) parentNode.children().get(value); + if (currentNode == null) { + currentNode = new CompositeNode<>(name, value, parentNode, new HashMap>()); + parentNode.children().put(value, currentNode); + } + parentNode = currentNode; + } else { + LeafNode currentNode = (LeafNode) parentNode.children().get(value); + if (currentNode == null) { + currentNode = new LeafNode(name, value, parentNode, entry.getResult()); + parentNode.children().put(value, currentNode); + + if (logger.isDebugEnabled()) { + logger.debug(String.format("Branch has been created: %s", currentNode)); + } + } else { + logger.error( + String.format("Duplicated configuration entry has been detected for attribute '%s' with value '%s' - the node '%s'exists already", + name, + value, + currentNode)); + throw new IllegalArgumentException("Duplicated configuration entry: " + currentNode); + } + } + } + } + + private static Object value(ConfigurationEntry entry, String name) { + Object value = entry.getAttributeValue(name); + return Utils.value(value); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Strategy.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Strategy.java new file mode 100644 index 000000000..36f898163 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Strategy.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +import java.util.List; + +import org.onap.appc.rankingframework.RankedAttributesContext; + +interface Strategy { + R resolve(CompositeNode root, List rankedNames, RankedAttributesContext context); +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Utils.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Utils.java new file mode 100644 index 000000000..fb18377f9 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/onap/appc/rankingframework/impl/Utils.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework.impl; + +class Utils { + + private Utils() { + } + + static Object value(Object value) { + if (value == null || (value instanceof String && isEmpty((String) value))) { + value = Constants.DEFAULT_MATCH; + } + + return value; + } + + private static boolean isEmpty(String str) { + return str == null || str.length() == 0; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/AbstractRankedAttributesResolverFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/AbstractRankedAttributesResolverFactory.java deleted file mode 100644 index 99ac8a74e..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/AbstractRankedAttributesResolverFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -import org.onap.appc.rankingframework.impl.DefaultRankedAttributesTreeFactory; - -public abstract class AbstractRankedAttributesResolverFactory implements RankedAttributesResolverFactory { - - private static class ReferenceHolder { - private static final RankedAttributesResolverFactory INSTANCE = new DefaultRankedAttributesTreeFactory(); - } - - public static RankedAttributesResolverFactory getInstance() { - return ReferenceHolder.INSTANCE; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationEntry.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationEntry.java deleted file mode 100644 index 66c4ce7da..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationEntry.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -public interface ConfigurationEntry { - Object getAttributeValue(String name); - R getResult(); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationSet.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationSet.java deleted file mode 100644 index 461d197e7..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/ConfigurationSet.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -import java.util.Collection; - -public interface ConfigurationSet { - Collection getRankedAttributeNames(); - - Iterable> getEntries(); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesContext.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesContext.java deleted file mode 100644 index 09e749852..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesContext.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -public interface RankedAttributesContext { - Object getAttributeValue(String name); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolver.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolver.java deleted file mode 100644 index bd9da0911..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolver.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -public interface RankedAttributesResolver { - R resolve(RankedAttributesContext context); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolverFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolverFactory.java deleted file mode 100644 index 4f5a85299..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/RankedAttributesResolverFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -public interface RankedAttributesResolverFactory { - RankedAttributesResolver create(ConfigurationSet config); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/BacktraceStrategy.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/BacktraceStrategy.java deleted file mode 100644 index 6523fef65..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/BacktraceStrategy.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.onap.appc.rankingframework.RankedAttributesContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -class BacktraceStrategy implements Strategy { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(BacktraceStrategy.class); - - @Override - public R resolve(CompositeNode rootNode, List rankedNames, RankedAttributesContext context) { - - if (logger.isDebugEnabled()) { - StringBuilder buff = new StringBuilder(128); - for (String name : rankedNames) { - buff.append("/{").append(name).append(" = ").append(Utils.value(context.getAttributeValue(name))).append('}'); - } - logger.debug(String.format("Trying to resolve path: %s", buff)); - } - - Set visited = new HashSet<>(); - - CompositeNode parentNode = rootNode; - int depth = 0; - boolean stop = false; - R result = null; - - String attribute = null; - Object value = null; - - do { - if (value == null) { - attribute = rankedNames.get(depth); - value = Utils.value(context.getAttributeValue(attribute)); - } - - Node childNode = parentNode.children().get(value); - - if (childNode != null) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Found matching node '%s' - checking it out", childNode)); - } - - if (!visited.add(childNode.id())) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("The matching node '%s' was checked before - ignoring it", childNode)); - } - childNode = null; - } - } else { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Node '%s/{%s = %s}' not found - falling back", parentNode, attribute, value != null ? value : "NULL")); - } - } - - if (childNode != null) { - switch (childNode.type()) { - case COMPOSITE: - depth++; - value = null; - parentNode = (CompositeNode) childNode; - break; - case LEAF: - if (logger.isDebugEnabled()) { - logger.debug( String.format("Result node has been resolved succesfully - '%s'", childNode)); - } - result = ((LeafNode) childNode).result(); - stop = true; - break; - default: - throw new IllegalStateException(childNode.type().name()); - } - } else { - if (!value.equals(Constants.DEFAULT_MATCH)) { - logger.debug("Exact match didn't work, trying the default option, if any"); - value = Constants.DEFAULT_MATCH; - } else if (depth > 0) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Exact match didn't work and no default option available beneath '%s' - moving out", parentNode)); - } - depth--; - value = null; - parentNode = parentNode.parent(); - } else { - logger.debug("Didn't success to resolve the path - stopping without result"); - stop = true; - } - } - } while (!stop); - - return result; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/CompositeNode.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/CompositeNode.java deleted file mode 100644 index 8d15c5632..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/CompositeNode.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.Map; - -class CompositeNode extends NodeBase { - - private final Map> children; - - CompositeNode(String name, Object value, CompositeNode parent, Map> children) { - super(name, value, parent, Type.COMPOSITE); - this.children = children; - } - - Map> children() { - return children; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Constants.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Constants.java deleted file mode 100644 index 2e4ffd8e1..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Constants.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -class Constants { - - private Constants() { - } - - static final String DEFAULT_MATCH = "*"; -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java deleted file mode 100644 index 4d59735b5..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/DefaultRankedAttributesTreeFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.onap.appc.rankingframework.ConfigurationSet; -import org.onap.appc.rankingframework.RankedAttributesResolver; -import org.onap.appc.rankingframework.RankedAttributesResolverFactory; - -public final class DefaultRankedAttributesTreeFactory implements RankedAttributesResolverFactory { - - private final Strategy DEFAULT_STRATEGY = new BacktraceStrategy(); - - @Override - public RankedAttributesResolver create(ConfigurationSet config) { - - CompositeNode root = RankedAttributesTreeBuilder.build(config); - RankedAttributesResolver tree = new RankedAttributesTree(root, toList(config.getRankedAttributeNames()), - DEFAULT_STRATEGY); - return tree; - } - - private static List toList(Collection col) { - return Collections.unmodifiableList(new ArrayList<>(col)); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/LeafNode.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/LeafNode.java deleted file mode 100644 index c6bb97378..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/LeafNode.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -class LeafNode extends NodeBase { - - private final R result; - - LeafNode(String name, Object value, CompositeNode parent, R result) { - super(name, value, parent, Type.LEAF); - this.result = result; - } - - R result() { - return result; - } - - @Override - public String toString() { - StringBuffer buff = new StringBuffer(128); - buff.append(super.toString()); - buff.append(" --> "); - buff.append(result.toString()); - return buff.toString(); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Node.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Node.java deleted file mode 100644 index 940e50972..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Node.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -interface Node { - enum Type { - LEAF, COMPOSITE - } - - String id(); - - String name(); - - Object value(); - - CompositeNode parent(); - - Type type(); - - boolean isDefaultMatch(); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/NodeBase.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/NodeBase.java deleted file mode 100644 index 1075cca50..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/NodeBase.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.UUID; - -abstract class NodeBase implements Node { - - private final String name; - private final Object value; - private final Type type; - private final CompositeNode parent; - private final String id = UUID.randomUUID().toString(); - - NodeBase(String name, Object value, CompositeNode parent, Type type) { - this.name = name; - this.value = value; - this.parent = parent; - this.type = type; - } - - @Override - public String id() { - return id; - } - - @Override - public Type type() { - return type; - } - - @Override - public String name() { - return name; - } - - @Override - public Object value() { - return value; - } - - @Override - public CompositeNode parent() { - return parent; - } - - @Override - public boolean isDefaultMatch() { - return value.equals(Constants.DEFAULT_MATCH); - } - - @Override - public String toString() { - if (!name.equals("ROOT")) { - StringBuffer buff = new StringBuffer(128); - if (parent != null) { - buff.append(parent.toString()); - } - buff.append("/{"); - buff.append(name).append(" = ").append(value); - buff.append("}"); - - return buff.toString(); - } else { - return ""; - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTree.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTree.java deleted file mode 100644 index f3e3191ec..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTree.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.List; - -import org.onap.appc.rankingframework.RankedAttributesContext; -import org.onap.appc.rankingframework.RankedAttributesResolver; - -class RankedAttributesTree implements RankedAttributesResolver { - - private final CompositeNode root; - private final Strategy strategy; - private final List rankedNames; - - RankedAttributesTree(CompositeNode root, List rankedNames, Strategy strategy) { - this.root = root; - this.rankedNames = rankedNames; - this.strategy = strategy; - } - - @Override - public R resolve(RankedAttributesContext context) { - return strategy.resolve(root, rankedNames, context); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTreeBuilder.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTreeBuilder.java deleted file mode 100644 index 2a7cfbfe0..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/RankedAttributesTreeBuilder.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.HashMap; - -import org.onap.appc.rankingframework.ConfigurationEntry; -import org.onap.appc.rankingframework.ConfigurationSet; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -class RankedAttributesTreeBuilder { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RankedAttributesTreeBuilder.class); - - private RankedAttributesTreeBuilder() { - } - - static CompositeNode build(ConfigurationSet config) { - - Object[] names = config.getRankedAttributeNames().toArray(); - - CompositeNode root = new CompositeNode<>("ROOT", Constants.DEFAULT_MATCH, null, - new HashMap>()); - - if (logger.isDebugEnabled()) { - logger.debug(String.format("Building decision tree for ranked attributes: %s", config.getRankedAttributeNames())); - } - - for (ConfigurationEntry entry : config.getEntries()) { - process(entry, names, root); - } - - return root; - } - - private static void process(ConfigurationEntry entry, Object[] names, CompositeNode root) { - CompositeNode parentNode = null; - for (int i = 0; i < names.length; i++) { - - if (i == 0) { - parentNode = root; - } - - final String name = (String) names[i]; - - final Object value = value(entry, name); - - if (i < names.length - 1) { - CompositeNode currentNode = (CompositeNode) parentNode.children().get(value); - if (currentNode == null) { - currentNode = new CompositeNode<>(name, value, parentNode, new HashMap>()); - parentNode.children().put(value, currentNode); - } - parentNode = currentNode; - } else { - LeafNode currentNode = (LeafNode) parentNode.children().get(value); - if (currentNode == null) { - currentNode = new LeafNode(name, value, parentNode, entry.getResult()); - parentNode.children().put(value, currentNode); - - if (logger.isDebugEnabled()) { - logger.debug(String.format("Branch has been created: %s", currentNode)); - } - } else { - logger.error( - String.format("Duplicated configuration entry has been detected for attribute '%s' with value '%s' - the node '%s'exists already", - name, - value, - currentNode)); - throw new IllegalArgumentException("Duplicated configuration entry: " + currentNode); - } - } - } - } - - private static Object value(ConfigurationEntry entry, String name) { - Object value = entry.getAttributeValue(name); - return Utils.value(value); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Strategy.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Strategy.java deleted file mode 100644 index 36f898163..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Strategy.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -import java.util.List; - -import org.onap.appc.rankingframework.RankedAttributesContext; - -interface Strategy { - R resolve(CompositeNode root, List rankedNames, RankedAttributesContext context); -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Utils.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Utils.java deleted file mode 100644 index fb18377f9..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/main/java/org/openecomp/appc/rankingframework/impl/Utils.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework.impl; - -class Utils { - - private Utils() { - } - - static Object value(Object value) { - if (value == null || (value instanceof String && isEmpty((String) value))) { - value = Constants.DEFAULT_MATCH; - } - - return value; - } - - private static boolean isEmpty(String str) { - return str == null || str.length() == 0; - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/onap/appc/rankingframework/TestRankingFramework.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/onap/appc/rankingframework/TestRankingFramework.java new file mode 100644 index 000000000..99376923f --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/onap/appc/rankingframework/TestRankingFramework.java @@ -0,0 +1,228 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rankingframework; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; +import org.onap.appc.rankingframework.ConfigurationEntry; +import org.onap.appc.rankingframework.ConfigurationSet; +import org.onap.appc.rankingframework.RankedAttributesContext; +import org.onap.appc.rankingframework.RankedAttributesResolver; + +public class TestRankingFramework { + + private static final String COUNTRY = "COUNTRY"; + private static final String STATE = "STATE"; + private static final String CITY = "CITY"; + + private static final List NAMES = Arrays.asList(COUNTRY, STATE, CITY); + + private static final String PACIFIC = "Pacific"; + private static final String ATLANTIC = "Atlantic"; + private static final String ARCTIC = "Arctic"; + private static final String NA = "N/A"; + + private static ConfigurationEntry entry(String [] attributes, String result) { + if (attributes == null || attributes.length != NAMES.size()) { + throw new IllegalArgumentException(); + } + + Map map = new HashMap<>(attributes.length); + for (int i = 0; i < attributes.length; i++) { + map.put(NAMES.get(i), attributes[i]); + } + + return new ConfigurationEntryImpl(map, result); + } + + private static ConfigurationSet config(ConfigurationEntry ... entries) { + return new ConfigurationSetImpl(Arrays.asList(entries), NAMES); + } + + private static RankedAttributesContext context(String ... attributes) { + if (attributes == null || attributes.length != NAMES.size()) { + throw new IllegalArgumentException(); + } + + Map map = new HashMap<>(attributes.length); + for (int i = 0; i < attributes.length; i++) { + map.put(NAMES.get(i), attributes[i]); + } + + return new Context(map); + } + + private static class ConfigurationSetImpl implements ConfigurationSet { + + private final Collection> entries; + private final Collection names; + + ConfigurationSetImpl(Collection> entries, Collection names) { + this.entries = entries; + this.names = names; + } + + @Override + public Iterable> getEntries() { + return entries; + } + + @Override + public Collection getRankedAttributeNames() { + return names; + } + } + + private static class ConfigurationEntryImpl implements ConfigurationEntry { + + private final Map attributes; + private final String result; + + ConfigurationEntryImpl(Map attributes, String result) { + this.attributes = attributes; + this.result = result; + } + + @Override + public Object getAttributeValue(String name) { + return attributes.get(name); + } + + @Override + public String getResult() { + return result; + } + } + + private static class Context implements RankedAttributesContext { + + private final Map map; + + Context(Map map) { + this.map = map; + } + + @Override + public Object getAttributeValue(String name) { + return map.get(name); + } + } + + private static ConfigurationSet testData() { + @SuppressWarnings("unchecked") + ConfigurationSet config = config( + entry(new String [] {"US", "CA", "SFO"}, PACIFIC), + entry(new String [] {"US", "CA", "LA"}, PACIFIC), + entry(new String [] {"US", "FL", "MIAMI"}, ATLANTIC), + entry(new String [] {"US", "AK", "Barrow"}, ARCTIC), + entry(new String [] {"US", "AK", "*"}, PACIFIC), + entry(new String [] {"US", "*", "Houston"}, ATLANTIC), + entry(new String [] {"US", "*", "*"}, NA) + ); + + return config; + } + + private static RankedAttributesResolver resolver(ConfigurationSet config) { + return AbstractRankedAttributesResolverFactory.getInstance().create(config); + } + + @Test + public void testExactMatch() { + + ConfigurationSet config = testData(); + + RankedAttributesResolver resolver = resolver(config) ; + + RankedAttributesContext context = context("US", "CA", "SFO"); + + String result = resolver.resolve(context); + + Assert.assertEquals(PACIFIC, result); + } + + @Test + public void testDefaultMatchPartial() { + + ConfigurationSet config = testData(); + + RankedAttributesResolver resolver = resolver(config) ; + + RankedAttributesContext context = context("US", "AK", "Anchorage"); + + String result = resolver.resolve(context); + + Assert.assertEquals(PACIFIC, result); + } + + @Test + public void testDefaultMatchFull() { + + ConfigurationSet config = testData(); + + RankedAttributesResolver resolver = resolver(config) ; + + RankedAttributesContext context = context("US", "IL", "Chicago"); + + String result = resolver.resolve(context); + + Assert.assertEquals(NA, result); + } + + @Test + public void testDefaultMatchInTheMiddle() { + + ConfigurationSet config = testData(); + + RankedAttributesResolver resolver = resolver(config) ; + + RankedAttributesContext context = context("US", "TX", "Houston"); + + String result = resolver.resolve(context); + + Assert.assertEquals(ATLANTIC, result); + } + + @Test + public void testBacktrace() { + + ConfigurationSet config = testData(); + + RankedAttributesResolver resolver = resolver(config) ; + + RankedAttributesContext context = context("US", "CA", "SJC"); + + String result = resolver.resolve(context); + + Assert.assertEquals(NA, result); + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/openecomp/appc/rankingframework/TestRankingFramework.java b/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/openecomp/appc/rankingframework/TestRankingFramework.java deleted file mode 100644 index 99376923f..000000000 --- a/appc-dispatcher/appc-dispatcher-common/ranking-framework-lib/src/test/java/org/openecomp/appc/rankingframework/TestRankingFramework.java +++ /dev/null @@ -1,228 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.rankingframework; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; -import org.onap.appc.rankingframework.ConfigurationEntry; -import org.onap.appc.rankingframework.ConfigurationSet; -import org.onap.appc.rankingframework.RankedAttributesContext; -import org.onap.appc.rankingframework.RankedAttributesResolver; - -public class TestRankingFramework { - - private static final String COUNTRY = "COUNTRY"; - private static final String STATE = "STATE"; - private static final String CITY = "CITY"; - - private static final List NAMES = Arrays.asList(COUNTRY, STATE, CITY); - - private static final String PACIFIC = "Pacific"; - private static final String ATLANTIC = "Atlantic"; - private static final String ARCTIC = "Arctic"; - private static final String NA = "N/A"; - - private static ConfigurationEntry entry(String [] attributes, String result) { - if (attributes == null || attributes.length != NAMES.size()) { - throw new IllegalArgumentException(); - } - - Map map = new HashMap<>(attributes.length); - for (int i = 0; i < attributes.length; i++) { - map.put(NAMES.get(i), attributes[i]); - } - - return new ConfigurationEntryImpl(map, result); - } - - private static ConfigurationSet config(ConfigurationEntry ... entries) { - return new ConfigurationSetImpl(Arrays.asList(entries), NAMES); - } - - private static RankedAttributesContext context(String ... attributes) { - if (attributes == null || attributes.length != NAMES.size()) { - throw new IllegalArgumentException(); - } - - Map map = new HashMap<>(attributes.length); - for (int i = 0; i < attributes.length; i++) { - map.put(NAMES.get(i), attributes[i]); - } - - return new Context(map); - } - - private static class ConfigurationSetImpl implements ConfigurationSet { - - private final Collection> entries; - private final Collection names; - - ConfigurationSetImpl(Collection> entries, Collection names) { - this.entries = entries; - this.names = names; - } - - @Override - public Iterable> getEntries() { - return entries; - } - - @Override - public Collection getRankedAttributeNames() { - return names; - } - } - - private static class ConfigurationEntryImpl implements ConfigurationEntry { - - private final Map attributes; - private final String result; - - ConfigurationEntryImpl(Map attributes, String result) { - this.attributes = attributes; - this.result = result; - } - - @Override - public Object getAttributeValue(String name) { - return attributes.get(name); - } - - @Override - public String getResult() { - return result; - } - } - - private static class Context implements RankedAttributesContext { - - private final Map map; - - Context(Map map) { - this.map = map; - } - - @Override - public Object getAttributeValue(String name) { - return map.get(name); - } - } - - private static ConfigurationSet testData() { - @SuppressWarnings("unchecked") - ConfigurationSet config = config( - entry(new String [] {"US", "CA", "SFO"}, PACIFIC), - entry(new String [] {"US", "CA", "LA"}, PACIFIC), - entry(new String [] {"US", "FL", "MIAMI"}, ATLANTIC), - entry(new String [] {"US", "AK", "Barrow"}, ARCTIC), - entry(new String [] {"US", "AK", "*"}, PACIFIC), - entry(new String [] {"US", "*", "Houston"}, ATLANTIC), - entry(new String [] {"US", "*", "*"}, NA) - ); - - return config; - } - - private static RankedAttributesResolver resolver(ConfigurationSet config) { - return AbstractRankedAttributesResolverFactory.getInstance().create(config); - } - - @Test - public void testExactMatch() { - - ConfigurationSet config = testData(); - - RankedAttributesResolver resolver = resolver(config) ; - - RankedAttributesContext context = context("US", "CA", "SFO"); - - String result = resolver.resolve(context); - - Assert.assertEquals(PACIFIC, result); - } - - @Test - public void testDefaultMatchPartial() { - - ConfigurationSet config = testData(); - - RankedAttributesResolver resolver = resolver(config) ; - - RankedAttributesContext context = context("US", "AK", "Anchorage"); - - String result = resolver.resolve(context); - - Assert.assertEquals(PACIFIC, result); - } - - @Test - public void testDefaultMatchFull() { - - ConfigurationSet config = testData(); - - RankedAttributesResolver resolver = resolver(config) ; - - RankedAttributesContext context = context("US", "IL", "Chicago"); - - String result = resolver.resolve(context); - - Assert.assertEquals(NA, result); - } - - @Test - public void testDefaultMatchInTheMiddle() { - - ConfigurationSet config = testData(); - - RankedAttributesResolver resolver = resolver(config) ; - - RankedAttributesContext context = context("US", "TX", "Houston"); - - String result = resolver.resolve(context); - - Assert.assertEquals(ATLANTIC, result); - } - - @Test - public void testBacktrace() { - - ConfigurationSet config = testData(); - - RankedAttributesResolver resolver = resolver(config) ; - - RankedAttributesContext context = context("US", "CA", "SJC"); - - String result = resolver.resolve(context); - - Assert.assertEquals(NA, result); - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/TransactionRecorder.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/TransactionRecorder.java new file mode 100644 index 000000000..8f3c51129 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/TransactionRecorder.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.transactionrecorder; + + +import org.onap.appc.transactionrecorder.objects.TransactionRecord; + + +public interface TransactionRecorder { + /** + * Stores transaction record to appc database by calling APPC Dao layer. + * @param record Transaction record data. + */ + void store(TransactionRecord record); +} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java new file mode 100644 index 000000000..89e0d9281 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.transactionrecorder.impl; + +import org.onap.appc.dao.util.DBUtils; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.transactionrecorder.objects.TransactionRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + + + +public class TransactionRecorderImpl implements TransactionRecorder { + + private static String APPCCTL_SCHEMA = "appcctl"; + + private static final Logger logger = LoggerFactory.getLogger(TransactionRecorderImpl.class); + + /** + * Stores transaction record to appc database by calling APPC Dao layer. + * @param record Transaction record data. + */ + @Override + public void store(TransactionRecord record) { + Connection connection = null; + PreparedStatement stmt = null; + String queryString = "INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?)"; + try { + if (logger.isDebugEnabled()) { + logger.debug("Transaction Data started Inserting Successfully into DB"); + } + connection = DBUtils.getConnection(APPCCTL_SCHEMA); + stmt = connection.prepareStatement(queryString); + stmt.setTimestamp(1, new java.sql.Timestamp(record.getTimeStamp().toEpochMilli())); + stmt.setString(2, record.getRequestID()); + stmt.setTimestamp(3, new java.sql.Timestamp(record.getStartTime().toEpochMilli())); + stmt.setTimestamp(4, new java.sql.Timestamp(record.getEndTime().toEpochMilli())); + stmt.setString(5, record.getTargetID()); + stmt.setString(6, record.getTargetType()); + stmt.setString(7, record.getSubComponent()); + stmt.setString(8, record.getOperation()); + stmt.setString(9, record.getResultCode()); + stmt.setString(10, record.getDescription()); + stmt.execute(); + if (logger.isDebugEnabled()) { + logger.debug("Transaction Data Inserted Successfully into DB"); + } + } catch (SQLException e) { + logger.error("Error Accessing Database " + e); + throw new RuntimeException(e); + } finally { + DBUtils.clearResources(null, stmt, connection); + } + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/objects/TransactionRecord.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/objects/TransactionRecord.java new file mode 100644 index 000000000..ba3af9985 --- /dev/null +++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/objects/TransactionRecord.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.transactionrecorder.objects; + +import java.time.Instant; + + +public class TransactionRecord { + + /* +- Timestamp = RequestHandlerInput.RequestHeader.timeStamp +- Request ID = RequestHandlerInput.RequestHeader.requestID +- Start time = from flow +- End time = from flow +- VF_ID = RequestHandlerInput.targetID +- VF_type = genericVnf.getVnfType() +- Sub-component (optional) e.g. VFC_ID/VM UUID - ???? empty +- Operation e.g. Start, Configure etc. = CommandContext.Command +- Result - Success/Error code + description,as published to the initiator RequestHandlerResponse.ACCEPTED/RequestHandlerResponse.REJECTED + String (description) + */ + + private Instant timeStamp; + private String requestID; + private Instant startTime; + private Instant endTime; + private String targetID; + private String targetType; + private String subComponent; + private String operation; + private String resultCode; + private String description; + + public Instant getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(Instant timeStamp) { + this.timeStamp = timeStamp; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public Instant getStartTime() { + return startTime; + } + + public void setStartTime(Instant startTime) { + this.startTime = startTime; + } + + public Instant getEndTime() { + return endTime; + } + + public void setEndTime(Instant endTime) { + this.endTime = endTime; + } + + public String getTargetID() { + return targetID; + } + + public void setTargetID(String targetID) { + this.targetID = targetID; + } + + public String getTargetType() { + return targetType; + } + + public void setTargetType(String targetType) { + this.targetType = targetType; + } + + public String getSubComponent() { + return subComponent; + } + + public void setSubComponent(String subComponent) { + this.subComponent = subComponent; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getResultCode() { + return resultCode; + } + + public void setResultCode(String resultCode) { + this.resultCode = resultCode; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "TransactionRecord{" + + "timeStamp=" + timeStamp + + ", requestID='" + requestID + '\'' + + ", startTime=" + startTime + + ", endTime=" + endTime + + ", targetID='" + targetID + '\'' + + ", targetType='" + targetType + '\'' + + ", subComponent='" + subComponent + '\'' + + ", operation='" + operation + '\'' + + ", resultCode='" + resultCode + '\'' + + ", description='" + description + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/TransactionRecorder.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/TransactionRecorder.java deleted file mode 100644 index 8f3c51129..000000000 --- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/TransactionRecorder.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.transactionrecorder; - - -import org.onap.appc.transactionrecorder.objects.TransactionRecord; - - -public interface TransactionRecorder { - /** - * Stores transaction record to appc database by calling APPC Dao layer. - * @param record Transaction record data. - */ - void store(TransactionRecord record); -} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/impl/TransactionRecorderImpl.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/impl/TransactionRecorderImpl.java deleted file mode 100644 index 89e0d9281..000000000 --- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/impl/TransactionRecorderImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.transactionrecorder.impl; - -import org.onap.appc.dao.util.DBUtils; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.transactionrecorder.objects.TransactionRecord; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - - - -public class TransactionRecorderImpl implements TransactionRecorder { - - private static String APPCCTL_SCHEMA = "appcctl"; - - private static final Logger logger = LoggerFactory.getLogger(TransactionRecorderImpl.class); - - /** - * Stores transaction record to appc database by calling APPC Dao layer. - * @param record Transaction record data. - */ - @Override - public void store(TransactionRecord record) { - Connection connection = null; - PreparedStatement stmt = null; - String queryString = "INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?)"; - try { - if (logger.isDebugEnabled()) { - logger.debug("Transaction Data started Inserting Successfully into DB"); - } - connection = DBUtils.getConnection(APPCCTL_SCHEMA); - stmt = connection.prepareStatement(queryString); - stmt.setTimestamp(1, new java.sql.Timestamp(record.getTimeStamp().toEpochMilli())); - stmt.setString(2, record.getRequestID()); - stmt.setTimestamp(3, new java.sql.Timestamp(record.getStartTime().toEpochMilli())); - stmt.setTimestamp(4, new java.sql.Timestamp(record.getEndTime().toEpochMilli())); - stmt.setString(5, record.getTargetID()); - stmt.setString(6, record.getTargetType()); - stmt.setString(7, record.getSubComponent()); - stmt.setString(8, record.getOperation()); - stmt.setString(9, record.getResultCode()); - stmt.setString(10, record.getDescription()); - stmt.execute(); - if (logger.isDebugEnabled()) { - logger.debug("Transaction Data Inserted Successfully into DB"); - } - } catch (SQLException e) { - logger.error("Error Accessing Database " + e); - throw new RuntimeException(e); - } finally { - DBUtils.clearResources(null, stmt, connection); - } - } -} diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/objects/TransactionRecord.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/objects/TransactionRecord.java deleted file mode 100644 index ba3af9985..000000000 --- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/openecomp/appc/transactionrecorder/objects/TransactionRecord.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.transactionrecorder.objects; - -import java.time.Instant; - - -public class TransactionRecord { - - /* -- Timestamp = RequestHandlerInput.RequestHeader.timeStamp -- Request ID = RequestHandlerInput.RequestHeader.requestID -- Start time = from flow -- End time = from flow -- VF_ID = RequestHandlerInput.targetID -- VF_type = genericVnf.getVnfType() -- Sub-component (optional) e.g. VFC_ID/VM UUID - ???? empty -- Operation e.g. Start, Configure etc. = CommandContext.Command -- Result - Success/Error code + description,as published to the initiator RequestHandlerResponse.ACCEPTED/RequestHandlerResponse.REJECTED + String (description) - */ - - private Instant timeStamp; - private String requestID; - private Instant startTime; - private Instant endTime; - private String targetID; - private String targetType; - private String subComponent; - private String operation; - private String resultCode; - private String description; - - public Instant getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Instant timeStamp) { - this.timeStamp = timeStamp; - } - - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - public Instant getStartTime() { - return startTime; - } - - public void setStartTime(Instant startTime) { - this.startTime = startTime; - } - - public Instant getEndTime() { - return endTime; - } - - public void setEndTime(Instant endTime) { - this.endTime = endTime; - } - - public String getTargetID() { - return targetID; - } - - public void setTargetID(String targetID) { - this.targetID = targetID; - } - - public String getTargetType() { - return targetType; - } - - public void setTargetType(String targetType) { - this.targetType = targetType; - } - - public String getSubComponent() { - return subComponent; - } - - public void setSubComponent(String subComponent) { - this.subComponent = subComponent; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } - - public String getResultCode() { - return resultCode; - } - - public void setResultCode(String resultCode) { - this.resultCode = resultCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "TransactionRecord{" + - "timeStamp=" + timeStamp + - ", requestID='" + requestID + '\'' + - ", startTime=" + startTime + - ", endTime=" + endTime + - ", targetID='" + targetID + '\'' + - ", targetType='" + targetType + '\'' + - ", subComponent='" + subComponent + '\'' + - ", operation='" + operation + '\'' + - ", resultCode='" + resultCode + '\'' + - ", description='" + description + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/Constants.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/Constants.java new file mode 100644 index 000000000..64e54be97 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/Constants.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +public class Constants { + + private Constants(){} + + public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; + public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; + public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; + public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; + + public static final String CONTROLLER_IP = "127.0.0.1"; + public static final int CONTROLLER_PORT = 8181; + public static final String PROTOCOL = "http"; + + public static final String VF_LICENSE = "VF_LICENSE"; + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String SDNCTL_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + public static final String SDC_ARTIFACTS = "ASDC_ARTIFACTS"; + + // input fields names + public static final String PAYLOAD = "payload"; + + // constants fo DG + public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; + public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; + public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; + public static final String TARGET_VNF_TYPE = "target-vnf-type"; + public static final String FILE_CONTENT_FIELD_NAME = "file-content"; + public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; + public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String UPGRADE_VERSION = "upgrade-version"; + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String RESOURCEKEY = "resourceKey"; + public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; + public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; + public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; + public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; + public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; + public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; + public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; + public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; + + public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; + public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; + public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; + public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; + public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; + + public enum SDC_ARTIFACTS_FIELDS { + SERVICE_UUID, + DISTRIBUTION_ID, + SERVICE_NAME, + SERVICE_DESCRIPTION, + RESOURCE_UUID, + RESOURCE_INSTANCE_NAME, + RESOURCE_NAME, + RESOURCE_VERSION, + RESOURCE_TYPE, + ARTIFACT_UUID, + ARTIFACT_TYPE, + ARTIFACT_VERSION, + ARTIFACT_DESCRIPTION, + INTERNAL_VERSION, + CREATION_DATE, + ARTIFACT_NAME, + ARTIFACT_CONTENT + } +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseDataAccessService.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseDataAccessService.java new file mode 100644 index 000000000..f826828c4 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseDataAccessService.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +import org.onap.appc.licmgr.exception.DataAccessException; + +import java.util.Map; + + +@SuppressWarnings("JavaDoc") +public interface LicenseDataAccessService { + + /** + * + * @param schema + */ + void setSchema(String schema); + + /** + * + * @param vnfType resource name + * @param vnfVersion resource version + * @return map contains requested fields as Strings + * @throws RuntimeException + */ + Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws DataAccessException; + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseManager.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseManager.java new file mode 100644 index 000000000..f396beba1 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/LicenseManager.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +import org.onap.appc.licmgr.exception.DataAccessException; +import org.onap.appc.licmgr.objects.LicenseModel; + + +@SuppressWarnings("JavaDoc") +public interface LicenseManager { + + /** + * + * @param vnfType + * @param vnfVersion + * @return pojo object represented license model + * @throws DataAccessException + */ + LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException; + + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/exception/DataAccessException.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/exception/DataAccessException.java new file mode 100644 index 000000000..ba3def389 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/exception/DataAccessException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr.exception; + + + +public class DataAccessException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public DataAccessException(){ + } + + public DataAccessException(String message){ + super(message); + } + + public DataAccessException(Throwable cause){ + super(cause); + } + + public DataAccessException(String message , Throwable cause){ + super(message , cause); + } + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/objects/LicenseModel.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/objects/LicenseModel.java new file mode 100644 index 000000000..a2ea85ba2 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/onap/appc/licmgr/objects/LicenseModel.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr.objects; + +public class LicenseModel { + + private String entitlementPoolUuid; + + private String licenseKeyGroupUuid; + + public String getEntitlementPoolUuid() { + return entitlementPoolUuid; + } + + public void setEntitlementPoolUuid(String entitlementPoolUuid) { + this.entitlementPoolUuid = entitlementPoolUuid; + } + + public String getLicenseKeyGroupUuid() { + return licenseKeyGroupUuid; + } + + public void setLicenseKeyGroupUuid(String licenseKeyGroupUuid) { + this.licenseKeyGroupUuid = licenseKeyGroupUuid; + } +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/Constants.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/Constants.java deleted file mode 100644 index 64e54be97..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/Constants.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -public class Constants { - - private Constants(){} - - public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; - public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; - public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; - public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; - - public static final String CONTROLLER_IP = "127.0.0.1"; - public static final int CONTROLLER_PORT = 8181; - public static final String PROTOCOL = "http"; - - public static final String VF_LICENSE = "VF_LICENSE"; - - // tables and fields - public static final String NETCONF_SCHEMA = "sdnctl"; - public static final String SDNCTL_SCHEMA = "sdnctl"; - public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; - public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; - public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; - public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; - public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; - public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; - public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; - public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; - public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; - public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; - public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; - public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; - public static final String LOG_FIELD_NAME = "LOG"; - public static final String SDC_ARTIFACTS = "ASDC_ARTIFACTS"; - - // input fields names - public static final String PAYLOAD = "payload"; - - // constants fo DG - public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; - public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; - public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; - public static final String TARGET_VNF_TYPE = "target-vnf-type"; - public static final String FILE_CONTENT_FIELD_NAME = "file-content"; - public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; - public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; - public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; - public static final String UPGRADE_VERSION = "upgrade-version"; - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String RESOURCEKEY = "resourceKey"; - public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; - public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; - public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; - public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; - public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; - public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; - public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; - public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; - - public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; - public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; - public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; - public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; - public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; - - public enum SDC_ARTIFACTS_FIELDS { - SERVICE_UUID, - DISTRIBUTION_ID, - SERVICE_NAME, - SERVICE_DESCRIPTION, - RESOURCE_UUID, - RESOURCE_INSTANCE_NAME, - RESOURCE_NAME, - RESOURCE_VERSION, - RESOURCE_TYPE, - ARTIFACT_UUID, - ARTIFACT_TYPE, - ARTIFACT_VERSION, - ARTIFACT_DESCRIPTION, - INTERNAL_VERSION, - CREATION_DATE, - ARTIFACT_NAME, - ARTIFACT_CONTENT - } -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseDataAccessService.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseDataAccessService.java deleted file mode 100644 index f826828c4..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseDataAccessService.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -import org.onap.appc.licmgr.exception.DataAccessException; - -import java.util.Map; - - -@SuppressWarnings("JavaDoc") -public interface LicenseDataAccessService { - - /** - * - * @param schema - */ - void setSchema(String schema); - - /** - * - * @param vnfType resource name - * @param vnfVersion resource version - * @return map contains requested fields as Strings - * @throws RuntimeException - */ - Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws DataAccessException; - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseManager.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseManager.java deleted file mode 100644 index f396beba1..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseManager.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -import org.onap.appc.licmgr.exception.DataAccessException; -import org.onap.appc.licmgr.objects.LicenseModel; - - -@SuppressWarnings("JavaDoc") -public interface LicenseManager { - - /** - * - * @param vnfType - * @param vnfVersion - * @return pojo object represented license model - * @throws DataAccessException - */ - LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException; - - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/exception/DataAccessException.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/exception/DataAccessException.java deleted file mode 100644 index ba3def389..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/exception/DataAccessException.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr.exception; - - - -public class DataAccessException extends RuntimeException { - - private static final long serialVersionUID = -155423437162622414L; - - public DataAccessException(){ - } - - public DataAccessException(String message){ - super(message); - } - - public DataAccessException(Throwable cause){ - super(cause); - } - - public DataAccessException(String message , Throwable cause){ - super(message , cause); - } - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/objects/LicenseModel.java b/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/objects/LicenseModel.java deleted file mode 100644 index a2ea85ba2..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/objects/LicenseModel.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr.objects; - -public class LicenseModel { - - private String entitlementPoolUuid; - - private String licenseKeyGroupUuid; - - public String getEntitlementPoolUuid() { - return entitlementPoolUuid; - } - - public void setEntitlementPoolUuid(String entitlementPoolUuid) { - this.entitlementPoolUuid = entitlementPoolUuid; - } - - public String getLicenseKeyGroupUuid() { - return licenseKeyGroupUuid; - } - - public void setLicenseKeyGroupUuid(String licenseKeyGroupUuid) { - this.licenseKeyGroupUuid = licenseKeyGroupUuid; - } -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseDataAccessServiceImpl.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseDataAccessServiceImpl.java new file mode 100644 index 000000000..8976d1332 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseDataAccessServiceImpl.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr.impl; + +import javax.sql.rowset.CachedRowSet; + +import org.onap.appc.licmgr.Constants; +import org.onap.appc.licmgr.LicenseDataAccessService; +import org.onap.appc.licmgr.exception.DataAccessException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +import static org.onap.appc.licmgr.Constants.SDC_ARTIFACTS_FIELDS; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + + +@SuppressWarnings("JavaDoc") +public class LicenseDataAccessServiceImpl implements LicenseDataAccessService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(LicenseDataAccessServiceImpl.class); + + public void setSchema(String schema) { + this.schema = schema; + } + + private String schema; + + public void setDbLibService(DbLibService dbLibService) { + this.dbLibService = dbLibService; + } + + private DbLibService dbLibService; + + + /** + * empty constructor + */ + public LicenseDataAccessServiceImpl(){} + + @Override + public Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws + DataAccessException { + + Map result = new HashMap<>(); + if (null == fields || 0 == fields.length) fields = new String[]{SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT.name()}; + + String queryString = buildQueryStatement(); + + ArrayList argList = new ArrayList<>(); + argList.add(vnfType); + argList.add(vnfVersion); + argList.add(Constants.VF_LICENSE); + + try { + + final CachedRowSet data = dbLibService.getData(queryString, argList, Constants.NETCONF_SCHEMA); + + if (data.first()) { + for (String field : fields) { + result.put(field, data.getString(field)); + } + } else { + String msg = "Missing license model for VNF_TYPE: " + vnfType + " and VNF_VERSION: " + vnfVersion + " in table " + Constants.SDC_ARTIFACTS; + logger.info(msg); + } + } catch (SQLException e) { + logger.error("Error Accessing Database " + e); + throw new DataAccessException(e); + } + + return result; + } + + private String buildQueryStatement() { + return "select * " + "from " + Constants.SDC_ARTIFACTS + " " + + "where " + SDC_ARTIFACTS_FIELDS.RESOURCE_NAME.name() + " = ?" + + " AND " + SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.name() + " = ?" + + " AND " + SDC_ARTIFACTS_FIELDS.ARTIFACT_TYPE.name() + " = ?"; + } + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseManagerImpl.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseManagerImpl.java new file mode 100644 index 000000000..422db7f2d --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/onap/appc/licmgr/impl/LicenseManagerImpl.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr.impl; + +import static org.onap.appc.licmgr.Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT; + +import java.util.Map; + +import org.onap.appc.licmgr.LicenseDataAccessService; +import org.onap.appc.licmgr.LicenseManager; +import org.onap.appc.licmgr.exception.DataAccessException; +import org.onap.appc.licmgr.objects.LicenseModel; + + +@SuppressWarnings("all") +public class LicenseManagerImpl implements LicenseManager { + + private LicenseDataAccessService DAService; + + public void setDAService(LicenseDataAccessService daSrv){ + DAService = daSrv; + } + + public LicenseManagerImpl() { + } + + @Override + public LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException { + + LicenseModel licenseModel; + try { + Map resultMap = DAService.retrieveLicenseModelData(vnfType, vnfVersion); + if (resultMap.isEmpty()) { + throw new DataAccessException(String.format("License model not found for vnfType='%s' and vnfVersion='%s'", vnfType, vnfVersion)); + } + String licenseModelXML = resultMap.get(ARTIFACT_CONTENT.name()); + licenseModel = convert(licenseModelXML); // JAXBUtil.toObject(licenseModelXML, VfLicenseModel.class); + } catch (DataAccessException le) { + throw le; + } catch (Exception e) { + throw new DataAccessException(e); + } + return licenseModel; + } + + + private static LicenseModel convert(String xml) { + + LicenseModel licenseModel = new LicenseModel(); + + int posEntitlementStart = xml.indexOf(""); + int posEntitlementEnd = xml.indexOf("", posEntitlementStart); + if (-1 != posEntitlementStart) { + licenseModel.setEntitlementPoolUuid(xml.substring(posEntitlementStart + "".length(), posEntitlementEnd)); + } + + int posLicenseStart = xml.indexOf(""); + int posLicenseEnd = xml.indexOf("", posEntitlementStart); + if (-1 != posLicenseStart) { + licenseModel.setLicenseKeyGroupUuid(xml.substring(posLicenseStart + "".length(), posLicenseEnd)); + } + + return licenseModel; + } + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseDataAccessServiceImpl.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseDataAccessServiceImpl.java deleted file mode 100644 index 8976d1332..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseDataAccessServiceImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr.impl; - -import javax.sql.rowset.CachedRowSet; - -import org.onap.appc.licmgr.Constants; -import org.onap.appc.licmgr.LicenseDataAccessService; -import org.onap.appc.licmgr.exception.DataAccessException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -import static org.onap.appc.licmgr.Constants.SDC_ARTIFACTS_FIELDS; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - - -@SuppressWarnings("JavaDoc") -public class LicenseDataAccessServiceImpl implements LicenseDataAccessService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(LicenseDataAccessServiceImpl.class); - - public void setSchema(String schema) { - this.schema = schema; - } - - private String schema; - - public void setDbLibService(DbLibService dbLibService) { - this.dbLibService = dbLibService; - } - - private DbLibService dbLibService; - - - /** - * empty constructor - */ - public LicenseDataAccessServiceImpl(){} - - @Override - public Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws - DataAccessException { - - Map result = new HashMap<>(); - if (null == fields || 0 == fields.length) fields = new String[]{SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT.name()}; - - String queryString = buildQueryStatement(); - - ArrayList argList = new ArrayList<>(); - argList.add(vnfType); - argList.add(vnfVersion); - argList.add(Constants.VF_LICENSE); - - try { - - final CachedRowSet data = dbLibService.getData(queryString, argList, Constants.NETCONF_SCHEMA); - - if (data.first()) { - for (String field : fields) { - result.put(field, data.getString(field)); - } - } else { - String msg = "Missing license model for VNF_TYPE: " + vnfType + " and VNF_VERSION: " + vnfVersion + " in table " + Constants.SDC_ARTIFACTS; - logger.info(msg); - } - } catch (SQLException e) { - logger.error("Error Accessing Database " + e); - throw new DataAccessException(e); - } - - return result; - } - - private String buildQueryStatement() { - return "select * " + "from " + Constants.SDC_ARTIFACTS + " " + - "where " + SDC_ARTIFACTS_FIELDS.RESOURCE_NAME.name() + " = ?" + - " AND " + SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.name() + " = ?" + - " AND " + SDC_ARTIFACTS_FIELDS.ARTIFACT_TYPE.name() + " = ?"; - } - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseManagerImpl.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseManagerImpl.java deleted file mode 100644 index 422db7f2d..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseManagerImpl.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr.impl; - -import static org.onap.appc.licmgr.Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT; - -import java.util.Map; - -import org.onap.appc.licmgr.LicenseDataAccessService; -import org.onap.appc.licmgr.LicenseManager; -import org.onap.appc.licmgr.exception.DataAccessException; -import org.onap.appc.licmgr.objects.LicenseModel; - - -@SuppressWarnings("all") -public class LicenseManagerImpl implements LicenseManager { - - private LicenseDataAccessService DAService; - - public void setDAService(LicenseDataAccessService daSrv){ - DAService = daSrv; - } - - public LicenseManagerImpl() { - } - - @Override - public LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException { - - LicenseModel licenseModel; - try { - Map resultMap = DAService.retrieveLicenseModelData(vnfType, vnfVersion); - if (resultMap.isEmpty()) { - throw new DataAccessException(String.format("License model not found for vnfType='%s' and vnfVersion='%s'", vnfType, vnfVersion)); - } - String licenseModelXML = resultMap.get(ARTIFACT_CONTENT.name()); - licenseModel = convert(licenseModelXML); // JAXBUtil.toObject(licenseModelXML, VfLicenseModel.class); - } catch (DataAccessException le) { - throw le; - } catch (Exception e) { - throw new DataAccessException(e); - } - return licenseModel; - } - - - private static LicenseModel convert(String xml) { - - LicenseModel licenseModel = new LicenseModel(); - - int posEntitlementStart = xml.indexOf(""); - int posEntitlementEnd = xml.indexOf("", posEntitlementStart); - if (-1 != posEntitlementStart) { - licenseModel.setEntitlementPoolUuid(xml.substring(posEntitlementStart + "".length(), posEntitlementEnd)); - } - - int posLicenseStart = xml.indexOf(""); - int posLicenseEnd = xml.indexOf("", posEntitlementStart); - if (-1 != posLicenseStart) { - licenseModel.setLicenseKeyGroupUuid(xml.substring(posLicenseStart + "".length(), posLicenseEnd)); - } - - return licenseModel; - } - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..f775abb39 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,37 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-LIC-MGR-TEST +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index f775abb39..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,37 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-LIC-MGR-TEST -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerImplTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerImplTest.java new file mode 100644 index 000000000..35c8650d1 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerImplTest.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerMock.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerMock.java new file mode 100644 index 000000000..21323fbef --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerMock.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +import org.onap.appc.licmgr.exception.DataAccessException; +import org.onap.appc.licmgr.objects.LicenseModel; + + +public class LicenseManagerMock implements LicenseManager { + + LicenseModel licenseModel; + @Override + public LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException { + if (vnfType == "VSCP" && vnfVersion == "123"){ + return licenseModel; + } + else { + return null; + } + } + + public void storeLicenseModel(LicenseModel licenseModel){ + this.licenseModel = licenseModel; + + } +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerPluginImplTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerPluginImplTest.java new file mode 100644 index 000000000..35c8650d1 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseManagerPluginImplTest.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseServiceMock.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseServiceMock.java new file mode 100644 index 000000000..a52c463fc --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/LicenseServiceMock.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +import org.onap.appc.licmgr.exception.DataAccessException; +import java.util.HashMap; +import java.util.Map; + +class LicenseServiceMock implements LicenseDataAccessService { + + private String configFile; + private HashMap backupConf; + + @Override + public void setSchema(String schema) { + } + + void setConfigFile(String configFile) { + this.configFile = configFile; + } + + public HashMap getBackupConf() { + return backupConf; + } + + @Override + public Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws DataAccessException { + return null; + } + +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/TestVfLicenseModelConvert.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/TestVfLicenseModelConvert.java new file mode 100644 index 000000000..7bb185b33 --- /dev/null +++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/TestVfLicenseModelConvert.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.licmgr; + +/* +import org.onap.appc.licmgr.objects.VfLicenseModel; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +*/ + +public class TestVfLicenseModelConvert { +/* + public static void main(String args[]) { + + try { + + //create JAXB context + JAXBContext context = JAXBContext.newInstance(VfLicenseModel.class); + + //Create Unmarshaller using JAXB context + Unmarshaller unmarshaller = context.createUnmarshaller(); + + Path xmlPath = Paths.get("src/test/resources/xml/vf-license-model.xml"); + InputStream xmlInputStream = Files.newInputStream(xmlPath); + + VfLicenseModel licenseModel = (VfLicenseModel) unmarshaller.unmarshal(xmlInputStream); + + String vnfId = licenseModel.getVnfId(); + String vendorName = licenseModel.getVendorName(); + + } catch (Exception e) { + e.printStackTrace(); + } + } +*/ +} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerImplTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerImplTest.java deleted file mode 100644 index 35c8650d1..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerImplTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerMock.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerMock.java deleted file mode 100644 index 21323fbef..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerMock.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -import org.onap.appc.licmgr.exception.DataAccessException; -import org.onap.appc.licmgr.objects.LicenseModel; - - -public class LicenseManagerMock implements LicenseManager { - - LicenseModel licenseModel; - @Override - public LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException { - if (vnfType == "VSCP" && vnfVersion == "123"){ - return licenseModel; - } - else { - return null; - } - } - - public void storeLicenseModel(LicenseModel licenseModel){ - this.licenseModel = licenseModel; - - } -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerPluginImplTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerPluginImplTest.java deleted file mode 100644 index 35c8650d1..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerPluginImplTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseServiceMock.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseServiceMock.java deleted file mode 100644 index a52c463fc..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseServiceMock.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -import org.onap.appc.licmgr.exception.DataAccessException; -import java.util.HashMap; -import java.util.Map; - -class LicenseServiceMock implements LicenseDataAccessService { - - private String configFile; - private HashMap backupConf; - - @Override - public void setSchema(String schema) { - } - - void setConfigFile(String configFile) { - this.configFile = configFile; - } - - public HashMap getBackupConf() { - return backupConf; - } - - @Override - public Map retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws DataAccessException { - return null; - } - -} diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/TestVfLicenseModelConvert.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/TestVfLicenseModelConvert.java deleted file mode 100644 index 7bb185b33..000000000 --- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/TestVfLicenseModelConvert.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.licmgr; - -/* -import org.onap.appc.licmgr.objects.VfLicenseModel; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -*/ - -public class TestVfLicenseModelConvert { -/* - public static void main(String args[]) { - - try { - - //create JAXB context - JAXBContext context = JAXBContext.newInstance(VfLicenseModel.class); - - //Create Unmarshaller using JAXB context - Unmarshaller unmarshaller = context.createUnmarshaller(); - - Path xmlPath = Paths.get("src/test/resources/xml/vf-license-model.xml"); - InputStream xmlInputStream = Files.newInputStream(xmlPath); - - VfLicenseModel licenseModel = (VfLicenseModel) unmarshaller.unmarshal(xmlInputStream); - - String vnfId = licenseModel.getVnfId(); - String vendorName = licenseModel.getVendorName(); - - } catch (Exception e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/message/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/message/RequestHandlerMessages.java new file mode 100644 index 000000000..36937a023 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/message/RequestHandlerMessages.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.message; + + +public class RequestHandlerMessages { + public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; + public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/LCMStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/LCMStateManager.java new file mode 100644 index 000000000..3890b1e24 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/LCMStateManager.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +/** + */ +public interface LCMStateManager { + /** + * This method checks if the LCM operations are enabled or not + * * @return true if enabled else false + */ + boolean isLCMOperationEnabled(); + + /** + * This method disables the LCM operations + */ + void disableLCMOperations(); + + /** + * This method disables the LCM operations + */ + void enableLCMOperations(); +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/RequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/RequestHandler.java new file mode 100644 index 000000000..d8aba25b2 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/RequestHandler.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; + +/** + * This class provides application logic for the Request/Response Handler Component. + * + */ +public interface RequestHandler { + /** + * It receives requests from the north-bound REST API (Communication) Layer and + * performs following validations. + * 1. VNF exists in A&AI for the given targetID (VnfID) + * 2. For the current VNF Orchestration Status, the command can be executed + * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database + * If any of the validation fails, it returns appropriate response + * + * @param input RequestHandlerInput object which contains request header and other request parameters like command , target Id , payload etc. + * @return response for request as enum with Return code and message. + */ + RequestHandlerOutput handleRequest(RequestHandlerInput input); + + /** + * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. + * @param vnf_id vnf id or target Id on which updates required + * @param requestIdentifierString - string contains id uniquely represents the request + * @param forceFlag + * @return true in case AAI updates are successful. false for any error or exception. + */ + void onRequestExecutionStart(String vnf_id, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException; + + /** + * This method perform following operations required after execution of workflow. + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * Generate audit logs. + * Adds transaction record to database id if transaction logging is enabled. + * @param runtimeContext RuntimeContext object which contains all parameters from request, response and few parameters from AA&I + * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. + */ + void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated); + + /** + * This method perform following operations required if TTL ends when request still waiting in execution queue . + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * @param runtimeContext RuntimeContext object which contains all parameters from request, response and few parameters from AA&I; + * @param updateAAI boolean flag which indicate AAI upodate status after request completion. + */ + void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI); + + /** + * This method returns the count of in progress requests + * * @return in progress requests count + */ + int getInprogressRequestCount(); +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerInput.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerInput.java new file mode 100644 index 000000000..94d35028b --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerInput.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.objects; + +import org.onap.appc.domainmodel.lcm.RequestContext; + +public class RequestHandlerInput { + + + private RequestContext requestContext; + private String rpcName; + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public RequestContext getRequestContext() { + return requestContext; + } + + public RequestHandlerInput(){ + } + + + public void setRequestContext(RequestContext requestContext) { + this.requestContext = requestContext; + } + + @Override + public String toString() { + return "RequestHandlerInput{" + + "requestContext=" + requestContext + + '}'; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerOutput.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerOutput.java new file mode 100644 index 000000000..16b36b048 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/onap/appc/requesthandler/objects/RequestHandlerOutput.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.objects; + +import org.onap.appc.domainmodel.lcm.ResponseContext; + +public class RequestHandlerOutput { + + private ResponseContext responseContext; + + public RequestHandlerOutput(){ + + } + + public ResponseContext getResponseContext() { + return responseContext; + } + + public void setResponseContext(ResponseContext responseContext) { + this.responseContext = responseContext; + } + + @Override + public String toString() { + return "RequestHandlerOutput{" + + "responseContext=" + responseContext + + '}'; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/message/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/message/RequestHandlerMessages.java deleted file mode 100644 index 36937a023..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/message/RequestHandlerMessages.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.message; - - -public class RequestHandlerMessages { - public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; - public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/LCMStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/LCMStateManager.java deleted file mode 100644 index 3890b1e24..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/LCMStateManager.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -/** - */ -public interface LCMStateManager { - /** - * This method checks if the LCM operations are enabled or not - * * @return true if enabled else false - */ - boolean isLCMOperationEnabled(); - - /** - * This method disables the LCM operations - */ - void disableLCMOperations(); - - /** - * This method disables the LCM operations - */ - void enableLCMOperations(); -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/RequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/RequestHandler.java deleted file mode 100644 index d8aba25b2..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/RequestHandler.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; - -/** - * This class provides application logic for the Request/Response Handler Component. - * - */ -public interface RequestHandler { - /** - * It receives requests from the north-bound REST API (Communication) Layer and - * performs following validations. - * 1. VNF exists in A&AI for the given targetID (VnfID) - * 2. For the current VNF Orchestration Status, the command can be executed - * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database - * If any of the validation fails, it returns appropriate response - * - * @param input RequestHandlerInput object which contains request header and other request parameters like command , target Id , payload etc. - * @return response for request as enum with Return code and message. - */ - RequestHandlerOutput handleRequest(RequestHandlerInput input); - - /** - * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. - * @param vnf_id vnf id or target Id on which updates required - * @param requestIdentifierString - string contains id uniquely represents the request - * @param forceFlag - * @return true in case AAI updates are successful. false for any error or exception. - */ - void onRequestExecutionStart(String vnf_id, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException; - - /** - * This method perform following operations required after execution of workflow. - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * Generate audit logs. - * Adds transaction record to database id if transaction logging is enabled. - * @param runtimeContext RuntimeContext object which contains all parameters from request, response and few parameters from AA&I - * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. - */ - void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated); - - /** - * This method perform following operations required if TTL ends when request still waiting in execution queue . - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * @param runtimeContext RuntimeContext object which contains all parameters from request, response and few parameters from AA&I; - * @param updateAAI boolean flag which indicate AAI upodate status after request completion. - */ - void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI); - - /** - * This method returns the count of in progress requests - * * @return in progress requests count - */ - int getInprogressRequestCount(); -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerInput.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerInput.java deleted file mode 100644 index 94d35028b..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerInput.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.objects; - -import org.onap.appc.domainmodel.lcm.RequestContext; - -public class RequestHandlerInput { - - - private RequestContext requestContext; - private String rpcName; - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public RequestContext getRequestContext() { - return requestContext; - } - - public RequestHandlerInput(){ - } - - - public void setRequestContext(RequestContext requestContext) { - this.requestContext = requestContext; - } - - @Override - public String toString() { - return "RequestHandlerInput{" + - "requestContext=" + requestContext + - '}'; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerOutput.java b/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerOutput.java deleted file mode 100644 index 16b36b048..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-api/src/main/java/org/openecomp/appc/requesthandler/objects/RequestHandlerOutput.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.objects; - -import org.onap.appc.domainmodel.lcm.ResponseContext; - -public class RequestHandlerOutput { - - private ResponseContext responseContext; - - public RequestHandlerOutput(){ - - } - - public ResponseContext getResponseContext() { - return responseContext; - } - - public void setResponseContext(ResponseContext responseContext) { - this.responseContext = responseContext; - } - - @Override - public String toString() { - return "RequestHandlerOutput{" + - "responseContext=" + responseContext + - '}'; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java new file mode 100644 index 000000000..15e8d2436 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.messageadapter; + +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; + +public interface MessageAdapter { + /** + * Initialize dmaapProducer client to post messages using configuration properties + */ + void init(); + + /** + * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP. + * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel). + * @return True if message is postes successfully else False + */ + boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse); + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java new file mode 100644 index 000000000..63a3c00a4 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.messageadapter.impl; + + +import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; +import org.onap.appc.adapter.factory.MessageService; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.requesthandler.conv.Converter; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashSet; +import java.util.Properties; + +public class MessageAdapterImpl implements MessageAdapter{ + + private MessageService messageService; + private Producer producer; + private String partition ; + private Configuration configuration; + private HashSet pool; + private String writeTopic; + private String apiKey; + private String apiSecret; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class); + + /** + * Initialize producer client to post messages using configuration properties + */ + @Override + public void init(){ + this.producer = getProducer(); + } + + private Producer getProducer() { + configuration = ConfigurationFactory.getConfiguration(); + Properties properties=configuration.getProperties(); + updateProperties(properties); + + BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); + } + } + return producer; + } + + + private void updateProperties(Properties props) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props)); + } + pool = new HashSet<>(); + if (props != null) { + // readTopic = props.getProperty("dmaap.topic.read"); + writeTopic = props.getProperty("appc.LCM.topic.write"); + apiKey = props.getProperty("appc.LCM.client.key"); + apiSecret = props.getProperty("appc.LCM.client.secret"); + messageService = MessageService.parse(props.getProperty("message.service.type")); + // READ_TIMEOUT = Integer.valueOf(props.getProperty("dmaap.topic.read.timeout", String.valueOf(READ_TIMEOUT))); + String hostnames = props.getProperty("appc.LCM.poolMembers"); + if (hostnames != null && !hostnames.isEmpty()) { + for (String name : hostnames.split(",")) { + pool.add(name); + } + } + } + } + + /** + * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP. + * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel). + * @return True if message is postes successfully else False + */ + @Override + public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){ + boolean success; + if (logger.isTraceEnabled()) { + logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse)); + } + + String jsonMessage; + try { + jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse); + if (logger.isDebugEnabled()) { + logger.debug("DMaaP Response = " + jsonMessage); + } + success = producer.post(this.partition, jsonMessage); + } catch (JsonProcessingException e1) { + logger.error("Error generating Json from DMaaP message "+ e1.getMessage()); + success= false; + }catch (Exception e){ + logger.error("Error sending message to DMaaP "+e.getMessage()); + success= false; + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")"); + } + return success; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java new file mode 100644 index 000000000..4015181a1 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.constant; + +import java.util.concurrent.TimeUnit; + +public class Constants { + + public static final int DEFAULT_TTL = 30; + public static final String SUCCESS_MSG="SUCCESS"; + public static final String FAILURE_MSG="FAILURE"; + public static final String DEFAULT_LOGGING_FLAG="true"; + public static final long DEFAULT_IDLE_TIMEOUT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java new file mode 100644 index 000000000..5a791711e --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java @@ -0,0 +1,411 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.conv; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.*; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.FlagsBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataContainer; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.requesthandler.impl.DmaapOutgoingMessage; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + + +public class Converter { + public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + public static final String MODE_FLAG = "MODE"; + public static final String FORCE_FLAG = "FORCE"; + public static final String TTL_FLAG = "TTL"; + public final static String DMaaP_ROOT_VALUE = "output"; + private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(Converter.class); + static { + isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + public static Builder convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) { + Builder outObj = null; + if(response == null){ + throw new IllegalArgumentException("empty asyncResponse"); + } + if(vnfOperation == null){ + throw new IllegalArgumentException("empty asyncResponse.action"); + } + Action action = Action.valueOf(vnfOperation.name()); + CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response); + Status status = convAsyncResponseTorev160108Status(response); + Payload payload = convAsyncResponseTorev160108Payload(response); + switch (action){ + case Rollback: + outObj = new RollbackOutputBuilder(); + ((RollbackOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RollbackOutputBuilder)outObj).setStatus(status); + return outObj; + case Snapshot: + outObj = new SnapshotOutputBuilder(); + ((SnapshotOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SnapshotOutputBuilder)outObj).setStatus(status); + try { + ((SnapshotOutputBuilder) outObj).setSnapshotId(response.getAdditionalContext().get("output.snapshot-id")); + } catch (NullPointerException ignored) { + // in case of negative response, snapshotID does not populated, so just ignore NPL + } + return outObj; + case Audit: + outObj = new AuditOutputBuilder(); + ((AuditOutputBuilder)outObj).setCommonHeader(commonHeader); + ((AuditOutputBuilder)outObj).setStatus(status); + ((AuditOutputBuilder)outObj).setPayload(payload); + return outObj; + case HealthCheck: + outObj = new HealthCheckOutputBuilder(); + ((HealthCheckOutputBuilder)outObj).setCommonHeader(commonHeader); + ((HealthCheckOutputBuilder)outObj).setStatus(status); + return outObj; + case LiveUpgrade: + outObj = new LiveUpgradeOutputBuilder(); + ((LiveUpgradeOutputBuilder)outObj).setCommonHeader(commonHeader); + ((LiveUpgradeOutputBuilder)outObj).setStatus(status); + return outObj; + case Lock: + outObj = new LockOutputBuilder(); + ((LockOutputBuilder)outObj).setCommonHeader(commonHeader); + ((LockOutputBuilder)outObj).setStatus(status); + return outObj; + case Configure: + outObj = new ConfigureOutputBuilder(); + ((ConfigureOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigureOutputBuilder)outObj).setStatus(status); + ((ConfigureOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigModify: + outObj = new ConfigModifyOutputBuilder(); + ((ConfigModifyOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigModifyOutputBuilder)outObj).setStatus(status); + ((ConfigModifyOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigScaleOut: + outObj = new ConfigScaleoutOutputBuilder(); + ((ConfigScaleoutOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigScaleoutOutputBuilder)outObj).setStatus(status); + ((ConfigScaleoutOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigRestore: + outObj = new ConfigRestoreOutputBuilder(); + ((ConfigRestoreOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigRestoreOutputBuilder)outObj).setStatus(status); + ((ConfigRestoreOutputBuilder)outObj).setPayload(payload); + return outObj; + case SoftwareUpload: + outObj = new SoftwareUploadOutputBuilder(); + ((SoftwareUploadOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SoftwareUploadOutputBuilder)outObj).setStatus(status); + return outObj; + case Stop: + outObj = new StopOutputBuilder(); + ((StopOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StopOutputBuilder)outObj).setStatus(status); + return outObj; + case Sync: + outObj = new SyncOutputBuilder(); + ((SyncOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SyncOutputBuilder)outObj).setStatus(status); + ((SyncOutputBuilder)outObj).setPayload(payload); + return outObj; + case Terminate: + outObj = new TerminateOutputBuilder(); + ((TerminateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((TerminateOutputBuilder)outObj).setStatus(status); + return outObj; + case Test: + outObj = new TestOutputBuilder(); + ((TestOutputBuilder)outObj).setCommonHeader(commonHeader); + ((TestOutputBuilder)outObj).setStatus(status); + return outObj; + case Unlock: + outObj = new UnlockOutputBuilder(); + ((UnlockOutputBuilder)outObj).setCommonHeader(commonHeader); + ((UnlockOutputBuilder)outObj).setStatus(status); + return outObj; + case Restart: + outObj = new RestartOutputBuilder(); + ((RestartOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RestartOutputBuilder)outObj).setStatus(status); + return outObj; + case Rebuild: + outObj = new RebuildOutputBuilder(); + ((RebuildOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RebuildOutputBuilder)outObj).setStatus(status); + return outObj; + case Migrate: + outObj = new MigrateOutputBuilder(); + ((MigrateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((MigrateOutputBuilder)outObj).setStatus(status); + return outObj; + case Evacuate: + outObj = new EvacuateOutputBuilder(); + ((EvacuateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((EvacuateOutputBuilder)outObj).setStatus(status); + return outObj; + case ConfigBackup: + outObj = new ConfigBackupOutputBuilder(); + ((ConfigBackupOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigBackupOutputBuilder)outObj).setStatus(status); + ((ConfigBackupOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigBackupDelete: + outObj = new ConfigBackupDeleteOutputBuilder(); + ((ConfigBackupDeleteOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigBackupDeleteOutputBuilder)outObj).setStatus(status); + ((ConfigBackupDeleteOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigExport: + outObj = new ConfigExportOutputBuilder(); + ((ConfigExportOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigExportOutputBuilder)outObj).setStatus(status); + return outObj; + case Start: + outObj = new StartOutputBuilder(); + ((StartOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StartOutputBuilder)outObj).setStatus(status); + return outObj; + case StopApplication: + outObj = new StopApplicationOutputBuilder(); + ((StopApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StopApplicationOutputBuilder)outObj).setStatus(status); + return outObj; + case StartApplication: + outObj = new StartApplicationOutputBuilder(); + ((StartApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StartApplicationOutputBuilder)outObj).setStatus(status); + return outObj; + default: + throw new IllegalArgumentException(action+" action is not supported"); + } + } + + public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) { + Payload payload = null; + if(inObj.getPayload() != null) { + payload = new Payload(inObj.getPayload()); + } + return payload; + } + + public static String convPayloadObjectToJsonString(Object inObj) throws ParseException { + String payloadAsString = null; + if(inObj != null) { + + if(inObj instanceof String){ + payloadAsString = (String)inObj; + }else { + try { + ObjectMapper objectMapper = new ObjectMapper(); + payloadAsString = objectMapper.writeValueAsString(inObj); +// payloadAsString = objectMapper.writeValueAsString(payloadAsString); + } catch (JsonProcessingException e) { + String errMsg = "Error serialize payload json to string"; + throw new ParseException(errMsg + "-" + e.toString(), 0); + } + } + } + return payloadAsString; + } + + public static Status convAsyncResponseTorev160108Status(ResponseContext inObj) { + StatusBuilder statusBuilder = new StatusBuilder(); + statusBuilder.setCode(inObj.getStatus().getCode()); + statusBuilder.setMessage(inObj.getStatus().getMessage()); + return statusBuilder.build(); + } + + public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) { + CommonHeader outObj = null; + if(inObj == null){ + throw new IllegalArgumentException("empty asyncResponse"); + } + + CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags = null; + if(inObj.getCommonHeader().getFlags() != null){ + commonHeaderFlags = Converter.convFlagsMapTorev160108Flags(inObj.getCommonHeader().getFlags()); + commonHeaderBuilder.setFlags(commonHeaderFlags); + } + + + commonHeaderBuilder.setApiVer(inObj.getCommonHeader().getApiVer()); + commonHeaderBuilder.setRequestId(inObj.getCommonHeader().getRequestId()); + if(inObj.getCommonHeader().getSubRequestId() != null){ + commonHeaderBuilder.setSubRequestId(inObj.getCommonHeader().getSubRequestId()); + } + + if(inObj.getCommonHeader().getOriginatorId() != null){ + commonHeaderBuilder.setOriginatorId(inObj.getCommonHeader().getOriginatorId()); + } + + if(inObj.getCommonHeader().getTimeStamp() != null){ + String zuluTimestampStr = Converter.convDateToZuluString(Date.from(inObj.getCommonHeader().getTimeStamp())); + ZULU zuluTimestamp = new ZULU(zuluTimestampStr); + commonHeaderBuilder.setTimestamp(zuluTimestamp); + } + outObj = commonHeaderBuilder.build(); + return outObj; + + } + + public static String convDateToZuluString(Date timeStamp) { + return isoFormatter.format(timeStamp); + } + + public static org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags + convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) { + Flags rev160108flags = null; + boolean anyFlag = false; + FlagsBuilder flagsBuilder = new FlagsBuilder(); + /* + * TODO: The below flags are related to APP-C request and should not be sent back - uncomment when response flags are introduced. + */ + /* + if(flags.containsKey(FORCE_FLAG)){ + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force force = + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force.valueOf(flags.get(FORCE_FLAG).toString()); + flagsBuilder.setForce(force); + anyFlag = true; + } + if(flags.containsKey(MODE_FLAG)){ + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode mode = + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode.valueOf(flags.get(MODE_FLAG).toString()); + flagsBuilder.setMode(mode); + anyFlag = true; + } + if(flags.containsKey(TTL_FLAG)){ + flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString())); + anyFlag = true; + } + if(anyFlag){ + rev160108flags = flagsBuilder.build(); + } + */ + + rev160108flags = flagsBuilder.build(); + return rev160108flags; + } + + public static String convAsyncResponseToJsonStringBody(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); + Object message = builder.build(); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.addMixInAnnotations(message.getClass(), MixInFlagsMessage.class); + objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); + objectMapper.addMixInAnnotations(Flags.class, MixIn.class); + objectMapper.addMixInAnnotations(Status.class, MixIn.class); + objectMapper.addMixInAnnotations(Payload.class, MixIn.class); + objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); + +// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) + .writer(SerializationFeature.WRAP_ROOT_VALUE).withRootName(DMaaP_ROOT_VALUE).withoutFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + return writer.writeValueAsString(message); + } + + public static String convAsyncResponseToDmaapOutgoingMessageJsonString(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class); + objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); + objectMapper.addMixInAnnotations(Flags.class, MixIn.class); + objectMapper.addMixInAnnotations(Status.class, MixIn.class); + objectMapper.addMixInAnnotations(Payload.class, MixIn.class); + objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); + +// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true).writer(); + return writer.writeValueAsString(dmaapOutgoingMessage); + } + + public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); + String correlationID = getCorrelationID(asyncResponse); + outObj.setCorrelationID(correlationID); + outObj.setType("response"); + outObj.setRpcName(rpcName); + Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); + Object messageBody = builder.build(); + DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); + outObj.setBody(body); + return outObj; + } + + private static String getCorrelationID(ResponseContext context) { + return context.getCommonHeader().getRequestId() + + (context.getCommonHeader().getSubRequestId() == null ? + "":"-" + context.getCommonHeader().getSubRequestId()); + } + + abstract class MixIn { + @JsonIgnore + abstract Class getImplementedInterface(); // to be removed during serialization + + @JsonValue + abstract java.lang.String getValue(); + } + abstract class MixInCommonHeader extends MixIn { + @JsonProperty("api-ver") + abstract java.lang.String getApiVer(); + @JsonProperty("originator-id") + abstract java.lang.String getOriginatorId(); + @JsonProperty("request-id") + abstract java.lang.String getRequestId(); + @JsonProperty("sub-request-id") + abstract java.lang.String getSubRequestId(); + + } + abstract class MixInFlagsMessage extends MixIn { + @JsonProperty("common-header") + abstract CommonHeader getCommonHeader(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java new file mode 100644 index 000000000..5626cfe6f --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class DGWorkflowNotFoundException extends Exception { + public final String workflowModule; + public final String workflowName; + public final String workflowVersion; + public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion){ + super(message); + this.workflowModule = workflowModule; + this.workflowName = workflowName; + this.workflowVersion = workflowVersion; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java new file mode 100644 index 000000000..b06788a99 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class DuplicateRequestException extends Exception { + public DuplicateRequestException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java new file mode 100644 index 000000000..6e2435559 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class InvalidInputException extends Exception { + public InvalidInputException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java new file mode 100644 index 000000000..ca5f72682 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + +/** + */ +public class LCMOperationsDisabledException extends Exception { + + /** + * Constructs a new exception with the specified detail message. + * + * @param message the detail message. + */ + public LCMOperationsDisabledException(String message) { + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java new file mode 100644 index 000000000..219265084 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + +public class MissingVNFDataInAAIException extends Exception { + String missingAttributeName; + public MissingVNFDataInAAIException(String attributeName) { + this.missingAttributeName = attributeName; + } + + public String getMissingAttributeName() { + return missingAttributeName; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java new file mode 100644 index 000000000..02a130c8b --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class RequestExpiredException extends Exception { + public RequestExpiredException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java new file mode 100644 index 000000000..d1b2759d6 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class VNFNotFoundException extends Exception { + public VNFNotFoundException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java new file mode 100644 index 000000000..85157e32f --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class WorkflowNotFoundException extends Exception { + public final String vnfTypeVersion; + public final String command; + public WorkflowNotFoundException(String message,String vnfTypeVersion,String command){ + super(message); + this.vnfTypeVersion = vnfTypeVersion; + this.command = command; + } + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java new file mode 100644 index 000000000..fd1292ff9 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.helper; + +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * This class serves as Request Registry, which holds the + * request unique parameters (originatorId,requestId,subRequestId) + * in memory. + */ +public class RequestRegistry { + + static Set set = Collections.newSetFromMap(new ConcurrentHashMap()); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestRegistry.class); + public RequestRegistry(){ + + } + + /** + * This method accepts unique request parameters and adds it to Request Registry + * if Registry already contains same parameters it returns false, + * else returns true. + * @param requestIdentifier + * @return + */ + public boolean registerRequest(UniqueRequestIdentifier requestIdentifier){ + + if (logger.isTraceEnabled()) { + logger.trace("Entering to registerRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); + } + boolean output = set.add(requestIdentifier); + logger.debug(" Output = " + output); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from registerRequest with (output = "+ ObjectUtils.toString(output)+")"); + } + return output; + } + + /** + * This method accepts unique request parameters and removes request + * from the Request Registry + * @param requestIdentifier + */ + public void removeRequest(UniqueRequestIdentifier requestIdentifier){ + if (logger.isTraceEnabled()) { + logger.trace("Entering to removeRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); + } + set.remove(requestIdentifier); + } + + /** + * This method returns the count of currently registered requests + * in the request registry + * * @return currently registered requests count + */ + public int getRegisteredRequestCount() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getRegisteredRequestCount"); + } + return set.size(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java new file mode 100644 index 000000000..e45341d3d --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.helper; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; +import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException; +import org.onap.appc.requesthandler.exceptions.RequestExpiredException; +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; + +public interface RequestValidator { + public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java new file mode 100644 index 000000000..8b56dda41 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java @@ -0,0 +1,626 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.requesthandler.constant.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executor.CommandExecutor; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.messageadapter.impl.MessageAdapterImpl; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.publisher.LogPublisher; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.helper.RequestRegistry; +import org.onap.appc.requesthandler.helper.RequestValidator; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.transactionrecorder.objects.TransactionRecord; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.time.Instant; +import java.util.HashMap; +import java.util.Properties; + +import static com.att.eelf.configuration.Configuration.*; + +/** + * This class provides application logic for the Request/Response Handler Component. + * + */ +public abstract class AbstractRequestHandlerImpl implements RequestHandler { + + private RequestValidator requestValidator; + + + + private RequestRegistry requestRegistry; + + private CommandExecutor commandExecutor; + + private TransactionRecorder transactionRecorder; + + private MessageAdapter messageAdapter; + + private static MetricRegistry metricRegistry; + + private boolean isMetricEnabled = false; + + protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class); + + public AbstractRequestHandlerImpl() { + requestRegistry = new RequestRegistry(); + messageAdapter = new MessageAdapterImpl(); + messageAdapter.init(); + Properties properties = configuration.getProperties(); + if (properties != null && properties.getProperty("metric.enabled") != null) { + isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled")); + } + if (isMetricEnabled) { + initMetric(); + } + } + + public void setTransactionRecorder(TransactionRecorder transactionRecorder) { + this.transactionRecorder = transactionRecorder; + } + + public void setRequestValidator(RequestValidator requestValidator) { + this.requestValidator = requestValidator; + } + + public void setMessageAdapter(MessageAdapter messageAdapter) { + this.messageAdapter = messageAdapter; + } + + + + public void setRequestRegistry(RequestRegistry requestRegistry) { + this.requestRegistry = requestRegistry; + } + + public void setCommandExecutor(CommandExecutor commandExecutor) { + this.commandExecutor = commandExecutor; + } + + + /** + * It receives requests from the north-bound REST API (Communication) Layer and + * performs following validations. + * 1. VNF exists in A&AI for the given targetID (VnfID) + * 2. For the current VNF Orchestration Status, the command can be executed + * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database + * If any of the validation fails, it returns appropriate response + * + * @param input RequestHandlerInput object which contains request header and other request parameters like command , target Id , payload etc. + * @return response for request as enum with Return code and message. + */ + @Override + public RequestHandlerOutput handleRequest(RequestHandlerInput input) { + if (logger.isTraceEnabled()) + logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")"); + Params params ; + String vnfId, vnfType = null, errorMessage = null; + Instant startTime = Instant.now(); + RequestHandlerOutput output = null; + setInitialLogProperties(input.getRequestContext()); + + RuntimeContext runtimeContext = new RuntimeContext(); + runtimeContext.setRequestContext(input.getRequestContext()); + runtimeContext.setTimeStart(startTime); + runtimeContext.setRpcName(input.getRpcName()); + + final ResponseContext responseContext = new ResponseContext(); + responseContext.setStatus(new Status(0,"")); + responseContext.setAdditionalContext(new HashMap<>(4)); + responseContext.setCommonHeader(input.getRequestContext().getCommonHeader()); + runtimeContext.setResponseContext(responseContext); + runtimeContext.getResponseContext().setStatus(new Status(0,"")); + + vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + try { + + requestValidator.validateRequest(runtimeContext); + + handleRequest(runtimeContext); + + final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); + if (statusCode % 100 == 2 || statusCode % 100 == 3) { + createTransactionRecord(runtimeContext); + } + output = new RequestHandlerOutput(); + output.setResponseContext(runtimeContext.getResponseContext()); + + } catch (VNFNotFoundException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId); + storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage); + params = new Params().addParam("vnfId", vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params); + } catch (NoTransitionDefinedException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name()); + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); + output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.STATE_MACHINE, + logMessage); + } catch (LifecycleException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); + output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params); + } catch (UnstableVNFException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("vnfId", vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params); + } catch (WorkflowNotFoundException e) { + errorMessage = e.getMessage(); + String vnfTypeVersion = e.vnfTypeVersion; + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion); + output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params); + } catch (DGWorkflowNotFoundException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name()); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + logMessage); + params = new Params().addParam("actionName", input.getRequestContext().getAction().name()) + .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion); + output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params); + } catch (RequestExpiredException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("actionName", input.getRequestContext().getAction().name()); + output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params); + } catch (InvalidInputException e) { + errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params); + } catch (DuplicateRequestException e) { + errorMessage = e.getMessage(); + output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null); + } catch (MissingVNFDataInAAIException e) { + params = new Params().addParam("attributeName",e.getMissingAttributeName()) + .addParam("vnfId",vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params); + errorMessage = output.getResponseContext().getStatus().getMessage(); + } catch (LCMOperationsDisabledException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params); + } catch (Exception e) { + storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage()); + errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params); + } finally { + try { + if (logger.isDebugEnabled() && errorMessage != null) + logger.debug("error occurred in handleRequest " + errorMessage); + logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())); + logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())); + + runtimeContext.setResponseContext(output.getResponseContext()); + if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) { + if (isMetricEnabled) { + if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); + }else { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest(); + } + } + removeRequestFromRegistry(input.getRequestContext().getCommonHeader()); + } + } finally { + storeAuditLogRecord(runtimeContext); + storeMetricLogRecord(runtimeContext); + clearRequestLogProperties(); + } + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")"); + } + return output; + } + + protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) { + LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ? + String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "", + runtimeContext.getResponseContext().getStatus() != null ? + String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "", + targetEntity, + targetServiceName, + additionalMessage, + this.getClass().getCanonicalName()); + } + + private void createTransactionRecord(RuntimeContext runtimeContext) { + TransactionRecord transactionRecord = new TransactionRecord(); + transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp()); + transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId()); + transactionRecord.setStartTime(runtimeContext.getTimeStart()); + transactionRecord.setEndTime(Instant.now()); + transactionRecord.setTargetID(runtimeContext.getVnfContext().getId()); + transactionRecord.setTargetType(runtimeContext.getVnfContext().getType()); + transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name()); + transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode())); + transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage()); + transactionRecorder.store(transactionRecord); + } + + protected abstract void handleRequest(RuntimeContext runtimeContext) ; + + protected void callWfOperation(RuntimeContext runtimeContext) { + int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader()); + if (remainingTTL > 0) { + if (logger.isDebugEnabled()) { + logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL); + } + + RuntimeContext clonedContext = cloneContext(runtimeContext); + + try { + commandExecutor.executeCommand(clonedContext); + if(logger.isTraceEnabled()) { + logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId())); + } + fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null); + if (isMetricEnabled) { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); + } + } catch (APPCException e) { + String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + Params params = new Params().addParam("errorMsg", errorMessage); + fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params); + } + + } else { + fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.REQUEST_HANDLER, + EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST, + runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(), + runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(), + String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl()))); + } + } + + protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) { + runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params))); + } + + /* + * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted + * status code and other - depending on DG status). Other properties should not be a problem + */ + private RuntimeContext cloneContext(RuntimeContext runtimeContext) { + RuntimeContext other = new RuntimeContext(); + other.setRequestContext(runtimeContext.getRequestContext()); + other.setResponseContext(new ResponseContext()); + other.getResponseContext().setStatus(new Status(0,"")); + other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader()); + other.setVnfContext(runtimeContext.getVnfContext()); + other.setRpcName(runtimeContext.getRpcName()); + other.setTimeStart(runtimeContext.getTimeStart()); + other.setIsLockAcquired(runtimeContext.isLockAcquired()); + return other; + } + + + private void clearRequestLogProperties() { + try { + MDC.remove(MDC_KEY_REQUEST_ID); + MDC.remove(MDC_SERVICE_INSTANCE_ID); + MDC.remove(MDC_SERVICE_NAME); + MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); + MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY); + } catch (Exception e) { + //do nothing + } + } + + private void removeRequestFromRegistry(CommonHeader commonHeader) { + if (logger.isTraceEnabled()) + logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader)); + requestRegistry.removeRequest( + new UniqueRequestIdentifier(commonHeader.getOriginatorId(), + commonHeader.getRequestId(), + commonHeader.getSubRequestId())); + } + + + private void setInitialLogProperties(RequestContext requestContext) { + + try { + MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId()); + if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) { + MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId()); + } + MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId()); + MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong! + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name()); + MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId()); + + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } catch (RuntimeException e) { + //ignore + } + } + + + private int calculateRemainingTTL(CommonHeader commonHeader) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader)); + } + long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().toEpochMilli()); + logger.debug("usedTimeInMillis = " + usedTimeInMillis); + int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000); + logger.debug("usedTimeInSeconds = " + usedTimeInSeconds); + Integer inputTTL = this.getInputTTL(commonHeader); + logger.debug("inputTTL = " + inputTTL); + Integer remainingTTL = inputTTL - usedTimeInSeconds; + logger.debug("Remaining TTL = " + remainingTTL); + if (logger.isTraceEnabled()) + logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")"); + return remainingTTL; + } + + private Integer getInputTTL(CommonHeader header) { + if (logger.isTraceEnabled()) + logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header)); + if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) { + String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); + Integer defaultTTL = Integer.parseInt(defaultTTLStr); + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")"); + return defaultTTL; + } + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")"); + + return header.getFlags().getTtl(); + } + + private boolean isValidTTL(String ttl) { + if (ttl == null || ttl.length() == 0) { + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (result = false)"); + return false; + } + try { + Integer i = Integer.parseInt(ttl); + return (i > 0); + } catch (NumberFormatException e) { + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (result = false)"); + return false; + } + } + + private Boolean isLoggingEnabled() { + String defaultFlagStr = configuration.getProperty("org.onap.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG)); + return Boolean.parseBoolean(defaultFlagStr); + } + + private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) { + RequestHandlerOutput output = new RequestHandlerOutput(); + ResponseContext responseContext = new ResponseContext(); + org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params)); + responseContext.setStatus(status); + output.setResponseContext(responseContext); + return output; + } + + /** + * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. + * + * @param vnfId String of VNF ID + * @param readOnlyActivity boolean indicator + * @param requestIdentifierString - string contains id uniquely represents the request + * @param forceFlag boolean indicator + * @throws UnstableVNFException when failed + */ + @Override + public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ; + + /** + * This method perform following operations required after execution of workflow. + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * Generate audit logs. + * Adds transaction record to database id if transaction logging is enabled. + * + * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. + */ + @Override + public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext)); + } + + postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); + requestRegistry.removeRequest( + new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); + + storeAuditLogRecord(runtimeContext); + if (isLoggingEnabled()) { + createTransactionRecord(runtimeContext); + } + } + + private void storeAuditLogRecord(RuntimeContext runtimeContext) { + LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(), + Instant.now(), + String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()), + runtimeContext.getResponseContext().getStatus().getMessage(), + this.getClass().getCanonicalName()); + } + + private void storeMetricLogRecord(RuntimeContext runtimeContext) { + LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(), + Instant.now(), + LoggingConstants.TargetNames.APPC, + runtimeContext.getRequestContext().getAction().name(), + runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode() ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR, + String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()), + runtimeContext.getResponseContext().getStatus().getMessage(), + this.getClass().getCanonicalName()); + } + + + + + private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext)); + } + boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext); + if (!callbackResponse) { + logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext); + } + if (logger.isTraceEnabled()) + logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")"); + } + + /** + * This method perform following operations required if TTL ends when request still waiting in execution queue . + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * + * @param runtimeContext AsyncResponse object which contains VNF Id , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId; + * @param updateAAI boolean flag which indicate AAI upodate status after request completion. + */ + @Override + public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestTTLEnd with " + + "AsyncResponse = " + ObjectUtils.toString(runtimeContext) + + ", updateAAI = " + ObjectUtils.toString(updateAAI)); + } + logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage()); + fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null); + postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); + + requestRegistry.removeRequest( + new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); + } + + private void initMetric() { + if (logger.isDebugEnabled()) + logger.debug("Metric getting initialized"); + MetricService metricService = getMetricservice(); + metricRegistry = metricService.createRegistry("APPC"); + DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory(). + dispatchingFunctionCounterBuilder(). + withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER). + withAcceptRequestValue(0) + .withRejectRequestValue(0) + .build(); + if (metricRegistry.register(dispatchingFuntionMetric)) { + Metric[] metrics = new Metric[]{dispatchingFuntionMetric}; + LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); + LogPublisher[] logPublishers = new LogPublisher[1]; + logPublishers[0] = logPublisher; + PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). + scheduledPolicyBuilder().withPublishers(logPublishers). + withMetrics(metrics). + build(); + if (logger.isDebugEnabled()) + logger.debug("Policy getting initialized"); + manuallyScheduledPublishingPolicy.init(); + if (logger.isDebugEnabled()) + logger.debug("Metric initialized"); + } + } + + + private MetricService getMetricservice() { + BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); + if (sref != null) { + logger.info("Metric Service from bundlecontext"); + return (MetricService) bctx.getService(sref); + } else { + logger.info("Metric Service error from bundlecontext"); + logger.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); + return null; + } + } + + /** + * This method returns the count of in progress requests + * * @return in progress requests count + */ + @Override + public int getInprogressRequestCount() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getInprogressRequestCount"); + } + return requestRegistry.getRegisteredRequestCount(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java new file mode 100644 index 000000000..4f4942b8a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java @@ -0,0 +1,328 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.appc.requesthandler.constant.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.helper.RequestRegistry; +import org.onap.appc.requesthandler.helper.RequestValidator; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.time.Instant; +import java.util.Calendar; +import java.util.Date; + +public abstract class AbstractRequestValidatorImpl implements RequestValidator { + + protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class); + private final Configuration configuration = ConfigurationFactory.getConfiguration(); + protected LifecycleManager lifecyclemanager; + protected LCMStateManager lcmStateManager; + private AAIService aaiService; + private WorkFlowManager workflowManager; + private RequestRegistry requestRegistry = new RequestRegistry(); + + protected static Calendar DateToCalendar(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal; + } + + public void setWorkflowManager(WorkFlowManager workflowManager) { + this.workflowManager = workflowManager; + } + + public void setLcmStateManager(LCMStateManager lcmStateManager) { + this.lcmStateManager = lcmStateManager; + } + + public void setRequestRegistry(RequestRegistry requestRegistry) { + this.requestRegistry = requestRegistry; + } + + public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; + + private boolean isValidTTL(String ttl) { + if (logger.isTraceEnabled()){ + logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl)); + } + if (ttl == null || ttl.length() == 0) { + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")"); + } + return false; + } + try { + Integer i = Integer.parseInt(ttl); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")"); + } + return (i > 0); + } catch (NumberFormatException e) { + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")"); + } + return false; + } + } + + protected void getAAIservice() { + BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); + // Get AAIadapter reference + ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); + if (sref != null) { + logger.info("AAIService from bundlecontext"); + aaiService = (AAIService) bctx.getService(sref); + + } else { + logger.info("AAIService error from bundlecontext"); + logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); + + } + } + + protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx = getVnfdata(vnfId, "vnf", ctx); + + VNFContext vnfContext = new VNFContext(); + populateVnfContext(vnfContext, ctx); + + return vnfContext; + } + + protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { + + checkWorkflowExists(vnfContext, requestContext); + } + + private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { + + WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext)); + if (!workflowExistsOutput.isMappingExist()) { + if (logger.isDebugEnabled()) { + logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()); + } + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), + this.getClass().getCanonicalName()); + + + throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name()); + } + if (!workflowExistsOutput.isDgExist()) { + if (logger.isDebugEnabled()) { + logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput); + } + + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), + this.getClass().getCanonicalName()); + + + throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(), + workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion()); + } + } + + private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException { + String vnfType = ctx.getAttribute("vnf.vnf-type"); + String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status"); + if(StringUtils.isEmpty(vnfType)){ + throw new MissingVNFDataInAAIException("vnf-type"); + } + else if(StringUtils.isEmpty(orchestrationStatus)){ + throw new MissingVNFDataInAAIException("orchestration-status"); + } + vnfContext.setType(vnfType); + vnfContext.setStatus(orchestrationStatus); + vnfContext.setId(ctx.getAttribute("vnf.vnf-id")); + } + + private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) { + + WorkflowRequest workflowRequest = new WorkflowRequest(); + workflowRequest.setVnfContext(vnfContext); + workflowRequest.setRequestContext(requestContext); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")"); + } + return workflowRequest; + } + + protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header)); + } + + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId()); + boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier); + if (!requestAccepted) { + if (logger.isDebugEnabled()) { + logger.debug("Duplicate Request with " + requestIdentifier); + } + throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier); + } + } + + protected Integer readTTL(CommonHeader header) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header)); + } + if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) { + String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); + return Integer.parseInt(defaultTTLStr); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from readTTL with (TTL = "+ ObjectUtils.toString(header.getFlags().getTtl())+")"); + } + return header.getFlags().getTtl(); + } + + private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx)); + } + + String key = "vnf-id = '" + vnf_id + "'"; + logger.debug("inside getVnfdata=== " + key); + try { + Instant beginTimestamp = Instant.now(); + SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx); + Instant endTimestamp = Instant.now(); + String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR; + LoggingUtils.logMetricsMessage( + beginTimestamp, + endTimestamp, + LoggingConstants.TargetNames.AAI, + LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY, + status, + "", + response.name(), + this.getClass().getCanonicalName()); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id); + } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id); + } + logger.info("AAIResponse: " + response.toString()); + } catch (SvcLogicException e) { + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA, + "Error in getVnfdata" + e, + this.getClass().getCanonicalName()); + + throw new RuntimeException(e); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")"); + } + return ctx; + } + + protected void validateInput(RequestContext requestContext) + throws RequestExpiredException, InvalidInputException, DuplicateRequestException { + if (logger.isTraceEnabled()){ + logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext)); + } + if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null + || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 || + null == requestContext.getCommonHeader().getApiVer()) { + if (logger.isDebugEnabled()) { + logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name()); + } + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.APPC_INVALID_INPUT), + this.getClass().getCanonicalName()); + + throw new InvalidInputException("vnfID or command is null"); + } + CommonHeader commonHeader = requestContext.getCommonHeader(); + + checkForDuplicateRequest(commonHeader); + + Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp())); + Calendar currentTime = Calendar.getInstance(); + + // If input timestamp is of future, we reject the request + if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) { + if (logger.isDebugEnabled()) { + logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime()); + } + throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime()); + } + Integer ttl = readTTL(commonHeader); + logger.debug("TTL value set to (seconds) : " + ttl); + inputTimeStamp.add(Calendar.SECOND, ttl); + if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) { + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl, + this.getClass().getCanonicalName()); + + throw new RequestExpiredException("TTL Expired"); + } + if (logger.isDebugEnabled()) { + logger.debug("Validation of the request is successful"); + } + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java new file mode 100644 index 000000000..0df57a754 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * This class represents a message being sent out to DMaaP by APPC as async response. + * note the structure of this class must be adapted to the sync message sent to DMaaP represened in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapOutgoingMessage { + + @JsonProperty("version") + private String version; + + @JsonProperty("type") + private String type; + + @JsonProperty("correlation-id") + private String correlationID; + + private final static String defaultCambriaPartition = "MSO"; + @JsonProperty("cambria.partition") + private String cambriaPartition = defaultCambriaPartition; + + @JsonProperty("rpc-name") + private String rpcName; + + @JsonProperty("body") + private Body body; + + public DmaapOutgoingMessage() { + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCorrelationID() { + return correlationID; + } + + public void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + public String getCambriaPartition() { + return cambriaPartition; + } + + public void setCambriaPartition(String cambriaPartition) { + this.cambriaPartition = cambriaPartition; + } + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public Body getBody() { + return body; + } + + public void setBody(Body body) { + this.body = body; + } + + @Override + public String toString() { + return "DmaapOutgoingMessage{" + + "cambriaPartition='" + cambriaPartition + '\'' + + ", rpcName='" + rpcName + '\'' + + ", body=" + body + + '}'; + } + + @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Body { + public Body() { + } + + public Body(Object output) { + this.output = output; + } + + @JsonProperty("output") + private Object output; + + public Object getOutput() { + return output; + } + + public void setOutput(Object body) { + this.output = body; + } + + @Override + public String toString() { + return "Body{" + + "output=" + output + + '}'; + } + } +} + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java new file mode 100644 index 000000000..276eaddab --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.onap.appc.requesthandler.LCMStateManager; + +public class LCMStateManagerImpl implements LCMStateManager { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class); + private static AtomicBoolean isLCMEnabled = new AtomicBoolean(true); + + /** + * This method checks if the LCM operations are enabled or not + * * @return true if enabled else false + */ + public boolean isLCMOperationEnabled() { + return isLCMEnabled.get(); + } + + /** + * This method disables the LCM operations + */ + public void disableLCMOperations() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to disableLCMOperations"); + } + isLCMEnabled.set(false); + } + + /** + * This method enables the LCM operations + */ + public void enableLCMOperations() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to enableLCMOperations"); + } + isLCMEnabled.set(true); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java new file mode 100644 index 000000000..1f07b277c --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.appc.requesthandler.constant.Constants; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; + +/** + * This class provides application logic for the Request/Response Handler Component. + * + */ +public class RequestHandlerImpl extends AbstractRequestHandlerImpl { + + /** + * APP-C VNF lock idle timeout in milliseconds. Applied only when locking VNF using northbound API "lock" + */ + private static final String PROP_IDLE_TIMEOUT = "org.onap.appc.lock.idleTimeout"; + + private LockManager lockManager; + + private WorkingStateManager workingStateManager; + + public void setLockManager(LockManager lockManager) { + this.lockManager = lockManager; + } + + public void setWorkingStateManager(WorkingStateManager workingStateManager) { + this.workingStateManager = workingStateManager; + } + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class); + + protected void handleRequest(RuntimeContext runtimeContext) { + + switch (runtimeContext.getRequestContext().getAction()) { + case Lock: + try { + lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); + } catch (LockException e) { + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.LOCK_MANAGER, + EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); + } + break; + + case Unlock: + try { + releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); + } catch (LockException e) { + //TODO add proper error code and message + // logger.error(EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + } + break; + + case CheckLock: + boolean isLocked = lockManager.isLocked(runtimeContext.getVnfContext().getId()); + fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); + runtimeContext.getResponseContext().addKeyValueToAdditionalContext("locked", String.valueOf(isLocked).toUpperCase()); + break; + default: + try { + boolean lockAcquired = acquireVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), 0); + runtimeContext.setIsLockAcquired(lockAcquired); + callWfOperation(runtimeContext); + } catch (LockException e) { + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + } finally { + if (runtimeContext.isLockAcquired()) { + final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); + if (statusCode % 100 == 2 || statusCode % 100 == 3) { + try { + releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + } catch (LockException e) { + logger.error("Error releasing the lock",e); + } + } + } + } + } + } + + private void releaseVNFLock(String vnfId, String transactionId) throws LockException { + lockManager.releaseLock(vnfId, transactionId); + logger.info("Lock released for vnfID = " + vnfId); + } + + protected void lockWithTimeout(String vnfId, String requestId) throws LockException { + long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT); + acquireVNFLock(vnfId, requestId, timeout); + } + + private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException { + if (logger.isTraceEnabled()) + logger.trace("Entering to acquireVNFLock with vnfID = " + vnfID); + boolean lockAcquired = lockManager.acquireLock(vnfID, requestId, timeout); + if (lockAcquired) { + logger.info("Lock acquired for vnfID = " + vnfID); + } else { + logger.info("vnfID = " + vnfID + " was already locked"); + } + return lockAcquired; + } + + /** + * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. + * + * @param vnfId String of VNF ID + * @param readOnlyActivity boolean indicator + * @param requestIdentifierString - string contains id uniquely represents the request + * @param forceFlag boolean indicator + * @throws UnstableVNFException when failed + */ + @Override + public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestExecutionStart with vnfId = " + vnfId + "and requestIdentifierString = " + requestIdentifierString); + } + + if(!readOnlyActivity || !forceFlag || workingStateManager.isVNFStable(vnfId)) { + boolean updated = false; + try { + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, requestIdentifierString, forceFlag); + } catch (Exception e) { + logger.error("Error updating working state for vnf " + vnfId + e); + throw new RuntimeException(e); + } + if (!updated) { + throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); + } + } + + if (logger.isTraceEnabled()) + logger.trace("Exiting from onRequestExecutionStart "); + } + + private boolean isReadOnlyAction(VNFOperation action) { + if (VNFOperation.Sync.toString().equals(action) || + VNFOperation.Audit.toString().equals(action) || + VNFOperation.ConfigBackup.toString().equals(action) || + VNFOperation.ConfigBackupDelete.toString().equals(action) || + VNFOperation.ConfigExport.toString().equals(action)){ + return true; + } + return false; + } + + @Override + public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { + super.onRequestExecutionEnd(runtimeContext,isAAIUpdated); + VNFWorkingState workingState; + Status status = runtimeContext.getResponseContext().getStatus(); + if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) { + workingState = VNFWorkingState.STABLE; + } else { + workingState = VNFWorkingState.UNKNOWN; + } + + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()); + + String requestIdentifierString = requestIdentifier.toIdentifierString(); + workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false); + logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId()); + resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); + } + + private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) { + if (lockAcquired) { + try { + releaseVNFLock(vnfId, requestId); + } catch (LockException e) { + logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); + } + } else if (resetLockTimeout) { + try { + // reset timeout to previous value + lockWithTimeout(vnfId, requestId); + } catch (LockException e) { + logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); + } + } + } + + @Override + public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { + super.onRequestTTLEnd(runtimeContext,updateAAI); + resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java new file mode 100644 index 000000000..8724adc59 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.workingstatemanager.WorkingStateManager; + + +public class RequestValidatorImpl extends AbstractRequestValidatorImpl { + + private WorkingStateManager workingStateManager; + private LCMStateManager lcmStateManager; + + public void setLifecyclemanager(LifecycleManager lifecyclemanager) { + this.lifecyclemanager = lifecyclemanager; + } + + public void setWorkingStateManager(WorkingStateManager workingStateManager) { + this.workingStateManager = workingStateManager; + } + + public void setLcmStateManager(LCMStateManager lcmStateManager) { + this.lcmStateManager = lcmStateManager; + } + + public RequestValidatorImpl() { + } + + @Override + public void validateRequest(RuntimeContext runtimeContext) + throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, + DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, + DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + if (logger.isTraceEnabled()){ + logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext)); + } + if(!lcmStateManager.isLCMOperationEnabled()) { + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), + this.getClass().getCanonicalName()); + throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); + } + + getAAIservice(); + validateInput(runtimeContext.getRequestContext()); + checkVNFWorkingState(runtimeContext); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + VNFContext vnfContext = queryAAI(vnfId); + runtimeContext.setVnfContext(vnfContext); + + queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction()); + VNFOperation operation = runtimeContext.getRequestContext().getAction(); + if(!operation.isBuiltIn()) { + // for built-in operations skip WF presence check + queryWFM(vnfContext, runtimeContext.getRequestContext()); + } + } + + + private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to queryLCM with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+ + ", command = "+ ObjectUtils.toString(action)); + } + + String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name()); + if (logger.isDebugEnabled()) { + logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")"); + } + return nextState; + } + + + private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext())); + } + boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce(); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + if (logger.isDebugEnabled()) { + logger.debug("forceFlag = " + forceFlag); + } + boolean isVNFStable = workingStateManager.isVNFStable(vnfId); + if (!isVNFStable && !forceFlag) { + if (logger.isDebugEnabled()) { + logger.debug("VNF is not stable for VNF ID = " + vnfId); + } + throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); + } + + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java new file mode 100644 index 000000000..7e3917313 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; + +public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{ + + protected void handleRequest(RuntimeContext runtimeContext) { + runtimeContext.setIsLockAcquired(false); + callWfOperation(runtimeContext); + } + + @Override + public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { + + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java new file mode 100644 index 000000000..79f83fbc6 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.i18n.Msg; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.exceptions.*; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl { + + @Override + public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException { + if(!lcmStateManager.isLCMOperationEnabled()) { + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), + this.getClass().getCanonicalName()); + throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); + } + + getAAIservice(); + super.validateInput(runtimeContext.getRequestContext()); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + VNFContext vnfContext = queryAAI(vnfId); + runtimeContext.setVnfContext(vnfContext); + + VNFOperation operation = runtimeContext.getRequestContext().getAction(); + if(supportedVMLevelAction().contains(operation)) { + queryWFM(vnfContext, runtimeContext.getRequestContext()); + } + else{ + throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level"); + } + } + + public Set supportedVMLevelAction(){ + Set vnfOperations = new HashSet<>(); + vnfOperations.add(VNFOperation.Start); + vnfOperations.add(VNFOperation.Stop); + vnfOperations.add(VNFOperation.Restart); + vnfOperations.add(VNFOperation.Rebuild); + vnfOperations.add(VNFOperation.Terminate); + vnfOperations.add(VNFOperation.Migrate); + vnfOperations.add(VNFOperation.Evacuate); + vnfOperations.add(VNFOperation.Snapshot); + return vnfOperations; + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java new file mode 100644 index 000000000..e9b3d0f3a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager; + +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; + + +public interface WorkingStateManager { + + /** + * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. + * @param vnfId vnf Id to be verified for stable state + * @return True if vnf Exists and state is STABLE else False. + */ + public boolean isVNFStable(String vnfId); + + /** + * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or + * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. + * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. + * @param vnfId vnf Id to be updated + * @param workingState new working state + * @param ownerId + * @param forceFlag - force to update also on case given onwerId is different then the registered one + */ + public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag); + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java new file mode 100644 index 000000000..041cf7e84 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + +import java.sql.Connection; + +import org.onap.appc.dao.util.JdbcConnectionFactory; +import org.onap.appc.workingstatemanager.WorkingStateManager; + +public abstract class JdbcWorkingStateManager implements WorkingStateManager { + + private JdbcConnectionFactory connectionFactory; + + public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } + + protected Connection openDbConnection() { + return connectionFactory.openDbConnection(); + } + + protected void closeDbConnection(Connection connection) { + connectionFactory.closeDbConnection(connection); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java new file mode 100644 index 000000000..206d57229 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + + +public class RequestHandlerMessages { + public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; + public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java new file mode 100644 index 000000000..e2fb3f298 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.message.RequestHandlerMessages; +import org.onap.appc.util.MessageFormatter; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import org.onap.appc.workingstatemanager.objects.VnfWorkingStateDto; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang3.StringUtils; + + +public class WorkingStateManagerImpl extends JdbcWorkingStateManager { + + private static final String SQL_RETRIEVE_VNF_STATE_MANAGEMENT = "SELECT VNF_ID,STATE,OWNER_ID,UPDATED,VER FROM VNF_STATE_MANAGEMENT WHERE VNF_ID=?"; + private static final String SQL_INSERT_VNF_STATE_MANAGEMENT = "INSERT IGNORE INTO VNF_STATE_MANAGEMENT (VNF_ID,STATE,OWNER_ID,UPDATED,VER) VALUES (?, ?, ?, ?, ?)"; + private static final String SQL_UPDATE_VNF_STATE_MANAGEMENT = "UPDATE VNF_STATE_MANAGEMENT SET OWNER_ID=?, UPDATED=?, STATE=?, VER=? WHERE VNF_ID=? AND VER=?"; + private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; + private static int maxAttempts = ConfigurationFactory.getConfiguration().getIntegerProperty("org.onap.appc.workingstatemanager.maxAttempts",20); + + private static Map workingStateMap = new ConcurrentHashMap<>(); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkingStateManagerImpl.class); + + + /** + * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. + * @param vnfId vnf Id to be verified for stable state + * @return True if vnf Exists and state is STABLE else False. + */ + @Override + public boolean isVNFStable(String vnfId){ + if (logger.isTraceEnabled()) { + logger.trace("Entering to isVNFStable with vnfId = "+ vnfId); + } + Connection connection = null; + boolean vnfStable = false; + try { + connection = openDbConnection(); + VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); + vnfStable = isVNFStable(vnfWorkingStateDto); + } catch (SQLException e) { + String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); + throw new RuntimeException(errMsg); + } finally { + if(connection != null) { + closeDbConnection(connection); + } + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isVNFStable for vnfId = "+ vnfId+" with Result = "+vnfStable); + } + return vnfStable; + } + + /** + * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or + * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. + * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. + * @param vnfId vnf Id to be updated + * @param workingState new working state + * @param ownerId + * @param forceFlag - force to update also on case given onwerId is different then the registered one + */ + @Override + public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag){ + boolean updated = false; + if (logger.isTraceEnabled()) { + logger.trace("Entering to setWorkingState with vnfId = "+ ObjectUtils.toString(vnfId)+ ", VNFWorkingState = " + workingState.name() + ", ownerId = "+ownerId+", forceFlag = "+forceFlag); + } + Connection connection = null; + try { + connection = openDbConnection(); + updated = setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag, maxAttempts); + } catch (SQLException e) { + String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); + throw new RuntimeException(errMsg); + } finally { + if(connection != null) { + closeDbConnection(connection); + } + } + + logger.trace("setWorkingState exit with output updated = "+updated); + return updated; + } + + public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag, int maxAttempts) throws SQLException { + return setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,1,maxAttempts); + } + public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag,int attempt, int maxAttempts) throws SQLException { + boolean updated = false; + VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); + Long currentVersion = vnfWorkingStateDto != null ? vnfWorkingStateDto.getVer() : null; + if(forceFlag || isVNFStable(vnfWorkingStateDto) || + ( vnfWorkingStateDto != null && vnfWorkingStateDto.getOwnerId().equals(ownerId)) ) { + updated = storeWorkingStateIfSameVersion(connection, vnfId, workingState, ownerId, currentVersion); + + Params params = new Params().addParam("vnfId", vnfId).addParam("workingState",workingState.name()) + .addParam("attempt",attempt).addParam("maxAttempts",maxAttempts).addParam("ownerId",ownerId).addParam("forceFlag",forceFlag); + String logMessage; + if(updated) { + logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_UPDATED, params.getParams()); + }else { + logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_WAS_NOT_UPDATED, params.getParams()); + } + logger.debug(logMessage); + if(!updated && attempt= Long.MAX_VALUE) ? 1 : (currentVer + 1); + statement.setString(1, ownerId); + statement.setLong(2, getCurrentTime(connection)); + statement.setString(3, state); + statement.setLong(4, newVer); + statement.setString(5, vnfId); + statement.setLong(6, currentVer); + return (statement.executeUpdate() != 0); + } + } + + protected VnfWorkingStateDto retrieveVnfWorkingState(Connection connection, String vnfId) throws SQLException { + VnfWorkingStateDto res = null; + + try(PreparedStatement statement = connection.prepareStatement(SQL_RETRIEVE_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER + statement.setString(1, vnfId); + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = new VnfWorkingStateDto(vnfId); + String stateString = resultSet.getString(2); + VNFWorkingState vnfWorkingState = VNFWorkingState.valueOf(stateString); + res.setState(vnfWorkingState); + res.setOwnerId(resultSet.getString(3)); + res.setUpdated(resultSet.getLong(4)); + res.setVer(resultSet.getLong(5)); + } + } + } + return res; + } + + private long getCurrentTime(Connection connection) throws SQLException { + long res = -1; + if(connection != null) { + try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = resultSet.getTimestamp(1).getTime(); + } + } + } + } + if(res == -1) { + res = System.currentTimeMillis(); + } + return res; + } + + protected boolean addVnfWorkingStateIfNotExists(Connection connection, String vnfId, String ownerId, String state) throws SQLException { + boolean added = false; + try(PreparedStatement statement = connection.prepareStatement(SQL_INSERT_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER + statement.setString(1, vnfId); + statement.setString(2, state); + statement.setString(3, ownerId); + statement.setLong(4, getCurrentTime(connection)); + statement.setLong(5, 1L); + int rowCount = statement.executeUpdate(); + added = rowCount != 0 ? true : false; + } + return added; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java new file mode 100644 index 000000000..9c638de20 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.objects; + + +public enum VNFWorkingState { + STABLE,UNSTABLE,UNKNOWN; + public String toString(){ + return this.name(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java new file mode 100644 index 000000000..948d4ca59 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.objects; + + +public class VnfWorkingStateDto { + private String vnfId; + private VNFWorkingState state; + private String ownerId; + private long updated; + private long ver; + + public VnfWorkingStateDto() { + } + + public VnfWorkingStateDto(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public VNFWorkingState getState() { + return state; + } + + public void setState(VNFWorkingState state) { + this.state = state; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public long getUpdated() { + return updated; + } + + public void setUpdated(long updated) { + this.updated = updated; + } + + public long getVer() { + return ver; + } + + public void setVer(long ver) { + this.ver = ver; + } + + + @Override + public String toString() { + return "VnfWorkingStateDto{" + + "vnfId='" + vnfId + '\'' + + ", state=" + state + + ", ownerId='" + ownerId + '\'' + + ", updated=" + updated + + ", ver=" + ver + + '}'; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java deleted file mode 100644 index 15e8d2436..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.messageadapter; - -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; - -public interface MessageAdapter { - /** - * Initialize dmaapProducer client to post messages using configuration properties - */ - void init(); - - /** - * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP. - * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel). - * @return True if message is postes successfully else False - */ - boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse); - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java deleted file mode 100644 index 63a3c00a4..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.messageadapter.impl; - - -import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; -import org.onap.appc.adapter.factory.MessageService; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.requesthandler.conv.Converter; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashSet; -import java.util.Properties; - -public class MessageAdapterImpl implements MessageAdapter{ - - private MessageService messageService; - private Producer producer; - private String partition ; - private Configuration configuration; - private HashSet pool; - private String writeTopic; - private String apiKey; - private String apiSecret; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class); - - /** - * Initialize producer client to post messages using configuration properties - */ - @Override - public void init(){ - this.producer = getProducer(); - } - - private Producer getProducer() { - configuration = ConfigurationFactory.getConfiguration(); - Properties properties=configuration.getProperties(); - updateProperties(properties); - - BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); - } - } - return producer; - } - - - private void updateProperties(Properties props) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props)); - } - pool = new HashSet<>(); - if (props != null) { - // readTopic = props.getProperty("dmaap.topic.read"); - writeTopic = props.getProperty("appc.LCM.topic.write"); - apiKey = props.getProperty("appc.LCM.client.key"); - apiSecret = props.getProperty("appc.LCM.client.secret"); - messageService = MessageService.parse(props.getProperty("message.service.type")); - // READ_TIMEOUT = Integer.valueOf(props.getProperty("dmaap.topic.read.timeout", String.valueOf(READ_TIMEOUT))); - String hostnames = props.getProperty("appc.LCM.poolMembers"); - if (hostnames != null && !hostnames.isEmpty()) { - for (String name : hostnames.split(",")) { - pool.add(name); - } - } - } - } - - /** - * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP. - * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel). - * @return True if message is postes successfully else False - */ - @Override - public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){ - boolean success; - if (logger.isTraceEnabled()) { - logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse)); - } - - String jsonMessage; - try { - jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse); - if (logger.isDebugEnabled()) { - logger.debug("DMaaP Response = " + jsonMessage); - } - success = producer.post(this.partition, jsonMessage); - } catch (JsonProcessingException e1) { - logger.error("Error generating Json from DMaaP message "+ e1.getMessage()); - success= false; - }catch (Exception e){ - logger.error("Error sending message to DMaaP "+e.getMessage()); - success= false; - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")"); - } - return success; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java deleted file mode 100644 index 4015181a1..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.constant; - -import java.util.concurrent.TimeUnit; - -public class Constants { - - public static final int DEFAULT_TTL = 30; - public static final String SUCCESS_MSG="SUCCESS"; - public static final String FAILURE_MSG="FAILURE"; - public static final String DEFAULT_LOGGING_FLAG="true"; - public static final long DEFAULT_IDLE_TIMEOUT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java deleted file mode 100644 index 5a791711e..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java +++ /dev/null @@ -1,411 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.conv; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.*; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.FlagsBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; -import org.opendaylight.yangtools.concepts.Builder; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.requesthandler.impl.DmaapOutgoingMessage; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - - -public class Converter { - public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - public static final String MODE_FLAG = "MODE"; - public static final String FORCE_FLAG = "FORCE"; - public static final String TTL_FLAG = "TTL"; - public final static String DMaaP_ROOT_VALUE = "output"; - private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(Converter.class); - static { - isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public static Builder convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) { - Builder outObj = null; - if(response == null){ - throw new IllegalArgumentException("empty asyncResponse"); - } - if(vnfOperation == null){ - throw new IllegalArgumentException("empty asyncResponse.action"); - } - Action action = Action.valueOf(vnfOperation.name()); - CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response); - Status status = convAsyncResponseTorev160108Status(response); - Payload payload = convAsyncResponseTorev160108Payload(response); - switch (action){ - case Rollback: - outObj = new RollbackOutputBuilder(); - ((RollbackOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RollbackOutputBuilder)outObj).setStatus(status); - return outObj; - case Snapshot: - outObj = new SnapshotOutputBuilder(); - ((SnapshotOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SnapshotOutputBuilder)outObj).setStatus(status); - try { - ((SnapshotOutputBuilder) outObj).setSnapshotId(response.getAdditionalContext().get("output.snapshot-id")); - } catch (NullPointerException ignored) { - // in case of negative response, snapshotID does not populated, so just ignore NPL - } - return outObj; - case Audit: - outObj = new AuditOutputBuilder(); - ((AuditOutputBuilder)outObj).setCommonHeader(commonHeader); - ((AuditOutputBuilder)outObj).setStatus(status); - ((AuditOutputBuilder)outObj).setPayload(payload); - return outObj; - case HealthCheck: - outObj = new HealthCheckOutputBuilder(); - ((HealthCheckOutputBuilder)outObj).setCommonHeader(commonHeader); - ((HealthCheckOutputBuilder)outObj).setStatus(status); - return outObj; - case LiveUpgrade: - outObj = new LiveUpgradeOutputBuilder(); - ((LiveUpgradeOutputBuilder)outObj).setCommonHeader(commonHeader); - ((LiveUpgradeOutputBuilder)outObj).setStatus(status); - return outObj; - case Lock: - outObj = new LockOutputBuilder(); - ((LockOutputBuilder)outObj).setCommonHeader(commonHeader); - ((LockOutputBuilder)outObj).setStatus(status); - return outObj; - case Configure: - outObj = new ConfigureOutputBuilder(); - ((ConfigureOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigureOutputBuilder)outObj).setStatus(status); - ((ConfigureOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigModify: - outObj = new ConfigModifyOutputBuilder(); - ((ConfigModifyOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigModifyOutputBuilder)outObj).setStatus(status); - ((ConfigModifyOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigScaleOut: - outObj = new ConfigScaleoutOutputBuilder(); - ((ConfigScaleoutOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigScaleoutOutputBuilder)outObj).setStatus(status); - ((ConfigScaleoutOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigRestore: - outObj = new ConfigRestoreOutputBuilder(); - ((ConfigRestoreOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigRestoreOutputBuilder)outObj).setStatus(status); - ((ConfigRestoreOutputBuilder)outObj).setPayload(payload); - return outObj; - case SoftwareUpload: - outObj = new SoftwareUploadOutputBuilder(); - ((SoftwareUploadOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SoftwareUploadOutputBuilder)outObj).setStatus(status); - return outObj; - case Stop: - outObj = new StopOutputBuilder(); - ((StopOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StopOutputBuilder)outObj).setStatus(status); - return outObj; - case Sync: - outObj = new SyncOutputBuilder(); - ((SyncOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SyncOutputBuilder)outObj).setStatus(status); - ((SyncOutputBuilder)outObj).setPayload(payload); - return outObj; - case Terminate: - outObj = new TerminateOutputBuilder(); - ((TerminateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((TerminateOutputBuilder)outObj).setStatus(status); - return outObj; - case Test: - outObj = new TestOutputBuilder(); - ((TestOutputBuilder)outObj).setCommonHeader(commonHeader); - ((TestOutputBuilder)outObj).setStatus(status); - return outObj; - case Unlock: - outObj = new UnlockOutputBuilder(); - ((UnlockOutputBuilder)outObj).setCommonHeader(commonHeader); - ((UnlockOutputBuilder)outObj).setStatus(status); - return outObj; - case Restart: - outObj = new RestartOutputBuilder(); - ((RestartOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RestartOutputBuilder)outObj).setStatus(status); - return outObj; - case Rebuild: - outObj = new RebuildOutputBuilder(); - ((RebuildOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RebuildOutputBuilder)outObj).setStatus(status); - return outObj; - case Migrate: - outObj = new MigrateOutputBuilder(); - ((MigrateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((MigrateOutputBuilder)outObj).setStatus(status); - return outObj; - case Evacuate: - outObj = new EvacuateOutputBuilder(); - ((EvacuateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((EvacuateOutputBuilder)outObj).setStatus(status); - return outObj; - case ConfigBackup: - outObj = new ConfigBackupOutputBuilder(); - ((ConfigBackupOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigBackupOutputBuilder)outObj).setStatus(status); - ((ConfigBackupOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigBackupDelete: - outObj = new ConfigBackupDeleteOutputBuilder(); - ((ConfigBackupDeleteOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigBackupDeleteOutputBuilder)outObj).setStatus(status); - ((ConfigBackupDeleteOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigExport: - outObj = new ConfigExportOutputBuilder(); - ((ConfigExportOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigExportOutputBuilder)outObj).setStatus(status); - return outObj; - case Start: - outObj = new StartOutputBuilder(); - ((StartOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StartOutputBuilder)outObj).setStatus(status); - return outObj; - case StopApplication: - outObj = new StopApplicationOutputBuilder(); - ((StopApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StopApplicationOutputBuilder)outObj).setStatus(status); - return outObj; - case StartApplication: - outObj = new StartApplicationOutputBuilder(); - ((StartApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StartApplicationOutputBuilder)outObj).setStatus(status); - return outObj; - default: - throw new IllegalArgumentException(action+" action is not supported"); - } - } - - public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) { - Payload payload = null; - if(inObj.getPayload() != null) { - payload = new Payload(inObj.getPayload()); - } - return payload; - } - - public static String convPayloadObjectToJsonString(Object inObj) throws ParseException { - String payloadAsString = null; - if(inObj != null) { - - if(inObj instanceof String){ - payloadAsString = (String)inObj; - }else { - try { - ObjectMapper objectMapper = new ObjectMapper(); - payloadAsString = objectMapper.writeValueAsString(inObj); -// payloadAsString = objectMapper.writeValueAsString(payloadAsString); - } catch (JsonProcessingException e) { - String errMsg = "Error serialize payload json to string"; - throw new ParseException(errMsg + "-" + e.toString(), 0); - } - } - } - return payloadAsString; - } - - public static Status convAsyncResponseTorev160108Status(ResponseContext inObj) { - StatusBuilder statusBuilder = new StatusBuilder(); - statusBuilder.setCode(inObj.getStatus().getCode()); - statusBuilder.setMessage(inObj.getStatus().getMessage()); - return statusBuilder.build(); - } - - public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) { - CommonHeader outObj = null; - if(inObj == null){ - throw new IllegalArgumentException("empty asyncResponse"); - } - - CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags = null; - if(inObj.getCommonHeader().getFlags() != null){ - commonHeaderFlags = Converter.convFlagsMapTorev160108Flags(inObj.getCommonHeader().getFlags()); - commonHeaderBuilder.setFlags(commonHeaderFlags); - } - - - commonHeaderBuilder.setApiVer(inObj.getCommonHeader().getApiVer()); - commonHeaderBuilder.setRequestId(inObj.getCommonHeader().getRequestId()); - if(inObj.getCommonHeader().getSubRequestId() != null){ - commonHeaderBuilder.setSubRequestId(inObj.getCommonHeader().getSubRequestId()); - } - - if(inObj.getCommonHeader().getOriginatorId() != null){ - commonHeaderBuilder.setOriginatorId(inObj.getCommonHeader().getOriginatorId()); - } - - if(inObj.getCommonHeader().getTimeStamp() != null){ - String zuluTimestampStr = Converter.convDateToZuluString(Date.from(inObj.getCommonHeader().getTimeStamp())); - ZULU zuluTimestamp = new ZULU(zuluTimestampStr); - commonHeaderBuilder.setTimestamp(zuluTimestamp); - } - outObj = commonHeaderBuilder.build(); - return outObj; - - } - - public static String convDateToZuluString(Date timeStamp) { - return isoFormatter.format(timeStamp); - } - - public static org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags - convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) { - Flags rev160108flags = null; - boolean anyFlag = false; - FlagsBuilder flagsBuilder = new FlagsBuilder(); - /* - * TODO: The below flags are related to APP-C request and should not be sent back - uncomment when response flags are introduced. - */ - /* - if(flags.containsKey(FORCE_FLAG)){ - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force force = - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force.valueOf(flags.get(FORCE_FLAG).toString()); - flagsBuilder.setForce(force); - anyFlag = true; - } - if(flags.containsKey(MODE_FLAG)){ - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode mode = - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode.valueOf(flags.get(MODE_FLAG).toString()); - flagsBuilder.setMode(mode); - anyFlag = true; - } - if(flags.containsKey(TTL_FLAG)){ - flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString())); - anyFlag = true; - } - if(anyFlag){ - rev160108flags = flagsBuilder.build(); - } - */ - - rev160108flags = flagsBuilder.build(); - return rev160108flags; - } - - public static String convAsyncResponseToJsonStringBody(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); - Object message = builder.build(); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.addMixInAnnotations(message.getClass(), MixInFlagsMessage.class); - objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); - objectMapper.addMixInAnnotations(Flags.class, MixIn.class); - objectMapper.addMixInAnnotations(Status.class, MixIn.class); - objectMapper.addMixInAnnotations(Payload.class, MixIn.class); - objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); - -// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) - .writer(SerializationFeature.WRAP_ROOT_VALUE).withRootName(DMaaP_ROOT_VALUE).withoutFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); - return writer.writeValueAsString(message); - } - - public static String convAsyncResponseToDmaapOutgoingMessageJsonString(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class); - objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); - objectMapper.addMixInAnnotations(Flags.class, MixIn.class); - objectMapper.addMixInAnnotations(Status.class, MixIn.class); - objectMapper.addMixInAnnotations(Payload.class, MixIn.class); - objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); - -// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true).writer(); - return writer.writeValueAsString(dmaapOutgoingMessage); - } - - public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); - String correlationID = getCorrelationID(asyncResponse); - outObj.setCorrelationID(correlationID); - outObj.setType("response"); - outObj.setRpcName(rpcName); - Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); - Object messageBody = builder.build(); - DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); - outObj.setBody(body); - return outObj; - } - - private static String getCorrelationID(ResponseContext context) { - return context.getCommonHeader().getRequestId() - + (context.getCommonHeader().getSubRequestId() == null ? - "":"-" + context.getCommonHeader().getSubRequestId()); - } - - abstract class MixIn { - @JsonIgnore - abstract Class getImplementedInterface(); // to be removed during serialization - - @JsonValue - abstract java.lang.String getValue(); - } - abstract class MixInCommonHeader extends MixIn { - @JsonProperty("api-ver") - abstract java.lang.String getApiVer(); - @JsonProperty("originator-id") - abstract java.lang.String getOriginatorId(); - @JsonProperty("request-id") - abstract java.lang.String getRequestId(); - @JsonProperty("sub-request-id") - abstract java.lang.String getSubRequestId(); - - } - abstract class MixInFlagsMessage extends MixIn { - @JsonProperty("common-header") - abstract CommonHeader getCommonHeader(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java deleted file mode 100644 index 5626cfe6f..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class DGWorkflowNotFoundException extends Exception { - public final String workflowModule; - public final String workflowName; - public final String workflowVersion; - public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion){ - super(message); - this.workflowModule = workflowModule; - this.workflowName = workflowName; - this.workflowVersion = workflowVersion; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java deleted file mode 100644 index b06788a99..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class DuplicateRequestException extends Exception { - public DuplicateRequestException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java deleted file mode 100644 index 6e2435559..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class InvalidInputException extends Exception { - public InvalidInputException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java deleted file mode 100644 index ca5f72682..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - -/** - */ -public class LCMOperationsDisabledException extends Exception { - - /** - * Constructs a new exception with the specified detail message. - * - * @param message the detail message. - */ - public LCMOperationsDisabledException(String message) { - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java deleted file mode 100644 index 219265084..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - -public class MissingVNFDataInAAIException extends Exception { - String missingAttributeName; - public MissingVNFDataInAAIException(String attributeName) { - this.missingAttributeName = attributeName; - } - - public String getMissingAttributeName() { - return missingAttributeName; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java deleted file mode 100644 index 02a130c8b..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class RequestExpiredException extends Exception { - public RequestExpiredException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java deleted file mode 100644 index d1b2759d6..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class VNFNotFoundException extends Exception { - public VNFNotFoundException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java deleted file mode 100644 index 85157e32f..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class WorkflowNotFoundException extends Exception { - public final String vnfTypeVersion; - public final String command; - public WorkflowNotFoundException(String message,String vnfTypeVersion,String command){ - super(message); - this.vnfTypeVersion = vnfTypeVersion; - this.command = command; - } - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java deleted file mode 100644 index fd1292ff9..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.helper; - -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * This class serves as Request Registry, which holds the - * request unique parameters (originatorId,requestId,subRequestId) - * in memory. - */ -public class RequestRegistry { - - static Set set = Collections.newSetFromMap(new ConcurrentHashMap()); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestRegistry.class); - public RequestRegistry(){ - - } - - /** - * This method accepts unique request parameters and adds it to Request Registry - * if Registry already contains same parameters it returns false, - * else returns true. - * @param requestIdentifier - * @return - */ - public boolean registerRequest(UniqueRequestIdentifier requestIdentifier){ - - if (logger.isTraceEnabled()) { - logger.trace("Entering to registerRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); - } - boolean output = set.add(requestIdentifier); - logger.debug(" Output = " + output); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from registerRequest with (output = "+ ObjectUtils.toString(output)+")"); - } - return output; - } - - /** - * This method accepts unique request parameters and removes request - * from the Request Registry - * @param requestIdentifier - */ - public void removeRequest(UniqueRequestIdentifier requestIdentifier){ - if (logger.isTraceEnabled()) { - logger.trace("Entering to removeRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); - } - set.remove(requestIdentifier); - } - - /** - * This method returns the count of currently registered requests - * in the request registry - * * @return currently registered requests count - */ - public int getRegisteredRequestCount() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getRegisteredRequestCount"); - } - return set.size(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java deleted file mode 100644 index e45341d3d..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.helper; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; -import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; -import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException; -import org.onap.appc.requesthandler.exceptions.RequestExpiredException; -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; - -public interface RequestValidator { - public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java deleted file mode 100644 index 8b56dda41..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java +++ /dev/null @@ -1,626 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.requesthandler.constant.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executor.CommandExecutor; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.messageadapter.impl.MessageAdapterImpl; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.publisher.LogPublisher; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.helper.RequestRegistry; -import org.onap.appc.requesthandler.helper.RequestValidator; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.transactionrecorder.objects.TransactionRecord; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.time.Instant; -import java.util.HashMap; -import java.util.Properties; - -import static com.att.eelf.configuration.Configuration.*; - -/** - * This class provides application logic for the Request/Response Handler Component. - * - */ -public abstract class AbstractRequestHandlerImpl implements RequestHandler { - - private RequestValidator requestValidator; - - - - private RequestRegistry requestRegistry; - - private CommandExecutor commandExecutor; - - private TransactionRecorder transactionRecorder; - - private MessageAdapter messageAdapter; - - private static MetricRegistry metricRegistry; - - private boolean isMetricEnabled = false; - - protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class); - - public AbstractRequestHandlerImpl() { - requestRegistry = new RequestRegistry(); - messageAdapter = new MessageAdapterImpl(); - messageAdapter.init(); - Properties properties = configuration.getProperties(); - if (properties != null && properties.getProperty("metric.enabled") != null) { - isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled")); - } - if (isMetricEnabled) { - initMetric(); - } - } - - public void setTransactionRecorder(TransactionRecorder transactionRecorder) { - this.transactionRecorder = transactionRecorder; - } - - public void setRequestValidator(RequestValidator requestValidator) { - this.requestValidator = requestValidator; - } - - public void setMessageAdapter(MessageAdapter messageAdapter) { - this.messageAdapter = messageAdapter; - } - - - - public void setRequestRegistry(RequestRegistry requestRegistry) { - this.requestRegistry = requestRegistry; - } - - public void setCommandExecutor(CommandExecutor commandExecutor) { - this.commandExecutor = commandExecutor; - } - - - /** - * It receives requests from the north-bound REST API (Communication) Layer and - * performs following validations. - * 1. VNF exists in A&AI for the given targetID (VnfID) - * 2. For the current VNF Orchestration Status, the command can be executed - * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database - * If any of the validation fails, it returns appropriate response - * - * @param input RequestHandlerInput object which contains request header and other request parameters like command , target Id , payload etc. - * @return response for request as enum with Return code and message. - */ - @Override - public RequestHandlerOutput handleRequest(RequestHandlerInput input) { - if (logger.isTraceEnabled()) - logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")"); - Params params ; - String vnfId, vnfType = null, errorMessage = null; - Instant startTime = Instant.now(); - RequestHandlerOutput output = null; - setInitialLogProperties(input.getRequestContext()); - - RuntimeContext runtimeContext = new RuntimeContext(); - runtimeContext.setRequestContext(input.getRequestContext()); - runtimeContext.setTimeStart(startTime); - runtimeContext.setRpcName(input.getRpcName()); - - final ResponseContext responseContext = new ResponseContext(); - responseContext.setStatus(new Status(0,"")); - responseContext.setAdditionalContext(new HashMap<>(4)); - responseContext.setCommonHeader(input.getRequestContext().getCommonHeader()); - runtimeContext.setResponseContext(responseContext); - runtimeContext.getResponseContext().setStatus(new Status(0,"")); - - vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - try { - - requestValidator.validateRequest(runtimeContext); - - handleRequest(runtimeContext); - - final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); - if (statusCode % 100 == 2 || statusCode % 100 == 3) { - createTransactionRecord(runtimeContext); - } - output = new RequestHandlerOutput(); - output.setResponseContext(runtimeContext.getResponseContext()); - - } catch (VNFNotFoundException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId); - storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage); - params = new Params().addParam("vnfId", vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params); - } catch (NoTransitionDefinedException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name()); - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); - output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.STATE_MACHINE, - logMessage); - } catch (LifecycleException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); - output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params); - } catch (UnstableVNFException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("vnfId", vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params); - } catch (WorkflowNotFoundException e) { - errorMessage = e.getMessage(); - String vnfTypeVersion = e.vnfTypeVersion; - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion); - output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params); - } catch (DGWorkflowNotFoundException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name()); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - logMessage); - params = new Params().addParam("actionName", input.getRequestContext().getAction().name()) - .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion); - output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params); - } catch (RequestExpiredException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("actionName", input.getRequestContext().getAction().name()); - output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params); - } catch (InvalidInputException e) { - errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params); - } catch (DuplicateRequestException e) { - errorMessage = e.getMessage(); - output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null); - } catch (MissingVNFDataInAAIException e) { - params = new Params().addParam("attributeName",e.getMissingAttributeName()) - .addParam("vnfId",vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params); - errorMessage = output.getResponseContext().getStatus().getMessage(); - } catch (LCMOperationsDisabledException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params); - } catch (Exception e) { - storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage()); - errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params); - } finally { - try { - if (logger.isDebugEnabled() && errorMessage != null) - logger.debug("error occurred in handleRequest " + errorMessage); - logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())); - logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())); - - runtimeContext.setResponseContext(output.getResponseContext()); - if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) { - if (isMetricEnabled) { - if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); - }else { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest(); - } - } - removeRequestFromRegistry(input.getRequestContext().getCommonHeader()); - } - } finally { - storeAuditLogRecord(runtimeContext); - storeMetricLogRecord(runtimeContext); - clearRequestLogProperties(); - } - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")"); - } - return output; - } - - protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) { - LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ? - String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "", - runtimeContext.getResponseContext().getStatus() != null ? - String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "", - targetEntity, - targetServiceName, - additionalMessage, - this.getClass().getCanonicalName()); - } - - private void createTransactionRecord(RuntimeContext runtimeContext) { - TransactionRecord transactionRecord = new TransactionRecord(); - transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp()); - transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId()); - transactionRecord.setStartTime(runtimeContext.getTimeStart()); - transactionRecord.setEndTime(Instant.now()); - transactionRecord.setTargetID(runtimeContext.getVnfContext().getId()); - transactionRecord.setTargetType(runtimeContext.getVnfContext().getType()); - transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name()); - transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode())); - transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage()); - transactionRecorder.store(transactionRecord); - } - - protected abstract void handleRequest(RuntimeContext runtimeContext) ; - - protected void callWfOperation(RuntimeContext runtimeContext) { - int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader()); - if (remainingTTL > 0) { - if (logger.isDebugEnabled()) { - logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL); - } - - RuntimeContext clonedContext = cloneContext(runtimeContext); - - try { - commandExecutor.executeCommand(clonedContext); - if(logger.isTraceEnabled()) { - logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId())); - } - fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null); - if (isMetricEnabled) { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); - } - } catch (APPCException e) { - String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - Params params = new Params().addParam("errorMsg", errorMessage); - fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params); - } - - } else { - fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.REQUEST_HANDLER, - EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST, - runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(), - runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(), - String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl()))); - } - } - - protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) { - runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params))); - } - - /* - * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted - * status code and other - depending on DG status). Other properties should not be a problem - */ - private RuntimeContext cloneContext(RuntimeContext runtimeContext) { - RuntimeContext other = new RuntimeContext(); - other.setRequestContext(runtimeContext.getRequestContext()); - other.setResponseContext(new ResponseContext()); - other.getResponseContext().setStatus(new Status(0,"")); - other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader()); - other.setVnfContext(runtimeContext.getVnfContext()); - other.setRpcName(runtimeContext.getRpcName()); - other.setTimeStart(runtimeContext.getTimeStart()); - other.setIsLockAcquired(runtimeContext.isLockAcquired()); - return other; - } - - - private void clearRequestLogProperties() { - try { - MDC.remove(MDC_KEY_REQUEST_ID); - MDC.remove(MDC_SERVICE_INSTANCE_ID); - MDC.remove(MDC_SERVICE_NAME); - MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); - MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY); - } catch (Exception e) { - //do nothing - } - } - - private void removeRequestFromRegistry(CommonHeader commonHeader) { - if (logger.isTraceEnabled()) - logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader)); - requestRegistry.removeRequest( - new UniqueRequestIdentifier(commonHeader.getOriginatorId(), - commonHeader.getRequestId(), - commonHeader.getSubRequestId())); - } - - - private void setInitialLogProperties(RequestContext requestContext) { - - try { - MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId()); - if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) { - MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId()); - } - MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId()); - MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong! - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name()); - MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId()); - - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } catch (RuntimeException e) { - //ignore - } - } - - - private int calculateRemainingTTL(CommonHeader commonHeader) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader)); - } - long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().toEpochMilli()); - logger.debug("usedTimeInMillis = " + usedTimeInMillis); - int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000); - logger.debug("usedTimeInSeconds = " + usedTimeInSeconds); - Integer inputTTL = this.getInputTTL(commonHeader); - logger.debug("inputTTL = " + inputTTL); - Integer remainingTTL = inputTTL - usedTimeInSeconds; - logger.debug("Remaining TTL = " + remainingTTL); - if (logger.isTraceEnabled()) - logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")"); - return remainingTTL; - } - - private Integer getInputTTL(CommonHeader header) { - if (logger.isTraceEnabled()) - logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header)); - if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) { - String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); - Integer defaultTTL = Integer.parseInt(defaultTTLStr); - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")"); - return defaultTTL; - } - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")"); - - return header.getFlags().getTtl(); - } - - private boolean isValidTTL(String ttl) { - if (ttl == null || ttl.length() == 0) { - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (result = false)"); - return false; - } - try { - Integer i = Integer.parseInt(ttl); - return (i > 0); - } catch (NumberFormatException e) { - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (result = false)"); - return false; - } - } - - private Boolean isLoggingEnabled() { - String defaultFlagStr = configuration.getProperty("org.onap.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG)); - return Boolean.parseBoolean(defaultFlagStr); - } - - private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) { - RequestHandlerOutput output = new RequestHandlerOutput(); - ResponseContext responseContext = new ResponseContext(); - org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params)); - responseContext.setStatus(status); - output.setResponseContext(responseContext); - return output; - } - - /** - * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. - * - * @param vnfId String of VNF ID - * @param readOnlyActivity boolean indicator - * @param requestIdentifierString - string contains id uniquely represents the request - * @param forceFlag boolean indicator - * @throws UnstableVNFException when failed - */ - @Override - public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ; - - /** - * This method perform following operations required after execution of workflow. - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * Generate audit logs. - * Adds transaction record to database id if transaction logging is enabled. - * - * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. - */ - @Override - public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext)); - } - - postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); - requestRegistry.removeRequest( - new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); - - storeAuditLogRecord(runtimeContext); - if (isLoggingEnabled()) { - createTransactionRecord(runtimeContext); - } - } - - private void storeAuditLogRecord(RuntimeContext runtimeContext) { - LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(), - Instant.now(), - String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()), - runtimeContext.getResponseContext().getStatus().getMessage(), - this.getClass().getCanonicalName()); - } - - private void storeMetricLogRecord(RuntimeContext runtimeContext) { - LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(), - Instant.now(), - LoggingConstants.TargetNames.APPC, - runtimeContext.getRequestContext().getAction().name(), - runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode() ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR, - String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()), - runtimeContext.getResponseContext().getStatus().getMessage(), - this.getClass().getCanonicalName()); - } - - - - - private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext)); - } - boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext); - if (!callbackResponse) { - logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext); - } - if (logger.isTraceEnabled()) - logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")"); - } - - /** - * This method perform following operations required if TTL ends when request still waiting in execution queue . - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * - * @param runtimeContext AsyncResponse object which contains VNF Id , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId; - * @param updateAAI boolean flag which indicate AAI upodate status after request completion. - */ - @Override - public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestTTLEnd with " + - "AsyncResponse = " + ObjectUtils.toString(runtimeContext) + - ", updateAAI = " + ObjectUtils.toString(updateAAI)); - } - logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage()); - fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null); - postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); - - requestRegistry.removeRequest( - new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); - } - - private void initMetric() { - if (logger.isDebugEnabled()) - logger.debug("Metric getting initialized"); - MetricService metricService = getMetricservice(); - metricRegistry = metricService.createRegistry("APPC"); - DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory(). - dispatchingFunctionCounterBuilder(). - withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER). - withAcceptRequestValue(0) - .withRejectRequestValue(0) - .build(); - if (metricRegistry.register(dispatchingFuntionMetric)) { - Metric[] metrics = new Metric[]{dispatchingFuntionMetric}; - LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); - LogPublisher[] logPublishers = new LogPublisher[1]; - logPublishers[0] = logPublisher; - PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). - scheduledPolicyBuilder().withPublishers(logPublishers). - withMetrics(metrics). - build(); - if (logger.isDebugEnabled()) - logger.debug("Policy getting initialized"); - manuallyScheduledPublishingPolicy.init(); - if (logger.isDebugEnabled()) - logger.debug("Metric initialized"); - } - } - - - private MetricService getMetricservice() { - BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); - if (sref != null) { - logger.info("Metric Service from bundlecontext"); - return (MetricService) bctx.getService(sref); - } else { - logger.info("Metric Service error from bundlecontext"); - logger.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); - return null; - } - } - - /** - * This method returns the count of in progress requests - * * @return in progress requests count - */ - @Override - public int getInprogressRequestCount() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getInprogressRequestCount"); - } - return requestRegistry.getRegisteredRequestCount(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java deleted file mode 100644 index 4f4942b8a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java +++ /dev/null @@ -1,328 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.appc.requesthandler.constant.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.helper.RequestRegistry; -import org.onap.appc.requesthandler.helper.RequestValidator; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.time.Instant; -import java.util.Calendar; -import java.util.Date; - -public abstract class AbstractRequestValidatorImpl implements RequestValidator { - - protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class); - private final Configuration configuration = ConfigurationFactory.getConfiguration(); - protected LifecycleManager lifecyclemanager; - protected LCMStateManager lcmStateManager; - private AAIService aaiService; - private WorkFlowManager workflowManager; - private RequestRegistry requestRegistry = new RequestRegistry(); - - protected static Calendar DateToCalendar(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal; - } - - public void setWorkflowManager(WorkFlowManager workflowManager) { - this.workflowManager = workflowManager; - } - - public void setLcmStateManager(LCMStateManager lcmStateManager) { - this.lcmStateManager = lcmStateManager; - } - - public void setRequestRegistry(RequestRegistry requestRegistry) { - this.requestRegistry = requestRegistry; - } - - public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; - - private boolean isValidTTL(String ttl) { - if (logger.isTraceEnabled()){ - logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl)); - } - if (ttl == null || ttl.length() == 0) { - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")"); - } - return false; - } - try { - Integer i = Integer.parseInt(ttl); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")"); - } - return (i > 0); - } catch (NumberFormatException e) { - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")"); - } - return false; - } - } - - protected void getAAIservice() { - BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); - // Get AAIadapter reference - ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); - if (sref != null) { - logger.info("AAIService from bundlecontext"); - aaiService = (AAIService) bctx.getService(sref); - - } else { - logger.info("AAIService error from bundlecontext"); - logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); - - } - } - - protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx = getVnfdata(vnfId, "vnf", ctx); - - VNFContext vnfContext = new VNFContext(); - populateVnfContext(vnfContext, ctx); - - return vnfContext; - } - - protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { - - checkWorkflowExists(vnfContext, requestContext); - } - - private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { - - WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext)); - if (!workflowExistsOutput.isMappingExist()) { - if (logger.isDebugEnabled()) { - logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()); - } - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), - this.getClass().getCanonicalName()); - - - throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name()); - } - if (!workflowExistsOutput.isDgExist()) { - if (logger.isDebugEnabled()) { - logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput); - } - - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), - this.getClass().getCanonicalName()); - - - throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(), - workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion()); - } - } - - private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException { - String vnfType = ctx.getAttribute("vnf.vnf-type"); - String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status"); - if(StringUtils.isEmpty(vnfType)){ - throw new MissingVNFDataInAAIException("vnf-type"); - } - else if(StringUtils.isEmpty(orchestrationStatus)){ - throw new MissingVNFDataInAAIException("orchestration-status"); - } - vnfContext.setType(vnfType); - vnfContext.setStatus(orchestrationStatus); - vnfContext.setId(ctx.getAttribute("vnf.vnf-id")); - } - - private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) { - - WorkflowRequest workflowRequest = new WorkflowRequest(); - workflowRequest.setVnfContext(vnfContext); - workflowRequest.setRequestContext(requestContext); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")"); - } - return workflowRequest; - } - - protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header)); - } - - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId()); - boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier); - if (!requestAccepted) { - if (logger.isDebugEnabled()) { - logger.debug("Duplicate Request with " + requestIdentifier); - } - throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier); - } - } - - protected Integer readTTL(CommonHeader header) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header)); - } - if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) { - String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); - return Integer.parseInt(defaultTTLStr); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from readTTL with (TTL = "+ ObjectUtils.toString(header.getFlags().getTtl())+")"); - } - return header.getFlags().getTtl(); - } - - private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx)); - } - - String key = "vnf-id = '" + vnf_id + "'"; - logger.debug("inside getVnfdata=== " + key); - try { - Instant beginTimestamp = Instant.now(); - SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx); - Instant endTimestamp = Instant.now(); - String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR; - LoggingUtils.logMetricsMessage( - beginTimestamp, - endTimestamp, - LoggingConstants.TargetNames.AAI, - LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY, - status, - "", - response.name(), - this.getClass().getCanonicalName()); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id); - } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id); - } - logger.info("AAIResponse: " + response.toString()); - } catch (SvcLogicException e) { - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA, - "Error in getVnfdata" + e, - this.getClass().getCanonicalName()); - - throw new RuntimeException(e); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")"); - } - return ctx; - } - - protected void validateInput(RequestContext requestContext) - throws RequestExpiredException, InvalidInputException, DuplicateRequestException { - if (logger.isTraceEnabled()){ - logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext)); - } - if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null - || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 || - null == requestContext.getCommonHeader().getApiVer()) { - if (logger.isDebugEnabled()) { - logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name()); - } - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.APPC_INVALID_INPUT), - this.getClass().getCanonicalName()); - - throw new InvalidInputException("vnfID or command is null"); - } - CommonHeader commonHeader = requestContext.getCommonHeader(); - - checkForDuplicateRequest(commonHeader); - - Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp())); - Calendar currentTime = Calendar.getInstance(); - - // If input timestamp is of future, we reject the request - if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) { - if (logger.isDebugEnabled()) { - logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime()); - } - throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime()); - } - Integer ttl = readTTL(commonHeader); - logger.debug("TTL value set to (seconds) : " + ttl); - inputTimeStamp.add(Calendar.SECOND, ttl); - if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) { - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl, - this.getClass().getCanonicalName()); - - throw new RequestExpiredException("TTL Expired"); - } - if (logger.isDebugEnabled()) { - logger.debug("Validation of the request is successful"); - } - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java deleted file mode 100644 index 0df57a754..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - - - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** - * This class represents a message being sent out to DMaaP by APPC as async response. - * note the structure of this class must be adapted to the sync message sent to DMaaP represened in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapOutgoingMessage { - - @JsonProperty("version") - private String version; - - @JsonProperty("type") - private String type; - - @JsonProperty("correlation-id") - private String correlationID; - - private final static String defaultCambriaPartition = "MSO"; - @JsonProperty("cambria.partition") - private String cambriaPartition = defaultCambriaPartition; - - @JsonProperty("rpc-name") - private String rpcName; - - @JsonProperty("body") - private Body body; - - public DmaapOutgoingMessage() { - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCorrelationID() { - return correlationID; - } - - public void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - public String getCambriaPartition() { - return cambriaPartition; - } - - public void setCambriaPartition(String cambriaPartition) { - this.cambriaPartition = cambriaPartition; - } - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public Body getBody() { - return body; - } - - public void setBody(Body body) { - this.body = body; - } - - @Override - public String toString() { - return "DmaapOutgoingMessage{" + - "cambriaPartition='" + cambriaPartition + '\'' + - ", rpcName='" + rpcName + '\'' + - ", body=" + body + - '}'; - } - - @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) - @JsonIgnoreProperties(ignoreUnknown = true) - public static class Body { - public Body() { - } - - public Body(Object output) { - this.output = output; - } - - @JsonProperty("output") - private Object output; - - public Object getOutput() { - return output; - } - - public void setOutput(Object body) { - this.output = body; - } - - @Override - public String toString() { - return "Body{" + - "output=" + output + - '}'; - } - } -} - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java deleted file mode 100644 index 276eaddab..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.onap.appc.requesthandler.LCMStateManager; - -public class LCMStateManagerImpl implements LCMStateManager { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class); - private static AtomicBoolean isLCMEnabled = new AtomicBoolean(true); - - /** - * This method checks if the LCM operations are enabled or not - * * @return true if enabled else false - */ - public boolean isLCMOperationEnabled() { - return isLCMEnabled.get(); - } - - /** - * This method disables the LCM operations - */ - public void disableLCMOperations() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to disableLCMOperations"); - } - isLCMEnabled.set(false); - } - - /** - * This method enables the LCM operations - */ - public void enableLCMOperations() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to enableLCMOperations"); - } - isLCMEnabled.set(true); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java deleted file mode 100644 index 1f07b277c..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java +++ /dev/null @@ -1,235 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.appc.requesthandler.constant.Constants; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; - -/** - * This class provides application logic for the Request/Response Handler Component. - * - */ -public class RequestHandlerImpl extends AbstractRequestHandlerImpl { - - /** - * APP-C VNF lock idle timeout in milliseconds. Applied only when locking VNF using northbound API "lock" - */ - private static final String PROP_IDLE_TIMEOUT = "org.onap.appc.lock.idleTimeout"; - - private LockManager lockManager; - - private WorkingStateManager workingStateManager; - - public void setLockManager(LockManager lockManager) { - this.lockManager = lockManager; - } - - public void setWorkingStateManager(WorkingStateManager workingStateManager) { - this.workingStateManager = workingStateManager; - } - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class); - - protected void handleRequest(RuntimeContext runtimeContext) { - - switch (runtimeContext.getRequestContext().getAction()) { - case Lock: - try { - lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); - } catch (LockException e) { - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.LOCK_MANAGER, - EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); - } - break; - - case Unlock: - try { - releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); - } catch (LockException e) { - //TODO add proper error code and message - // logger.error(EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - } - break; - - case CheckLock: - boolean isLocked = lockManager.isLocked(runtimeContext.getVnfContext().getId()); - fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); - runtimeContext.getResponseContext().addKeyValueToAdditionalContext("locked", String.valueOf(isLocked).toUpperCase()); - break; - default: - try { - boolean lockAcquired = acquireVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), 0); - runtimeContext.setIsLockAcquired(lockAcquired); - callWfOperation(runtimeContext); - } catch (LockException e) { - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - } finally { - if (runtimeContext.isLockAcquired()) { - final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); - if (statusCode % 100 == 2 || statusCode % 100 == 3) { - try { - releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - } catch (LockException e) { - logger.error("Error releasing the lock",e); - } - } - } - } - } - } - - private void releaseVNFLock(String vnfId, String transactionId) throws LockException { - lockManager.releaseLock(vnfId, transactionId); - logger.info("Lock released for vnfID = " + vnfId); - } - - protected void lockWithTimeout(String vnfId, String requestId) throws LockException { - long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT); - acquireVNFLock(vnfId, requestId, timeout); - } - - private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException { - if (logger.isTraceEnabled()) - logger.trace("Entering to acquireVNFLock with vnfID = " + vnfID); - boolean lockAcquired = lockManager.acquireLock(vnfID, requestId, timeout); - if (lockAcquired) { - logger.info("Lock acquired for vnfID = " + vnfID); - } else { - logger.info("vnfID = " + vnfID + " was already locked"); - } - return lockAcquired; - } - - /** - * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. - * - * @param vnfId String of VNF ID - * @param readOnlyActivity boolean indicator - * @param requestIdentifierString - string contains id uniquely represents the request - * @param forceFlag boolean indicator - * @throws UnstableVNFException when failed - */ - @Override - public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestExecutionStart with vnfId = " + vnfId + "and requestIdentifierString = " + requestIdentifierString); - } - - if(!readOnlyActivity || !forceFlag || workingStateManager.isVNFStable(vnfId)) { - boolean updated = false; - try { - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, requestIdentifierString, forceFlag); - } catch (Exception e) { - logger.error("Error updating working state for vnf " + vnfId + e); - throw new RuntimeException(e); - } - if (!updated) { - throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); - } - } - - if (logger.isTraceEnabled()) - logger.trace("Exiting from onRequestExecutionStart "); - } - - private boolean isReadOnlyAction(VNFOperation action) { - if (VNFOperation.Sync.toString().equals(action) || - VNFOperation.Audit.toString().equals(action) || - VNFOperation.ConfigBackup.toString().equals(action) || - VNFOperation.ConfigBackupDelete.toString().equals(action) || - VNFOperation.ConfigExport.toString().equals(action)){ - return true; - } - return false; - } - - @Override - public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { - super.onRequestExecutionEnd(runtimeContext,isAAIUpdated); - VNFWorkingState workingState; - Status status = runtimeContext.getResponseContext().getStatus(); - if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) { - workingState = VNFWorkingState.STABLE; - } else { - workingState = VNFWorkingState.UNKNOWN; - } - - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()); - - String requestIdentifierString = requestIdentifier.toIdentifierString(); - workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false); - logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId()); - resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); - } - - private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) { - if (lockAcquired) { - try { - releaseVNFLock(vnfId, requestId); - } catch (LockException e) { - logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); - } - } else if (resetLockTimeout) { - try { - // reset timeout to previous value - lockWithTimeout(vnfId, requestId); - } catch (LockException e) { - logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); - } - } - } - - @Override - public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { - super.onRequestTTLEnd(runtimeContext,updateAAI); - resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java deleted file mode 100644 index 8724adc59..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.workingstatemanager.WorkingStateManager; - - -public class RequestValidatorImpl extends AbstractRequestValidatorImpl { - - private WorkingStateManager workingStateManager; - private LCMStateManager lcmStateManager; - - public void setLifecyclemanager(LifecycleManager lifecyclemanager) { - this.lifecyclemanager = lifecyclemanager; - } - - public void setWorkingStateManager(WorkingStateManager workingStateManager) { - this.workingStateManager = workingStateManager; - } - - public void setLcmStateManager(LCMStateManager lcmStateManager) { - this.lcmStateManager = lcmStateManager; - } - - public RequestValidatorImpl() { - } - - @Override - public void validateRequest(RuntimeContext runtimeContext) - throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, - DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, - DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - if (logger.isTraceEnabled()){ - logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext)); - } - if(!lcmStateManager.isLCMOperationEnabled()) { - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), - this.getClass().getCanonicalName()); - throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); - } - - getAAIservice(); - validateInput(runtimeContext.getRequestContext()); - checkVNFWorkingState(runtimeContext); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - VNFContext vnfContext = queryAAI(vnfId); - runtimeContext.setVnfContext(vnfContext); - - queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction()); - VNFOperation operation = runtimeContext.getRequestContext().getAction(); - if(!operation.isBuiltIn()) { - // for built-in operations skip WF presence check - queryWFM(vnfContext, runtimeContext.getRequestContext()); - } - } - - - private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to queryLCM with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+ - ", command = "+ ObjectUtils.toString(action)); - } - - String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name()); - if (logger.isDebugEnabled()) { - logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")"); - } - return nextState; - } - - - private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext())); - } - boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce(); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - if (logger.isDebugEnabled()) { - logger.debug("forceFlag = " + forceFlag); - } - boolean isVNFStable = workingStateManager.isVNFStable(vnfId); - if (!isVNFStable && !forceFlag) { - if (logger.isDebugEnabled()) { - logger.debug("VNF is not stable for VNF ID = " + vnfId); - } - throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); - } - - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java deleted file mode 100644 index 7e3917313..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; - -public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{ - - protected void handleRequest(RuntimeContext runtimeContext) { - runtimeContext.setIsLockAcquired(false); - callWfOperation(runtimeContext); - } - - @Override - public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { - - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java deleted file mode 100644 index 79f83fbc6..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.i18n.Msg; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.exceptions.*; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl { - - @Override - public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException { - if(!lcmStateManager.isLCMOperationEnabled()) { - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), - this.getClass().getCanonicalName()); - throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); - } - - getAAIservice(); - super.validateInput(runtimeContext.getRequestContext()); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - VNFContext vnfContext = queryAAI(vnfId); - runtimeContext.setVnfContext(vnfContext); - - VNFOperation operation = runtimeContext.getRequestContext().getAction(); - if(supportedVMLevelAction().contains(operation)) { - queryWFM(vnfContext, runtimeContext.getRequestContext()); - } - else{ - throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level"); - } - } - - public Set supportedVMLevelAction(){ - Set vnfOperations = new HashSet<>(); - vnfOperations.add(VNFOperation.Start); - vnfOperations.add(VNFOperation.Stop); - vnfOperations.add(VNFOperation.Restart); - vnfOperations.add(VNFOperation.Rebuild); - vnfOperations.add(VNFOperation.Terminate); - vnfOperations.add(VNFOperation.Migrate); - vnfOperations.add(VNFOperation.Evacuate); - vnfOperations.add(VNFOperation.Snapshot); - return vnfOperations; - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java deleted file mode 100644 index e9b3d0f3a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager; - -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; - - -public interface WorkingStateManager { - - /** - * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. - * @param vnfId vnf Id to be verified for stable state - * @return True if vnf Exists and state is STABLE else False. - */ - public boolean isVNFStable(String vnfId); - - /** - * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or - * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. - * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. - * @param vnfId vnf Id to be updated - * @param workingState new working state - * @param ownerId - * @param forceFlag - force to update also on case given onwerId is different then the registered one - */ - public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag); - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java deleted file mode 100644 index 041cf7e84..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - -import java.sql.Connection; - -import org.onap.appc.dao.util.JdbcConnectionFactory; -import org.onap.appc.workingstatemanager.WorkingStateManager; - -public abstract class JdbcWorkingStateManager implements WorkingStateManager { - - private JdbcConnectionFactory connectionFactory; - - public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } - - protected Connection openDbConnection() { - return connectionFactory.openDbConnection(); - } - - protected void closeDbConnection(Connection connection) { - connectionFactory.closeDbConnection(connection); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java deleted file mode 100644 index 206d57229..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - - -public class RequestHandlerMessages { - public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; - public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java deleted file mode 100644 index e2fb3f298..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java +++ /dev/null @@ -1,231 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.message.RequestHandlerMessages; -import org.onap.appc.util.MessageFormatter; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import org.onap.appc.workingstatemanager.objects.VnfWorkingStateDto; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang3.StringUtils; - - -public class WorkingStateManagerImpl extends JdbcWorkingStateManager { - - private static final String SQL_RETRIEVE_VNF_STATE_MANAGEMENT = "SELECT VNF_ID,STATE,OWNER_ID,UPDATED,VER FROM VNF_STATE_MANAGEMENT WHERE VNF_ID=?"; - private static final String SQL_INSERT_VNF_STATE_MANAGEMENT = "INSERT IGNORE INTO VNF_STATE_MANAGEMENT (VNF_ID,STATE,OWNER_ID,UPDATED,VER) VALUES (?, ?, ?, ?, ?)"; - private static final String SQL_UPDATE_VNF_STATE_MANAGEMENT = "UPDATE VNF_STATE_MANAGEMENT SET OWNER_ID=?, UPDATED=?, STATE=?, VER=? WHERE VNF_ID=? AND VER=?"; - private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; - private static int maxAttempts = ConfigurationFactory.getConfiguration().getIntegerProperty("org.onap.appc.workingstatemanager.maxAttempts",20); - - private static Map workingStateMap = new ConcurrentHashMap<>(); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkingStateManagerImpl.class); - - - /** - * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. - * @param vnfId vnf Id to be verified for stable state - * @return True if vnf Exists and state is STABLE else False. - */ - @Override - public boolean isVNFStable(String vnfId){ - if (logger.isTraceEnabled()) { - logger.trace("Entering to isVNFStable with vnfId = "+ vnfId); - } - Connection connection = null; - boolean vnfStable = false; - try { - connection = openDbConnection(); - VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); - vnfStable = isVNFStable(vnfWorkingStateDto); - } catch (SQLException e) { - String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); - throw new RuntimeException(errMsg); - } finally { - if(connection != null) { - closeDbConnection(connection); - } - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isVNFStable for vnfId = "+ vnfId+" with Result = "+vnfStable); - } - return vnfStable; - } - - /** - * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or - * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. - * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. - * @param vnfId vnf Id to be updated - * @param workingState new working state - * @param ownerId - * @param forceFlag - force to update also on case given onwerId is different then the registered one - */ - @Override - public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag){ - boolean updated = false; - if (logger.isTraceEnabled()) { - logger.trace("Entering to setWorkingState with vnfId = "+ ObjectUtils.toString(vnfId)+ ", VNFWorkingState = " + workingState.name() + ", ownerId = "+ownerId+", forceFlag = "+forceFlag); - } - Connection connection = null; - try { - connection = openDbConnection(); - updated = setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag, maxAttempts); - } catch (SQLException e) { - String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); - throw new RuntimeException(errMsg); - } finally { - if(connection != null) { - closeDbConnection(connection); - } - } - - logger.trace("setWorkingState exit with output updated = "+updated); - return updated; - } - - public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag, int maxAttempts) throws SQLException { - return setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,1,maxAttempts); - } - public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag,int attempt, int maxAttempts) throws SQLException { - boolean updated = false; - VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); - Long currentVersion = vnfWorkingStateDto != null ? vnfWorkingStateDto.getVer() : null; - if(forceFlag || isVNFStable(vnfWorkingStateDto) || - ( vnfWorkingStateDto != null && vnfWorkingStateDto.getOwnerId().equals(ownerId)) ) { - updated = storeWorkingStateIfSameVersion(connection, vnfId, workingState, ownerId, currentVersion); - - Params params = new Params().addParam("vnfId", vnfId).addParam("workingState",workingState.name()) - .addParam("attempt",attempt).addParam("maxAttempts",maxAttempts).addParam("ownerId",ownerId).addParam("forceFlag",forceFlag); - String logMessage; - if(updated) { - logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_UPDATED, params.getParams()); - }else { - logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_WAS_NOT_UPDATED, params.getParams()); - } - logger.debug(logMessage); - if(!updated && attempt= Long.MAX_VALUE) ? 1 : (currentVer + 1); - statement.setString(1, ownerId); - statement.setLong(2, getCurrentTime(connection)); - statement.setString(3, state); - statement.setLong(4, newVer); - statement.setString(5, vnfId); - statement.setLong(6, currentVer); - return (statement.executeUpdate() != 0); - } - } - - protected VnfWorkingStateDto retrieveVnfWorkingState(Connection connection, String vnfId) throws SQLException { - VnfWorkingStateDto res = null; - - try(PreparedStatement statement = connection.prepareStatement(SQL_RETRIEVE_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER - statement.setString(1, vnfId); - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = new VnfWorkingStateDto(vnfId); - String stateString = resultSet.getString(2); - VNFWorkingState vnfWorkingState = VNFWorkingState.valueOf(stateString); - res.setState(vnfWorkingState); - res.setOwnerId(resultSet.getString(3)); - res.setUpdated(resultSet.getLong(4)); - res.setVer(resultSet.getLong(5)); - } - } - } - return res; - } - - private long getCurrentTime(Connection connection) throws SQLException { - long res = -1; - if(connection != null) { - try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = resultSet.getTimestamp(1).getTime(); - } - } - } - } - if(res == -1) { - res = System.currentTimeMillis(); - } - return res; - } - - protected boolean addVnfWorkingStateIfNotExists(Connection connection, String vnfId, String ownerId, String state) throws SQLException { - boolean added = false; - try(PreparedStatement statement = connection.prepareStatement(SQL_INSERT_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER - statement.setString(1, vnfId); - statement.setString(2, state); - statement.setString(3, ownerId); - statement.setLong(4, getCurrentTime(connection)); - statement.setLong(5, 1L); - int rowCount = statement.executeUpdate(); - added = rowCount != 0 ? true : false; - } - return added; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java deleted file mode 100644 index 9c638de20..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.objects; - - -public enum VNFWorkingState { - STABLE,UNSTABLE,UNKNOWN; - public String toString(){ - return this.name(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java deleted file mode 100644 index 948d4ca59..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.objects; - - -public class VnfWorkingStateDto { - private String vnfId; - private VNFWorkingState state; - private String ownerId; - private long updated; - private long ver; - - public VnfWorkingStateDto() { - } - - public VnfWorkingStateDto(String vnfId) { - this.vnfId = vnfId; - } - - public String getVnfId() { - return vnfId; - } - - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - public VNFWorkingState getState() { - return state; - } - - public void setState(VNFWorkingState state) { - this.state = state; - } - - public String getOwnerId() { - return ownerId; - } - - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - - public long getUpdated() { - return updated; - } - - public void setUpdated(long updated) { - this.updated = updated; - } - - public long getVer() { - return ver; - } - - public void setVer(long ver) { - this.ver = ver; - } - - - @Override - public String toString() { - return "VnfWorkingStateDto{" + - "vnfId='" + vnfId + '\'' + - ", state=" + state + - ", ownerId='" + ownerId + '\'' + - ", updated=" + updated + - ", ver=" + ver + - '}'; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..9bf3b6c1a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,49 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HLDR-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + +org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +# +# This needs to be changed so that the action can be appended to the end of the URL path +# +#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider:topology-service +#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider: +org.onap.appc.workingstatemanager.maxAttempts=20 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 9bf3b6c1a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,49 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HLDR-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - -org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -# -# This needs to be changed so that the action can be appended to the end of the URL path -# -#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider:topology-service -#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider: -org.onap.appc.workingstatemanager.maxAttempts=20 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java new file mode 100644 index 000000000..95146fbfa --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.requesthandler.impl.LCMStateManagerImpl; + +public class LCMStateManagerImplTest { + + LCMStateManager lcmStateManager; + + @Before + public void init() throws Exception { + lcmStateManager = new LCMStateManagerImpl(); + } + + /** + * Test to check the disable LCM operations method + */ + @Test + public void disableLCMOperations() throws Exception { + lcmStateManager.disableLCMOperations(); + Assert.assertFalse(lcmStateManager.isLCMOperationEnabled()); + } + + /** + * Test to check the enable LCM operations method + */ + @Test + public void enableLCMOperations() throws Exception { + lcmStateManager.enableLCMOperations(); + Assert.assertTrue(lcmStateManager.isLCMOperationEnabled()); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java new file mode 100644 index 000000000..9339931e8 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java @@ -0,0 +1,570 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.impl.RequestHandlerImpl; +import org.onap.appc.requesthandler.impl.RequestValidatorImpl; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Instant; +import java.util.UUID; + +import static junit.framework.TestCase.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.*; + +@SuppressWarnings("unchecked") +@RunWith(PowerMockRunner.class) +@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class, + RequestValidatorImpl.class, TransactionRecorder.class}) +public class RequestValidatorTest { + private final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); + + private RequestValidatorImpl requestValidator; + + private AAIService aaiAdapter ; + private LifecycleManager lifecyclemanager; + private WorkFlowManager workflowManager; + private WorkingStateManager workingStateManager ; + private LCMStateManager lcmStateManager; + + private final BundleContext bundleContext= Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + @Before + public void init() throws Exception { + // *** + AAIService aaiService = Mockito.mock(AAIService.class); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService); + PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(), + anyObject())).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + SvcLogicContext ctx =(SvcLogicContext)args[6]; + String prefix = (String)args[4]; + String key = (String)args[3]; + if(key.contains("'28'")){ + return SvcLogicResource.QueryStatus.FAILURE ; + }else if ( key.contains("'8'")) { + return SvcLogicResource.QueryStatus.NOT_FOUND ; + }else { + ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); + ctx.setAttribute(prefix + ".orchestration-status", "Instantiated"); + } + return SvcLogicResource.QueryStatus.SUCCESS ; + }); + PowerMockito.when(aaiService.update(anyString(),anyString(), anyObject(),anyString(), anyObject())) + .thenReturn(SvcLogicResource.QueryStatus.SUCCESS); + // *** + + aaiAdapter = Mockito.mock(AAIService.class); + lifecyclemanager= Mockito.mock(LifecycleManager.class); + workflowManager= Mockito.mock(WorkFlowManager.class); + workingStateManager = Mockito.mock(WorkingStateManager.class); + lcmStateManager = Mockito.mock(LCMStateManager.class); + + requestValidator = new RequestValidatorImpl(); + requestValidator.setWorkflowManager(workflowManager); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestValidator.setWorkingStateManager(workingStateManager); + requestValidator.setLcmStateManager(lcmStateManager); + + Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); + } + + public AAIService getAaiadapter() { + return this.aaiAdapter; + } + + private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, + boolean force, String originatorId, String requestId, + String subRequestId, Instant timeStamp){ + String API_VERSION= "2.0.0"; + RequestHandlerInput input = new RequestHandlerInput(); + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + RequestContext requestContext = runtimeContext.getRequestContext(); + input.setRequestContext(requestContext); + requestContext.getActionIdentifiers().setVnfId(vnfID); + requestContext.setAction(action); + if (action != null) { + input.setRpcName(convertActionNameToUrl(action.name())); + } else{ + input.setRpcName(null); + } + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestId); + requestContext.getCommonHeader().setOriginatorId(originatorId); + requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); + requestContext.getCommonHeader().getTimeStamp(); + requestContext.getCommonHeader().setApiVer(API_VERSION); + requestContext.getCommonHeader().setTimestamp(timeStamp); + return input; + } + + @Test + public void testNullVnfID() throws Exception { + logger.debug("=====================testNullVnfID============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30, + false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullVnfID============================="); + } + + @Test + public void testPositiveFlowWithConfigure() throws Exception { + logger.debug("=====================testPositiveFlowWithConfigure============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); + RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNull(ex); + logger.debug("testPositiveFlowWithConfigure"); + logger.debug("=====================testPositiveFlowWithConfigure============================="); + } + + @Test + public void testVnfNotFound() throws Exception { + logger.debug("=====================testVnfNotFound============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testVnfNotFound============================="); + } + + @Test + public void testNullCommand() throws Exception { + logger.debug("=====================testNullCommand============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("7", null,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullCommand============================="); + } + + @Test + public void testNullVnfIDAndCommand() throws Exception { + logger.debug("=====================testNullVnfIDAndCommand============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput(null, null,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullVnfIDAndCommand============================="); + } + + @Test + public void testWorkflowNotFound() throws Exception { + logger.debug("=====================testWorkflowNotFound============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(false,false)); + RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testWorkflowNotFound============================="); + } + + @Test + public void testUnstableVnfWithConfigure() throws Exception { + logger.debug("=====================testUnstableVnfWithConfigure============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("11", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithConfigure============================="); + } + + @Test + public void testUnstableVnfWithTest() throws Exception { + logger.debug("=====================testUnstableVnfWithTest============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + RequestHandlerInput input = this.getRequestHandlerInput("12", VNFOperation.Test,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithTest============================="); + } + + @Test + public void testUnstableVnfWithStart() throws Exception { + logger.debug("=====================testUnstableVnfWithStart============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("13", VNFOperation.Start,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithStart============================="); + } + + @Test + public void testUnstableVnfWithTerminate() throws Exception { + logger.debug("=====================testUnstableVnfWithTerminate============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + RequestHandlerInput input = this.getRequestHandlerInput("14", VNFOperation.Terminate,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithTerminate============================="); + } + + @Test + public void testUnstableVnfWithRestart() throws Exception { + logger.debug("=====================testUnstableVnfWithRestart============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("26", VNFOperation.Restart,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithRestart============================="); + } + + @Test + public void testUnstableVnfWithRebuild() throws Exception { + logger.debug("=====================testUnstableVnfWithRebuild============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("27", VNFOperation.Rebuild,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithRebuild============================="); + } + + @Test + public void testAAIDown() throws Exception { + logger.debug("=====================testAAIDown============================="); + RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testAAIDown============================="); + } + + @Test + public void testNegativeFlowWithTimeStamp() throws Exception { + logger.debug("=====================testNegativeFlowWithTimeStamp============================="); + Instant now = Instant.now(); + Instant past = now.minusMillis(1000000); + RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(),past); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("testNegativeFlowWithTimeStamp"); + logger.debug("=====================testNegativeFlowWithTimeStamp============================="); + } + + @Test + public void rejectDuplicateRequest() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true); + RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); + + RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + RuntimeContext runtimeContext1 = putInputToRuntimeContext(input1); + + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNull(ex); + + try { + requestValidator.validateRequest(runtimeContext1); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + } + + @Test + public void testLockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Lock); + } + + @Test + public void testUnlockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Unlock); + } + + @Test + public void testCheckLockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.CheckLock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Lock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testUnlockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Unlock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testCheckLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.CheckLock); + } + + @Test(expected = LCMOperationsDisabledException.class) + public void testLCMOperationsDisabled() throws Exception { + Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false); + testOperation("no-matter", VNFOperation.Configure); + } + private void testOperation(String resource, VNFOperation operation) throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, + requestID, subRequestID, Instant.now()); + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + requestValidator.validateRequest(runtimeContext); + } + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + ResponseContext responseContext = createResponseContextWithSuObjects(); + runtimeContext.setResponseContext(responseContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } + + private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) { + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + runtimeContext.setRequestContext(input.getRequestContext()); + runtimeContext.setRpcName(input.getRpcName()); + runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId()); + return runtimeContext; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java new file mode 100644 index 000000000..a65af669b --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java @@ -0,0 +1,372 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.requesthandler.conv.Converter; + +import java.text.ParseException; +import java.time.Instant; +import java.util.Date; +import java.util.HashMap; + + +public class TestConverter { + private String expectedJsonBodyStr ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; + private String expectedDmaapOutgoingMessageJsonStringTest ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"test\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringRollback ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"rollback\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSnapshot ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"snapshot\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringAudit ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"audit\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringHealthCheck ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"health-check\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringLiveUpgrade ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"live-upgrade\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringLock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"lock\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringModifyConfig ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"config-modify\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSoftwareUpload ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"software-upload\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringStop ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"stop\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSync ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"sync\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringTerminate ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"terminate\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringUnlock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"unlock\",\"type\":\"response\"}"; + private String expectedJsonBodyStrwithPayload ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; + + @Test + public void convDateToZuluStringTest(){ + String dateToZuluString = Converter.convDateToZuluString(new Date(0L)); + Assert.assertEquals("1970-01-01T00:00:00.000Z", dateToZuluString); + } + + @Test + public void convAsyncResponseToBuilderTestTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Test; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTestTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Test; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTest,jsonStr); + } + + @Test + public void convPayloadObjectToJsonStringTest() throws JsonProcessingException, ParseException { + String jsonString = Converter.convPayloadObjectToJsonString("any valid JSON string value"); + Assert.assertEquals("any valid JSON string value", jsonString); + + HashMap hashMap = new HashMap<>(); + hashMap.put("key","value"); + jsonString = Converter.convPayloadObjectToJsonString(hashMap); + Assert.assertEquals("{\"key\":\"value\"}", jsonString); + } + + @Test + public void convAsyncResponseToBuilderRollbackTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Rollback; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringRollbackTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Rollback; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringRollback,jsonStr); + } + + @Test + public void convAsyncResponseToBuilderSnapshotTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Snapshot; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSnapshotTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Snapshot; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSnapshot,jsonStr); + } + @Test + public void convAsyncResponseToBuilderAuditTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Audit; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringAuditTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Audit; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringAudit,jsonStr); + } + @Test + public void convAsyncResponseToBuilderHealthCheckTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.HealthCheck; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringHealthCheckTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.HealthCheck; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringHealthCheck,jsonStr); + } + @Test + public void convAsyncResponseToBuilderLiveUpgradeTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.LiveUpgrade; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringLiveUpgradeTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.LiveUpgrade; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLiveUpgrade,jsonStr); + } + @Test + public void convAsyncResponseToBuilderLockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Lock; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringLockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Lock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLock,jsonStr); + } + @Test + public void convAsyncResponseToBuilderModifyConfigTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.ConfigModify; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringModifyConfigTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.ConfigModify; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringModifyConfig,jsonStr); + } + @Test + public void convAsyncResponseToBuilderSoftwareUploadTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.SoftwareUpload; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSoftwareUploadTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.SoftwareUpload; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSoftwareUpload,jsonStr); + } + @Test + public void convAsyncResponseToBuilderStopTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Stop; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringStopTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Stop; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringStop,jsonStr); + } + @Test + public void convAsyncResponseToBuilderSync() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSync() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSync,jsonStr); + } + @Test + public void convAsyncResponseToBuilderTerminateTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTerminateTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Terminate; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTerminate,jsonStr); + } + @Test + public void convAsyncResponseToBuilderUnlockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Unlock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringUnlockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Unlock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringUnlock,jsonStr); + } + /*@Test + public void convAsyncResponseToBuilderTest() throws JsonProcessingException { + AsyncResponse asyncResponse = buildAsyncResponse(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTest() throws JsonProcessingException { + AsyncResponse asyncResponse = buildAsyncResponse(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonString,jsonStr); + }*/ + + + private ResponseContext buildAsyncResponse() { + ResponseContext asyncResponse = createResponseContextWithSubObjects(); + asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + asyncResponse.getCommonHeader().setOriginatorId("oid"); + asyncResponse.getCommonHeader().setApiVer("2.0.0"); + asyncResponse.getCommonHeader().setRequestId("reqid"); + asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); + asyncResponse.setPayload("any valid JSON string value. Json escape characters need to be added to make it a valid json string value"); + return asyncResponse; + } + + private ResponseContext buildAsyncResponsewithPayload() { + ResponseContext asyncResponse = createResponseContextWithSubObjects(); + asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + asyncResponse.getCommonHeader().setOriginatorId("oid"); + asyncResponse.getCommonHeader().setApiVer("2.0.0"); + asyncResponse.getCommonHeader().setRequestId("reqid"); + asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); + asyncResponse.setPayload("{}"); + return asyncResponse; + } + + private ResponseContext createResponseContextWithSubObjects() { + + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } + + +} + + + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java new file mode 100644 index 000000000..dfb45389d --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java @@ -0,0 +1,649 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.time.Instant; +import java.util.HashMap; +import java.util.UUID; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.domainmodel.lcm.Flags.Mode; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.CommandExecutor; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.messageadapter.impl.MessageAdapterImpl; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; +import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.RequestExpiredException; +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; +import org.onap.appc.requesthandler.impl.RequestHandlerImpl; +import org.onap.appc.requesthandler.impl.RequestValidatorImpl; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.transactionrecorder.objects.TransactionRecord; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@Ignore +@RunWith(PowerMockRunner.class) +@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class, MessageAdapterImpl.class}) +public class TestRequestHandler { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); + + private RequestHandlerImpl requestHandler; + private RequestValidatorImpl requestValidator; + private WorkFlowManager workflowManager; + private WorkingStateManager workingStateManager ; + private LockManager lockManager; + private Configuration configuration; + + private final BundleContext bundleContext=Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + MessageAdapterFactory factory = new DmaapMessageAdapterFactoryImpl(); + + + @Before + public void init() throws Exception { + configuration = ConfigurationFactory.getConfiguration(); + + configuration.setProperty("appc.LCM.topic.write" , "TEST"); + configuration.setProperty("appc.LCM.client.key" , "TEST"); + configuration.setProperty("appc.LCM.client.secret" , "TEST"); + + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(MessageAdapterImpl.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(factory); + + + requestHandler = new RequestHandlerImpl(); + LifecycleManager lifecyclemanager= mock(LifecycleManager.class); + workflowManager= mock(WorkFlowManager.class); + CommandExecutor commandExecutor= mock(CommandExecutor.class); + MessageAdapter messageAdapter = mock(MessageAdapter.class); + workingStateManager = mock(WorkingStateManager.class); + lockManager = mock(LockManager.class); + TransactionRecorder transactionRecorder= mock(TransactionRecorder.class); + + requestHandler.setWorkingStateManager(workingStateManager); + requestHandler.setMessageAdapter(messageAdapter); + requestValidator = mock(RequestValidatorImpl.class); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestValidator.setWorkingStateManager(workingStateManager); + requestValidator.setWorkflowManager(workflowManager); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestHandler.setCommandExecutor(commandExecutor); + requestHandler.setRequestValidator(requestValidator); + requestHandler.setLockManager(lockManager); + requestHandler.setTransactionRecorder(transactionRecorder); + + doNothing().when(transactionRecorder).store((TransactionRecord) anyObject()); +// Mockito.when(commandExecutor.executeCommand((CommandExecutorInput)anyObject())).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); + for(Integer i=130; i<=140 ; i++) + { + Mockito.when(workingStateManager.isVNFStable(i.toString())).thenReturn(true); + } + Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("40")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("38")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("201")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("202")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("302")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("303")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("310")).thenReturn(true).thenReturn(true); + } + + private void threadSleep(){ + try { + Thread.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test + public void testNegativeFlowWithRequestingUsedVnfId() throws Exception { + logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("131", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + threadSleep (); + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + logger.debug("testNegativeFlowWithRequestingUsedVnfId"); + logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); + } + + @Test + public void testInvalidVNFExceptionRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testLifecycleException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new LifecycleException(new Exception(),"Configured","test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.INVALID_VNF_STATE.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + + @Test + public void testRequestExpiredException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new RequestExpiredException("")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.EXPIRED_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testMissingVNFdata() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID,Instant.now()); + PowerMockito.doThrow(new MissingVNFDataInAAIException("vnf-type")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testWorkflowNotFoundException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new WorkflowNotFoundException("Unable to find the DG","VNF-2.0.0.0", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode());} + + @Test + public void testDGWorkflowNotFoundException() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest) anyObject())).thenReturn(new WorkflowExistsOutput(true, true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0, false, originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new DGWorkflowNotFoundException("Unable to find the DG", "VNF-2.0.0.0", "temp", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testInvalidInputException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID1 = UUID.randomUUID().toString(); + String requestID1 = UUID.randomUUID().toString(); + String subRequestID1 = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID1, requestID1, subRequestID1, Instant.now()); + PowerMockito.doThrow(new InvalidInputException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + } + + @Test + public void testNoTransitionDefinedException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3010", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new NoTransitionDefinedException("Invalid VNF State","Unstable","Test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.NO_TRANSITION_DEFINE.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void rejectInvalidRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testUnstableWorkingState() throws Exception { + logger.debug("=====================testUnstableWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("37")).thenReturn(true,false); + RequestHandlerInput input = this.getRequestHandlerInput("37", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input); + RequestHandlerOutput output = requestHandler.handleRequest(input); + + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RequestHandlerInput input1 = this.getRequestHandlerInput("37", VNFOperation.Configure,1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + logger.debug("=====================testUnstableWorkingState============================="); + } + + @Test + public void testOnRequestExecutionEndSuccessForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"137", "", "", ""),true); + + input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); + } + + private void mockRuntimeContextAndVnfContext(RequestHandlerInput input1) throws Exception { + RuntimeContext runtimeContext = PowerMockito.mock(RuntimeContext.class); + VNFContext vnfContext = new VNFContext(); + vnfContext.setType("SCP"); + vnfContext.setId("137"); + when(runtimeContext.getVnfContext()).thenReturn(vnfContext); + when(runtimeContext.getRequestContext()).thenReturn(input1.getRequestContext()); + when(runtimeContext.getRpcName()).thenReturn(input1.getRpcName()); + + + ResponseContext responseContext = new ResponseContext(); + responseContext.setStatus(new Status(0, null)); + responseContext.setAdditionalContext(new HashMap(4)); + responseContext.setCommonHeader(input1.getRequestContext().getCommonHeader()); + runtimeContext.setResponseContext(responseContext); + when(runtimeContext.getResponseContext()).thenReturn(responseContext); + responseContext.setStatus(new Status(0, null)); + runtimeContext.setResponseContext(responseContext); + PowerMockito.whenNew(RuntimeContext.class).withAnyArguments().thenReturn(runtimeContext); + + } + + @Test + public void testOnRequestExecutionEndFailureForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.NO_TRANSITION_DEFINE,"38", "", "", ""),true); + + input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); + + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + } + + @Test + public void testOnRequestExecutionEndTTLExpiredForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input1); + + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + } + + @Test + public void testOnRequestTTLEndForWorkingState() throws Exception { + logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.EXPIRED_REQUEST_FAILURE,"40", "", "", ""); + requestHandler.onRequestTTLEnd(response,true); + input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); + } + + @Test + public void testForceCommandExecution() throws Exception { + logger.debug("=====================testForceCommandExecution============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.ACCEPTED,"138", "", "", ""); + requestHandler.onRequestTTLEnd(response,true); + input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + input1.getRequestContext().getCommonHeader().setFlags(new Flags(null, true, 1200)); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testForceCommandExecution============================="); + } + + @Test + public void testOnRequestExecutionEndSuccess() throws VNFNotFoundException { + logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Starts ============================="); + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"201", "", "", ""),true); + logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Ends ============================="); + } + + @Test + public void testOnRequestExecutionEndFailure() throws VNFNotFoundException { + logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Starts ============================="); + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.DG_FAILURE,"202", "", "", ""),true); + logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Ends ============================="); + } + + private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, boolean force,String originatorId, String requestId, String subRequestId, Instant timeStamp){ + String API_VERSION= "2.0.0"; + RequestHandlerInput input = new RequestHandlerInput(); + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + RequestContext requestContext = runtimeContext.getRequestContext(); + input.setRequestContext(requestContext); + requestContext.getActionIdentifiers().setVnfId(vnfID); + requestContext.setAction(action); + input.setRpcName(convertActionNameToUrl(action.name())); + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestId); + requestContext.getCommonHeader().setOriginatorId(originatorId); + requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); + requestContext.getCommonHeader().setTimestamp(timeStamp); + requestContext.getCommonHeader().setApiVer(API_VERSION); + return input; + } + + private RuntimeContext getAsyncResponse(boolean wfStatus, LCMCommandStatus commandStatus, String vnfId, String originatorId, String requestId, String subRequestId) + { + RuntimeContext output = createRuntimeContextWithSubObjects(); + + + output.getRequestContext().getActionIdentifiers().setVnfId(vnfId); + output.getVnfContext().setId(vnfId); + output.getResponseContext().getCommonHeader().setApiVer("2.0.0"); + output.getResponseContext().getCommonHeader().setTimestamp( Instant.now()); + output.getResponseContext().setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + output.setTimeStart( Instant.now()); + output.getResponseContext().getCommonHeader().setOriginatorId(originatorId); + output.getResponseContext().getCommonHeader().setRequestId(requestId); + output.getResponseContext().getCommonHeader().setSubRequestId(subRequestId); + + output.getVnfContext().setType("FIREWALL"); + output.getRequestContext().setAction(VNFOperation.Configure); + output.setRpcName("configure"); + output.getResponseContext().setPayload(""); + return output; + } + + @Test + public void rejectDuplicateRequest() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + input = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + + PowerMockito.doThrow(new DuplicateRequestException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.DUPLICATE_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void removeRequestFromRegistryOnRequestCompletion() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("302", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"302",originatorID,requestID,subRequestID); + requestHandler.onRequestExecutionEnd(asyncResponse,true); + + input = this.getRequestHandlerInput("310", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void removeRequestFromRegistryOnTTLExpiration() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("303", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.ACCEPTED,"303",originatorID,requestID,subRequestID); + requestHandler.onRequestTTLEnd(asyncResponse,false); + + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + /*@Test + public void getMetricserviceTest() throws Exception{ + Method method = RequestHandlerImpl.class.getDeclaredMethod("getMetricservice", null); + method.setAccessible(true); + method.invoke(null, null); + + }*/ + @Test + public void onRequestExecutionStartTest() throws Exception{ + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionStart("303",false, null, true); + Assert.assertNotNull(requestHandler); + } + + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + ResponseContext responseContext = createResponseContextWithSuObjects(); + runtimeContext.setResponseContext(responseContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } +} + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java new file mode 100644 index 000000000..fc14f2ac9 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.dao.util.AppcJdbcConnectionFactory; +import org.onap.appc.workingstatemanager.impl.WorkingStateManagerImpl; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.UUID; + + + +public class TestWorkingStateManager { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestWorkingStateManager.class); + WorkingStateManagerImpl workingStateManager; + + @Before + public void init() throws Exception { + workingStateManager = new WorkingStateManagerImpl(); + AppcJdbcConnectionFactory appcJdbcConnectionFactory = new AppcJdbcConnectionFactory(); + String schema = "sdnctl"; + appcJdbcConnectionFactory.setSchema(schema); + workingStateManager.setConnectionFactory(appcJdbcConnectionFactory); + String property = ConfigurationFactory.getConfiguration().getProperty(String.format("org.onap.appc.db.url.%s", schema)); + logger.info(property+" will be used as connection URL to mySQL."); + logger.warn("you can set connection URL to other IP by adding -DmysqlIp= in VM Option"); +// System.getProperties().getProperty("mys") + } + + @Test + // this test run on mysql you need to uncomment Ignore and to add -DmysqlIp= in VM Option, to make that test pass successfully. + @Ignore + public void testUpdateWorkingState() { + String vnfId = UUID.randomUUID().toString(); + String myOwnerId = "myOwnerId"; + String otherOwnerId = "otherOwnerId"; + boolean vnfStable = workingStateManager.isVNFStable(vnfId); + logger.info("isVNFStable returns "+vnfStable+" for vnfId "+vnfId); + + //set to unstable with force true + boolean updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + + //negative test - try to set to any value by other ownerId when vnf state is UNSTABLE + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, otherOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, otherOwnerId, false); + Assert.assertFalse(updated); + + //positive test - set with same ownerId and force false + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertTrue(workingStateManager.isVNFStable(vnfId)); + + //positive test - set with otherOwnerId and force false when VNF is stable + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + + //negative test - try to set to any value by myOwnerId when vnf state is UNKNOWN + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); + Assert.assertFalse(updated); + + //positive test - try to set to any value by myOwnerId when vnf state is UNKNOWN but with force + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java deleted file mode 100644 index 95146fbfa..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.requesthandler.impl.LCMStateManagerImpl; - -public class LCMStateManagerImplTest { - - LCMStateManager lcmStateManager; - - @Before - public void init() throws Exception { - lcmStateManager = new LCMStateManagerImpl(); - } - - /** - * Test to check the disable LCM operations method - */ - @Test - public void disableLCMOperations() throws Exception { - lcmStateManager.disableLCMOperations(); - Assert.assertFalse(lcmStateManager.isLCMOperationEnabled()); - } - - /** - * Test to check the enable LCM operations method - */ - @Test - public void enableLCMOperations() throws Exception { - lcmStateManager.enableLCMOperations(); - Assert.assertTrue(lcmStateManager.isLCMOperationEnabled()); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java deleted file mode 100644 index 9339931e8..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java +++ /dev/null @@ -1,570 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; -import org.onap.appc.requesthandler.impl.RequestHandlerImpl; -import org.onap.appc.requesthandler.impl.RequestValidatorImpl; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.time.Instant; -import java.util.UUID; - -import static junit.framework.TestCase.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.*; - -@SuppressWarnings("unchecked") -@RunWith(PowerMockRunner.class) -@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class, - RequestValidatorImpl.class, TransactionRecorder.class}) -public class RequestValidatorTest { - private final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); - - private RequestValidatorImpl requestValidator; - - private AAIService aaiAdapter ; - private LifecycleManager lifecyclemanager; - private WorkFlowManager workflowManager; - private WorkingStateManager workingStateManager ; - private LCMStateManager lcmStateManager; - - private final BundleContext bundleContext= Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - @Before - public void init() throws Exception { - // *** - AAIService aaiService = Mockito.mock(AAIService.class); - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService); - PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(), - anyObject())).thenAnswer(invocation -> { - Object[] args = invocation.getArguments(); - SvcLogicContext ctx =(SvcLogicContext)args[6]; - String prefix = (String)args[4]; - String key = (String)args[3]; - if(key.contains("'28'")){ - return SvcLogicResource.QueryStatus.FAILURE ; - }else if ( key.contains("'8'")) { - return SvcLogicResource.QueryStatus.NOT_FOUND ; - }else { - ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); - ctx.setAttribute(prefix + ".orchestration-status", "Instantiated"); - } - return SvcLogicResource.QueryStatus.SUCCESS ; - }); - PowerMockito.when(aaiService.update(anyString(),anyString(), anyObject(),anyString(), anyObject())) - .thenReturn(SvcLogicResource.QueryStatus.SUCCESS); - // *** - - aaiAdapter = Mockito.mock(AAIService.class); - lifecyclemanager= Mockito.mock(LifecycleManager.class); - workflowManager= Mockito.mock(WorkFlowManager.class); - workingStateManager = Mockito.mock(WorkingStateManager.class); - lcmStateManager = Mockito.mock(LCMStateManager.class); - - requestValidator = new RequestValidatorImpl(); - requestValidator.setWorkflowManager(workflowManager); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestValidator.setWorkingStateManager(workingStateManager); - requestValidator.setLcmStateManager(lcmStateManager); - - Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); - } - - public AAIService getAaiadapter() { - return this.aaiAdapter; - } - - private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, - boolean force, String originatorId, String requestId, - String subRequestId, Instant timeStamp){ - String API_VERSION= "2.0.0"; - RequestHandlerInput input = new RequestHandlerInput(); - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - RequestContext requestContext = runtimeContext.getRequestContext(); - input.setRequestContext(requestContext); - requestContext.getActionIdentifiers().setVnfId(vnfID); - requestContext.setAction(action); - if (action != null) { - input.setRpcName(convertActionNameToUrl(action.name())); - } else{ - input.setRpcName(null); - } - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestId); - requestContext.getCommonHeader().setOriginatorId(originatorId); - requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); - requestContext.getCommonHeader().getTimeStamp(); - requestContext.getCommonHeader().setApiVer(API_VERSION); - requestContext.getCommonHeader().setTimestamp(timeStamp); - return input; - } - - @Test - public void testNullVnfID() throws Exception { - logger.debug("=====================testNullVnfID============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30, - false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullVnfID============================="); - } - - @Test - public void testPositiveFlowWithConfigure() throws Exception { - logger.debug("=====================testPositiveFlowWithConfigure============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); - RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNull(ex); - logger.debug("testPositiveFlowWithConfigure"); - logger.debug("=====================testPositiveFlowWithConfigure============================="); - } - - @Test - public void testVnfNotFound() throws Exception { - logger.debug("=====================testVnfNotFound============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testVnfNotFound============================="); - } - - @Test - public void testNullCommand() throws Exception { - logger.debug("=====================testNullCommand============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("7", null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullCommand============================="); - } - - @Test - public void testNullVnfIDAndCommand() throws Exception { - logger.debug("=====================testNullVnfIDAndCommand============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput(null, null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullVnfIDAndCommand============================="); - } - - @Test - public void testWorkflowNotFound() throws Exception { - logger.debug("=====================testWorkflowNotFound============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(false,false)); - RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testWorkflowNotFound============================="); - } - - @Test - public void testUnstableVnfWithConfigure() throws Exception { - logger.debug("=====================testUnstableVnfWithConfigure============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("11", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithConfigure============================="); - } - - @Test - public void testUnstableVnfWithTest() throws Exception { - logger.debug("=====================testUnstableVnfWithTest============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - RequestHandlerInput input = this.getRequestHandlerInput("12", VNFOperation.Test,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithTest============================="); - } - - @Test - public void testUnstableVnfWithStart() throws Exception { - logger.debug("=====================testUnstableVnfWithStart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("13", VNFOperation.Start,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithStart============================="); - } - - @Test - public void testUnstableVnfWithTerminate() throws Exception { - logger.debug("=====================testUnstableVnfWithTerminate============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - RequestHandlerInput input = this.getRequestHandlerInput("14", VNFOperation.Terminate,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithTerminate============================="); - } - - @Test - public void testUnstableVnfWithRestart() throws Exception { - logger.debug("=====================testUnstableVnfWithRestart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("26", VNFOperation.Restart,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithRestart============================="); - } - - @Test - public void testUnstableVnfWithRebuild() throws Exception { - logger.debug("=====================testUnstableVnfWithRebuild============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("27", VNFOperation.Rebuild,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithRebuild============================="); - } - - @Test - public void testAAIDown() throws Exception { - logger.debug("=====================testAAIDown============================="); - RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testAAIDown============================="); - } - - @Test - public void testNegativeFlowWithTimeStamp() throws Exception { - logger.debug("=====================testNegativeFlowWithTimeStamp============================="); - Instant now = Instant.now(); - Instant past = now.minusMillis(1000000); - RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(),past); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("testNegativeFlowWithTimeStamp"); - logger.debug("=====================testNegativeFlowWithTimeStamp============================="); - } - - @Test - public void rejectDuplicateRequest() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true); - RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false, - originatorID, requestID, subRequestID, Instant.now()); - - RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false, - originatorID, requestID, subRequestID, Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - RuntimeContext runtimeContext1 = putInputToRuntimeContext(input1); - - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNull(ex); - - try { - requestValidator.validateRequest(runtimeContext1); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - } - - @Test - public void testLockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Lock); - } - - @Test - public void testUnlockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Unlock); - } - - @Test - public void testCheckLockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.CheckLock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testLockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Lock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testUnlockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Unlock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testCheckLockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.CheckLock); - } - - @Test(expected = LCMOperationsDisabledException.class) - public void testLCMOperationsDisabled() throws Exception { - Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false); - testOperation("no-matter", VNFOperation.Configure); - } - private void testOperation(String resource, VNFOperation operation) throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, - requestID, subRequestID, Instant.now()); - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - requestValidator.validateRequest(runtimeContext); - } - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - ResponseContext responseContext = createResponseContextWithSuObjects(); - runtimeContext.setResponseContext(responseContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } - - private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) { - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - runtimeContext.setRequestContext(input.getRequestContext()); - runtimeContext.setRpcName(input.getRpcName()); - runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId()); - return runtimeContext; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java deleted file mode 100644 index a65af669b..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java +++ /dev/null @@ -1,372 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.requesthandler.conv.Converter; - -import java.text.ParseException; -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; - - -public class TestConverter { - private String expectedJsonBodyStr ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; - private String expectedDmaapOutgoingMessageJsonStringTest ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"test\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringRollback ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"rollback\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSnapshot ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"snapshot\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringAudit ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"audit\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringHealthCheck ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"health-check\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringLiveUpgrade ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"live-upgrade\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringLock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"lock\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringModifyConfig ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"config-modify\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSoftwareUpload ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"software-upload\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringStop ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"stop\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSync ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"sync\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringTerminate ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"terminate\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringUnlock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"unlock\",\"type\":\"response\"}"; - private String expectedJsonBodyStrwithPayload ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; - - @Test - public void convDateToZuluStringTest(){ - String dateToZuluString = Converter.convDateToZuluString(new Date(0L)); - Assert.assertEquals("1970-01-01T00:00:00.000Z", dateToZuluString); - } - - @Test - public void convAsyncResponseToBuilderTestTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Test; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTestTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Test; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTest,jsonStr); - } - - @Test - public void convPayloadObjectToJsonStringTest() throws JsonProcessingException, ParseException { - String jsonString = Converter.convPayloadObjectToJsonString("any valid JSON string value"); - Assert.assertEquals("any valid JSON string value", jsonString); - - HashMap hashMap = new HashMap<>(); - hashMap.put("key","value"); - jsonString = Converter.convPayloadObjectToJsonString(hashMap); - Assert.assertEquals("{\"key\":\"value\"}", jsonString); - } - - @Test - public void convAsyncResponseToBuilderRollbackTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Rollback; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringRollbackTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Rollback; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringRollback,jsonStr); - } - - @Test - public void convAsyncResponseToBuilderSnapshotTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Snapshot; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSnapshotTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Snapshot; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSnapshot,jsonStr); - } - @Test - public void convAsyncResponseToBuilderAuditTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Audit; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringAuditTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Audit; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringAudit,jsonStr); - } - @Test - public void convAsyncResponseToBuilderHealthCheckTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.HealthCheck; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringHealthCheckTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.HealthCheck; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringHealthCheck,jsonStr); - } - @Test - public void convAsyncResponseToBuilderLiveUpgradeTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.LiveUpgrade; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringLiveUpgradeTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.LiveUpgrade; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLiveUpgrade,jsonStr); - } - @Test - public void convAsyncResponseToBuilderLockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Lock; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringLockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Lock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLock,jsonStr); - } - @Test - public void convAsyncResponseToBuilderModifyConfigTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.ConfigModify; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringModifyConfigTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.ConfigModify; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringModifyConfig,jsonStr); - } - @Test - public void convAsyncResponseToBuilderSoftwareUploadTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.SoftwareUpload; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSoftwareUploadTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.SoftwareUpload; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSoftwareUpload,jsonStr); - } - @Test - public void convAsyncResponseToBuilderStopTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Stop; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringStopTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Stop; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringStop,jsonStr); - } - @Test - public void convAsyncResponseToBuilderSync() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSync() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSync,jsonStr); - } - @Test - public void convAsyncResponseToBuilderTerminateTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTerminateTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Terminate; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTerminate,jsonStr); - } - @Test - public void convAsyncResponseToBuilderUnlockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Unlock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringUnlockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Unlock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringUnlock,jsonStr); - } - /*@Test - public void convAsyncResponseToBuilderTest() throws JsonProcessingException { - AsyncResponse asyncResponse = buildAsyncResponse(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTest() throws JsonProcessingException { - AsyncResponse asyncResponse = buildAsyncResponse(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonString,jsonStr); - }*/ - - - private ResponseContext buildAsyncResponse() { - ResponseContext asyncResponse = createResponseContextWithSubObjects(); - asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - asyncResponse.getCommonHeader().setOriginatorId("oid"); - asyncResponse.getCommonHeader().setApiVer("2.0.0"); - asyncResponse.getCommonHeader().setRequestId("reqid"); - asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); - asyncResponse.setPayload("any valid JSON string value. Json escape characters need to be added to make it a valid json string value"); - return asyncResponse; - } - - private ResponseContext buildAsyncResponsewithPayload() { - ResponseContext asyncResponse = createResponseContextWithSubObjects(); - asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - asyncResponse.getCommonHeader().setOriginatorId("oid"); - asyncResponse.getCommonHeader().setApiVer("2.0.0"); - asyncResponse.getCommonHeader().setRequestId("reqid"); - asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); - asyncResponse.setPayload("{}"); - return asyncResponse; - } - - private ResponseContext createResponseContextWithSubObjects() { - - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } - - -} - - - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java deleted file mode 100644 index dfb45389d..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java +++ /dev/null @@ -1,649 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.time.Instant; -import java.util.HashMap; -import java.util.UUID; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.domainmodel.lcm.Flags.Mode; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.CommandExecutor; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.messageadapter.impl.MessageAdapterImpl; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; -import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.RequestExpiredException; -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; -import org.onap.appc.requesthandler.impl.RequestHandlerImpl; -import org.onap.appc.requesthandler.impl.RequestValidatorImpl; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.transactionrecorder.objects.TransactionRecord; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@Ignore -@RunWith(PowerMockRunner.class) -@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class, MessageAdapterImpl.class}) -public class TestRequestHandler { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); - - private RequestHandlerImpl requestHandler; - private RequestValidatorImpl requestValidator; - private WorkFlowManager workflowManager; - private WorkingStateManager workingStateManager ; - private LockManager lockManager; - private Configuration configuration; - - private final BundleContext bundleContext=Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - MessageAdapterFactory factory = new DmaapMessageAdapterFactoryImpl(); - - - @Before - public void init() throws Exception { - configuration = ConfigurationFactory.getConfiguration(); - - configuration.setProperty("appc.LCM.topic.write" , "TEST"); - configuration.setProperty("appc.LCM.client.key" , "TEST"); - configuration.setProperty("appc.LCM.client.secret" , "TEST"); - - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(MessageAdapterImpl.class)).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(factory); - - - requestHandler = new RequestHandlerImpl(); - LifecycleManager lifecyclemanager= mock(LifecycleManager.class); - workflowManager= mock(WorkFlowManager.class); - CommandExecutor commandExecutor= mock(CommandExecutor.class); - MessageAdapter messageAdapter = mock(MessageAdapter.class); - workingStateManager = mock(WorkingStateManager.class); - lockManager = mock(LockManager.class); - TransactionRecorder transactionRecorder= mock(TransactionRecorder.class); - - requestHandler.setWorkingStateManager(workingStateManager); - requestHandler.setMessageAdapter(messageAdapter); - requestValidator = mock(RequestValidatorImpl.class); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestValidator.setWorkingStateManager(workingStateManager); - requestValidator.setWorkflowManager(workflowManager); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestHandler.setCommandExecutor(commandExecutor); - requestHandler.setRequestValidator(requestValidator); - requestHandler.setLockManager(lockManager); - requestHandler.setTransactionRecorder(transactionRecorder); - - doNothing().when(transactionRecorder).store((TransactionRecord) anyObject()); -// Mockito.when(commandExecutor.executeCommand((CommandExecutorInput)anyObject())).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - for(Integer i=130; i<=140 ; i++) - { - Mockito.when(workingStateManager.isVNFStable(i.toString())).thenReturn(true); - } - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("40")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("38")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("201")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("202")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("302")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("303")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("310")).thenReturn(true).thenReturn(true); - } - - private void threadSleep(){ - try { - Thread.sleep(5); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Test - public void testNegativeFlowWithRequestingUsedVnfId() throws Exception { - logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("131", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - threadSleep (); - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - logger.debug("testNegativeFlowWithRequestingUsedVnfId"); - logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); - } - - @Test - public void testInvalidVNFExceptionRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testLifecycleException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new LifecycleException(new Exception(),"Configured","test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.INVALID_VNF_STATE.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - - @Test - public void testRequestExpiredException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new RequestExpiredException("")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.EXPIRED_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testMissingVNFdata() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID,Instant.now()); - PowerMockito.doThrow(new MissingVNFDataInAAIException("vnf-type")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testWorkflowNotFoundException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new WorkflowNotFoundException("Unable to find the DG","VNF-2.0.0.0", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode());} - - @Test - public void testDGWorkflowNotFoundException() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest) anyObject())).thenReturn(new WorkflowExistsOutput(true, true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0, false, originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new DGWorkflowNotFoundException("Unable to find the DG", "VNF-2.0.0.0", "temp", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testInvalidInputException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID1 = UUID.randomUUID().toString(); - String requestID1 = UUID.randomUUID().toString(); - String subRequestID1 = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID1, requestID1, subRequestID1, Instant.now()); - PowerMockito.doThrow(new InvalidInputException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - } - - @Test - public void testNoTransitionDefinedException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3010", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new NoTransitionDefinedException("Invalid VNF State","Unstable","Test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.NO_TRANSITION_DEFINE.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void rejectInvalidRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testUnstableWorkingState() throws Exception { - logger.debug("=====================testUnstableWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("37")).thenReturn(true,false); - RequestHandlerInput input = this.getRequestHandlerInput("37", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input); - RequestHandlerOutput output = requestHandler.handleRequest(input); - - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RequestHandlerInput input1 = this.getRequestHandlerInput("37", VNFOperation.Configure,1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - logger.debug("=====================testUnstableWorkingState============================="); - } - - @Test - public void testOnRequestExecutionEndSuccessForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"137", "", "", ""),true); - - input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); - } - - private void mockRuntimeContextAndVnfContext(RequestHandlerInput input1) throws Exception { - RuntimeContext runtimeContext = PowerMockito.mock(RuntimeContext.class); - VNFContext vnfContext = new VNFContext(); - vnfContext.setType("SCP"); - vnfContext.setId("137"); - when(runtimeContext.getVnfContext()).thenReturn(vnfContext); - when(runtimeContext.getRequestContext()).thenReturn(input1.getRequestContext()); - when(runtimeContext.getRpcName()).thenReturn(input1.getRpcName()); - - - ResponseContext responseContext = new ResponseContext(); - responseContext.setStatus(new Status(0, null)); - responseContext.setAdditionalContext(new HashMap(4)); - responseContext.setCommonHeader(input1.getRequestContext().getCommonHeader()); - runtimeContext.setResponseContext(responseContext); - when(runtimeContext.getResponseContext()).thenReturn(responseContext); - responseContext.setStatus(new Status(0, null)); - runtimeContext.setResponseContext(responseContext); - PowerMockito.whenNew(RuntimeContext.class).withAnyArguments().thenReturn(runtimeContext); - - } - - @Test - public void testOnRequestExecutionEndFailureForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.NO_TRANSITION_DEFINE,"38", "", "", ""),true); - - input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); - - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - } - - @Test - public void testOnRequestExecutionEndTTLExpiredForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input1); - - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - } - - @Test - public void testOnRequestTTLEndForWorkingState() throws Exception { - logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.EXPIRED_REQUEST_FAILURE,"40", "", "", ""); - requestHandler.onRequestTTLEnd(response,true); - input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); - } - - @Test - public void testForceCommandExecution() throws Exception { - logger.debug("=====================testForceCommandExecution============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.ACCEPTED,"138", "", "", ""); - requestHandler.onRequestTTLEnd(response,true); - input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - input1.getRequestContext().getCommonHeader().setFlags(new Flags(null, true, 1200)); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testForceCommandExecution============================="); - } - - @Test - public void testOnRequestExecutionEndSuccess() throws VNFNotFoundException { - logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Starts ============================="); - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"201", "", "", ""),true); - logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Ends ============================="); - } - - @Test - public void testOnRequestExecutionEndFailure() throws VNFNotFoundException { - logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Starts ============================="); - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.DG_FAILURE,"202", "", "", ""),true); - logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Ends ============================="); - } - - private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, boolean force,String originatorId, String requestId, String subRequestId, Instant timeStamp){ - String API_VERSION= "2.0.0"; - RequestHandlerInput input = new RequestHandlerInput(); - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - RequestContext requestContext = runtimeContext.getRequestContext(); - input.setRequestContext(requestContext); - requestContext.getActionIdentifiers().setVnfId(vnfID); - requestContext.setAction(action); - input.setRpcName(convertActionNameToUrl(action.name())); - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestId); - requestContext.getCommonHeader().setOriginatorId(originatorId); - requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); - requestContext.getCommonHeader().setTimestamp(timeStamp); - requestContext.getCommonHeader().setApiVer(API_VERSION); - return input; - } - - private RuntimeContext getAsyncResponse(boolean wfStatus, LCMCommandStatus commandStatus, String vnfId, String originatorId, String requestId, String subRequestId) - { - RuntimeContext output = createRuntimeContextWithSubObjects(); - - - output.getRequestContext().getActionIdentifiers().setVnfId(vnfId); - output.getVnfContext().setId(vnfId); - output.getResponseContext().getCommonHeader().setApiVer("2.0.0"); - output.getResponseContext().getCommonHeader().setTimestamp( Instant.now()); - output.getResponseContext().setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - output.setTimeStart( Instant.now()); - output.getResponseContext().getCommonHeader().setOriginatorId(originatorId); - output.getResponseContext().getCommonHeader().setRequestId(requestId); - output.getResponseContext().getCommonHeader().setSubRequestId(subRequestId); - - output.getVnfContext().setType("FIREWALL"); - output.getRequestContext().setAction(VNFOperation.Configure); - output.setRpcName("configure"); - output.getResponseContext().setPayload(""); - return output; - } - - @Test - public void rejectDuplicateRequest() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - input = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - - PowerMockito.doThrow(new DuplicateRequestException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.DUPLICATE_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void removeRequestFromRegistryOnRequestCompletion() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("302", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"302",originatorID,requestID,subRequestID); - requestHandler.onRequestExecutionEnd(asyncResponse,true); - - input = this.getRequestHandlerInput("310", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void removeRequestFromRegistryOnTTLExpiration() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("303", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.ACCEPTED,"303",originatorID,requestID,subRequestID); - requestHandler.onRequestTTLEnd(asyncResponse,false); - - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - /*@Test - public void getMetricserviceTest() throws Exception{ - Method method = RequestHandlerImpl.class.getDeclaredMethod("getMetricservice", null); - method.setAccessible(true); - method.invoke(null, null); - - }*/ - @Test - public void onRequestExecutionStartTest() throws Exception{ - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionStart("303",false, null, true); - Assert.assertNotNull(requestHandler); - } - - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - ResponseContext responseContext = createResponseContextWithSuObjects(); - runtimeContext.setResponseContext(responseContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } -} - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java deleted file mode 100644 index fc14f2ac9..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.dao.util.AppcJdbcConnectionFactory; -import org.onap.appc.workingstatemanager.impl.WorkingStateManagerImpl; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.UUID; - - - -public class TestWorkingStateManager { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestWorkingStateManager.class); - WorkingStateManagerImpl workingStateManager; - - @Before - public void init() throws Exception { - workingStateManager = new WorkingStateManagerImpl(); - AppcJdbcConnectionFactory appcJdbcConnectionFactory = new AppcJdbcConnectionFactory(); - String schema = "sdnctl"; - appcJdbcConnectionFactory.setSchema(schema); - workingStateManager.setConnectionFactory(appcJdbcConnectionFactory); - String property = ConfigurationFactory.getConfiguration().getProperty(String.format("org.onap.appc.db.url.%s", schema)); - logger.info(property+" will be used as connection URL to mySQL."); - logger.warn("you can set connection URL to other IP by adding -DmysqlIp= in VM Option"); -// System.getProperties().getProperty("mys") - } - - @Test - // this test run on mysql you need to uncomment Ignore and to add -DmysqlIp= in VM Option, to make that test pass successfully. - @Ignore - public void testUpdateWorkingState() { - String vnfId = UUID.randomUUID().toString(); - String myOwnerId = "myOwnerId"; - String otherOwnerId = "otherOwnerId"; - boolean vnfStable = workingStateManager.isVNFStable(vnfId); - logger.info("isVNFStable returns "+vnfStable+" for vnfId "+vnfId); - - //set to unstable with force true - boolean updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - - //negative test - try to set to any value by other ownerId when vnf state is UNSTABLE - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, otherOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, otherOwnerId, false); - Assert.assertFalse(updated); - - //positive test - set with same ownerId and force false - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertTrue(workingStateManager.isVNFStable(vnfId)); - - //positive test - set with otherOwnerId and force false when VNF is stable - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - - //negative test - try to set to any value by myOwnerId when vnf state is UNKNOWN - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); - Assert.assertFalse(updated); - - //positive test - try to set to any value by myOwnerId when vnf state is UNKNOWN but with force - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..80e77b261 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,98 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +#org.onap.appc.bootstrap.file=executor-test.properties +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +# +# Certificate keystore and truststore +# +#org.openecomp.sdnc.sli.aai.ssl.trust= +#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin +#org.openecomp.sdnc.sli.aai.ssl.key= +#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin +org.openecomp.sdnc.sli.aai.host.certificate.ignore=true +org.openecomp.sdnc.sli.aai.certificate.trust.all=true + +# +# Configuration file for A&AI Adapter +# + +# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT +org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 + +org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query + +# service instance +org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances +org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance + +# complex +org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes +org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} + +# vservers +org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers +org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} + +# generic-vnf +org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ +org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} + +# +# Formatting +# +org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s +org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type +org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id +org.openecomp.sdnc.sli.aai.param.service.type=service-type + + +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + +org.onap.appc.db.url.%s", schema), ""); +org.onap.appc.db.user.%s", schema), ""); +org.onap.appc.db.pass.%s", schema), ""); + + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HDLR-TEST +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + + +mysqlIp=127.0.0.1 +org.onap.appc.db.url.sdnctl=jdbc:mysql://${mysqlIp}:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +org.onap.appc.workingstatemanager.maxAttempts=2 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 80e77b261..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,98 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -#org.onap.appc.bootstrap.file=executor-test.properties -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -# -# Certificate keystore and truststore -# -#org.openecomp.sdnc.sli.aai.ssl.trust= -#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin -#org.openecomp.sdnc.sli.aai.ssl.key= -#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin -org.openecomp.sdnc.sli.aai.host.certificate.ignore=true -org.openecomp.sdnc.sli.aai.certificate.trust.all=true - -# -# Configuration file for A&AI Adapter -# - -# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT -org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 - -org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query - -# service instance -org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances -org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance - -# complex -org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes -org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} - -# vservers -org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers -org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} - -# generic-vnf -org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ -org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} - -# -# Formatting -# -org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s -org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type -org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id -org.openecomp.sdnc.sli.aai.param.service.type=service-type - - -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - -org.onap.appc.db.url.%s", schema), ""); -org.onap.appc.db.user.%s", schema), ""); -org.onap.appc.db.pass.%s", schema), ""); - - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HDLR-TEST -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - - -mysqlIp=127.0.0.1 -org.onap.appc.db.url.sdnctl=jdbc:mysql://${mysqlIp}:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -org.onap.appc.workingstatemanager.maxAttempts=2 diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/WorkFlowManager.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/WorkFlowManager.java new file mode 100644 index 000000000..c0cb8f48e --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/WorkFlowManager.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow; + +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.appc.workflow.objects.WorkflowResponse; + +public interface WorkFlowManager { + /** + * Execute workflow and return response. + * This method execute workflow with following steps. + * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request. + * Execute workflow (DG) using SVC Logic Service reference + * Return response of workflow (DG) to caller. + * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID; + * @return Workflow Response which contains execution status and payload from DG if any + */ + WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest); + + /** + * Check if workflow (DG) exists in database + * @param workflowQueryParams workflow request with command and vnf Type + * @return WorkflowExistsOutput.mappingExist True if workflow mapping exists else False. WorkflowExistsOutput.dgExist True if DG workflow exists else False. + */ + WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams); + +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowExistsOutput.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowExistsOutput.java new file mode 100644 index 000000000..37d33d286 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowExistsOutput.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.objects; + +public class WorkflowExistsOutput { + + private boolean mappingExist ; + private boolean dgExist; + private String workflowModule; + private String workflowName; + private String workflowVersion; + + + public WorkflowExistsOutput() { + } + + public WorkflowExistsOutput(boolean mappingExist, boolean dgExist) { + this.mappingExist = mappingExist; + this.dgExist = dgExist; + } + + public boolean isMappingExist() { + return mappingExist; + } + + public void setMappingExist(boolean mappingExist) { + this.mappingExist = mappingExist; + } + + public boolean isDgExist() { + return dgExist; + } + + public void setDgExist(boolean dgExist) { + this.dgExist = dgExist; + } + + public String getWorkflowName() { + return workflowName; + } + + public void setWorkflowName(String workflowName) { + this.workflowName = workflowName; + } + + public String getWorkflowVersion() { + return workflowVersion; + } + + public void setWorkflowVersion(String workflowVersion) { + this.workflowVersion = workflowVersion; + } + + public String getWorkflowModule() { + return workflowModule; + } + + public void setWorkflowModule(String workflowModule) { + this.workflowModule = workflowModule; + } + public boolean exists(){ + return mappingExist && dgExist; + } + + @Override + public String toString() { + return "WorkflowExistsOutput{" + + "mappingExist=" + mappingExist + + ", dgExist=" + dgExist + + ", workflowModule='" + workflowModule + '\'' + + ", workflowName='" + workflowName + '\'' + + ", workflowVersion='" + workflowVersion + '\'' + + '}'; + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowRequest.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowRequest.java new file mode 100644 index 000000000..6cdbc7146 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowRequest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.objects; + +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFContext; + + +public class WorkflowRequest { + + private RequestContext requestContext; + private ResponseContext responseContext; + private VNFContext vnfContext; + + public RequestContext getRequestContext() { + return requestContext; + } + + public void setRequestContext(RequestContext requestContext) { + this.requestContext = requestContext; + } + + public ResponseContext getResponseContext() { + return responseContext; + } + + public void setResponseContext(ResponseContext responseContext) { + this.responseContext = responseContext; + } + + public VNFContext getVnfContext() { + return vnfContext; + } + + public void setVnfContext(VNFContext vnfContext) { + this.vnfContext = vnfContext; + } + + @Override + public String toString() { + return "WorkflowRequest{" + + "requestContext=" + requestContext + + ", responseContext=" + responseContext + + ", vnfContext=" + vnfContext + + '}'; + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowResponse.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowResponse.java new file mode 100644 index 000000000..f8d2997c5 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/onap/appc/workflow/objects/WorkflowResponse.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.objects; + +import java.util.Properties; + +import org.onap.appc.domainmodel.lcm.ResponseContext; + + +public class WorkflowResponse { + + private ResponseContext responseContext; + + public ResponseContext getResponseContext() { + return responseContext; + } + + public void setResponseContext(ResponseContext responseContext) { + this.responseContext = responseContext; + } + + @Override + public String toString() { + return "WorkflowResponse{" + + "responseContext=" + responseContext + + '}'; + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/WorkFlowManager.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/WorkFlowManager.java deleted file mode 100644 index c0cb8f48e..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/WorkFlowManager.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow; - -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.appc.workflow.objects.WorkflowResponse; - -public interface WorkFlowManager { - /** - * Execute workflow and return response. - * This method execute workflow with following steps. - * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request. - * Execute workflow (DG) using SVC Logic Service reference - * Return response of workflow (DG) to caller. - * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID; - * @return Workflow Response which contains execution status and payload from DG if any - */ - WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest); - - /** - * Check if workflow (DG) exists in database - * @param workflowQueryParams workflow request with command and vnf Type - * @return WorkflowExistsOutput.mappingExist True if workflow mapping exists else False. WorkflowExistsOutput.dgExist True if DG workflow exists else False. - */ - WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams); - -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowExistsOutput.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowExistsOutput.java deleted file mode 100644 index 37d33d286..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowExistsOutput.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.objects; - -public class WorkflowExistsOutput { - - private boolean mappingExist ; - private boolean dgExist; - private String workflowModule; - private String workflowName; - private String workflowVersion; - - - public WorkflowExistsOutput() { - } - - public WorkflowExistsOutput(boolean mappingExist, boolean dgExist) { - this.mappingExist = mappingExist; - this.dgExist = dgExist; - } - - public boolean isMappingExist() { - return mappingExist; - } - - public void setMappingExist(boolean mappingExist) { - this.mappingExist = mappingExist; - } - - public boolean isDgExist() { - return dgExist; - } - - public void setDgExist(boolean dgExist) { - this.dgExist = dgExist; - } - - public String getWorkflowName() { - return workflowName; - } - - public void setWorkflowName(String workflowName) { - this.workflowName = workflowName; - } - - public String getWorkflowVersion() { - return workflowVersion; - } - - public void setWorkflowVersion(String workflowVersion) { - this.workflowVersion = workflowVersion; - } - - public String getWorkflowModule() { - return workflowModule; - } - - public void setWorkflowModule(String workflowModule) { - this.workflowModule = workflowModule; - } - public boolean exists(){ - return mappingExist && dgExist; - } - - @Override - public String toString() { - return "WorkflowExistsOutput{" + - "mappingExist=" + mappingExist + - ", dgExist=" + dgExist + - ", workflowModule='" + workflowModule + '\'' + - ", workflowName='" + workflowName + '\'' + - ", workflowVersion='" + workflowVersion + '\'' + - '}'; - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowRequest.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowRequest.java deleted file mode 100644 index 6cdbc7146..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowRequest.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.objects; - -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFContext; - - -public class WorkflowRequest { - - private RequestContext requestContext; - private ResponseContext responseContext; - private VNFContext vnfContext; - - public RequestContext getRequestContext() { - return requestContext; - } - - public void setRequestContext(RequestContext requestContext) { - this.requestContext = requestContext; - } - - public ResponseContext getResponseContext() { - return responseContext; - } - - public void setResponseContext(ResponseContext responseContext) { - this.responseContext = responseContext; - } - - public VNFContext getVnfContext() { - return vnfContext; - } - - public void setVnfContext(VNFContext vnfContext) { - this.vnfContext = vnfContext; - } - - @Override - public String toString() { - return "WorkflowRequest{" + - "requestContext=" + requestContext + - ", responseContext=" + responseContext + - ", vnfContext=" + vnfContext + - '}'; - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowResponse.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowResponse.java deleted file mode 100644 index f8d2997c5..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-api/src/main/java/org/openecomp/appc/workflow/objects/WorkflowResponse.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.objects; - -import java.util.Properties; - -import org.onap.appc.domainmodel.lcm.ResponseContext; - - -public class WorkflowResponse { - - private ResponseContext responseContext; - - public ResponseContext getResponseContext() { - return responseContext; - } - - public void setResponseContext(ResponseContext responseContext) { - this.responseContext = responseContext; - } - - @Override - public String toString() { - return "WorkflowResponse{" + - "responseContext=" + responseContext + - '}'; - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/common/constant/Constants.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/common/constant/Constants.java new file mode 100644 index 000000000..ebac2d001 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/common/constant/Constants.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.common.constant; + +public class Constants { + + public static final String DG_ATTRIBUTE_STATUS = "SvcLogic.status"; + public static final String DG_STATUS_SUCCESS = "success"; + public static final String DG_ATTRIBUTE_STATUS_CODE = "SvcLogic.status.code"; + public static final String DG_OUTPUT_STATUS_CODE = "output.status.code"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + + /** + * The name of the property that contains the VM id value in the graph's context + */ + public static final String VF_ID = "org.onap.appc.vfid"; + + /** + * The name of the property that contains the VF Type value in the graph's context + */ + public static final String VF_TYPE = "org.onap.appc.vftype"; + + /** + * The name of the property that contains the service request id value in the graph's context + */ + public static final String REQUEST_ID = "org.onap.appc.reqid"; + + /** + * The name of the property that indicates which method of the IaaS adapter to call + */ + public static final String ACTION = "org.onap.appc.action"; + + public static final String PAYLOAD = "payload"; + + public static final String CONF_ID = "org.onap.appc.confid"; + + public static final String API_VERSION = "org.onap.appc.apiversion"; + + public static final String ORIGINATOR_ID = "org.onap.appc.originatorid"; + + public static final String OBJECT_ID ="org.onap.appc.objectid"; + + public static final String SUB_REQUEST_ID = "org.onap.appc.subrequestid"; + + public static final String ERROR_MESSAGE = "error-message"; + +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java new file mode 100644 index 000000000..ceae5677c --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java @@ -0,0 +1,347 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.impl; + +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.common.constant.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.util.ObjectMapper; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.appc.workflow.objects.WorkflowResponse; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Enumeration; +import java.util.Map; +import java.util.Properties; + + +public class WorkFlowManagerImpl implements WorkFlowManager{ + private SvcLogicService svcLogic = null; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private final WorkflowResolver workflowResolver = new WorkflowResolver( + configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300) + ); + + public void setSvcLogicServiceRef(SvcLogicService svcLogic) { + this.svcLogic = svcLogic; + } + + /** + * Execute workflow and return response. + * This method execute workflow with following steps. + * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request. + * Execute workflow (DG) using SVC Logic Service reference + * Return response of workflow (DG) to caller. + * + * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID; + * @return Workflow Response which contains execution status and payload from DG if any + */ + + @Override + public WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to executeWorkflow with WorkflowRequest = "+ ObjectUtils.toString(workflowRequest.toString())); + } + WorkflowResponse workflowResponse = new WorkflowResponse(); + workflowResponse.setResponseContext(workflowRequest.getResponseContext()); + + try { + + + WorkflowKey workflowKey = workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(), workflowRequest.getVnfContext().getType(), null,workflowRequest.getRequestContext().getCommonHeader().getApiVer()); + + Properties workflowParams = new Properties(); + String actionProperty = null; + String requestIdProperty=null; + String vfIdProperty =null; + if(!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){ + /* + The following method call (populateDGContext) populates DG context with the + request parameters to maintain backward compatibility with old DGs, + we are not altering the old way of passing (org.onap.appc.vnfId and so on..) + This is still a temporary solution, the end solution should be agreed with + all stakeholders and implemented. + */ + populateDGContext(workflowParams,workflowRequest); + } else { + actionProperty = configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION)); + requestIdProperty = configuration.getProperty("org.onap.appc.workflow.request.id", String.valueOf(Constants.REQUEST_ID)); + vfIdProperty = configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID)); + String payloadProperty = configuration.getProperty("org.onap.appc.workflow.payload", String.valueOf(Constants.PAYLOAD)); + String vfTypeProperty = configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE)); + String apiVerProperty = configuration.getProperty("org.onap.appc.workflow.apiVersion", String.valueOf(Constants.API_VERSION)); + String originatorIdProperty = configuration.getProperty("org.onap.appc.workflow.originatorId",Constants.ORIGINATOR_ID); + String subRequestId = configuration.getProperty("org.onap.appc.workflow.subRequestId",Constants.SUB_REQUEST_ID); + + workflowParams.put(actionProperty,workflowRequest.getRequestContext().getAction().name()); + workflowParams.put(requestIdProperty, workflowRequest.getRequestContext().getCommonHeader().getRequestId()); + workflowParams.put(vfIdProperty, workflowRequest.getVnfContext().getId()); + workflowParams.put(vfTypeProperty,workflowRequest.getVnfContext().getType()); + workflowParams.put(apiVerProperty,workflowRequest.getRequestContext().getCommonHeader().getApiVer()); + workflowParams.put(originatorIdProperty,workflowRequest.getRequestContext().getCommonHeader().getOriginatorId()); + workflowParams.put(subRequestId,workflowRequest.getRequestContext().getCommonHeader().getSubRequestId()); + + Object payloadJson = workflowRequest.getRequestContext().getPayload(); + if(payloadJson!=null) { + try { + Map payloadProperties = ObjectMapper.map(payloadJson); + workflowParams.putAll(payloadProperties); + + if (logger.isDebugEnabled()) { + logger.debug("DG properties: " + workflowParams); + } + } catch (Exception e) { + logger.error("Error parsing payload json string", e); + Properties workflowPrp = new Properties(); + workflowPrp.setProperty("error-message", "Error parsing payload json string"); + fillStatus(501, "Error parsing payload json string: "+e.getMessage(), workflowRequest.getResponseContext()); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from executeWorkflow with (workflowResponse = "+ObjectUtils.toString(workflowResponse)+")"); + } + return workflowResponse; + } + } + if (logger.isDebugEnabled()) { + logger.debug("DG parameters "+ actionProperty +":"+ workflowRequest.getRequestContext().getAction().name()+", "+ + requestIdProperty +":"+ workflowRequest.getRequestContext().getCommonHeader().getRequestId()+", "+ + vfIdProperty +":"+ workflowRequest.getVnfContext().getId()); + + logger.debug("Starting DG Execution for request "+workflowRequest.getRequestContext().getCommonHeader().getRequestId()); + } + } + if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){ + workflowParams.put("isBwcMode","true"); + } else { + workflowParams.put("isBwcMode", "false"); + } + + SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams , workflowResponse); + if (logger.isTraceEnabled()) { + logger.trace("Completed DG Execution for Request id: " + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + "with response code: " + workflowResponse.getResponseContext().getStatus().getCode()); + } + }catch (Exception e){ + logger.error("Error Executing DG " +e.getMessage()); + fillStatus(501, "Error Executing DG "+e.getMessage(), workflowRequest.getResponseContext()); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from executeWorkflow with (workflowResponse = "+ ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage())+")"); + } + return workflowResponse; + } + + private void populateDGContext(Properties workflowParams, WorkflowRequest workflowRequest) { + workflowParams.put("input.common-header.timestamp",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(Date.from(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()))); + workflowParams.put("input.common-header.api-ver",workflowRequest.getRequestContext().getCommonHeader().getApiVer()); + workflowParams.put("input.common-header.request-id",workflowRequest.getRequestContext().getCommonHeader().getRequestId()); + workflowParams.put("input.common-header.originator-id",workflowRequest.getRequestContext().getCommonHeader().getOriginatorId()); + workflowParams.put("input.common-header.sub-request-id",workflowRequest.getRequestContext().getCommonHeader().getSubRequestId()!=null ? workflowRequest.getRequestContext().getCommonHeader().getSubRequestId():""); + workflowParams.put("input.action",workflowRequest.getRequestContext().getAction().toString()); + workflowParams.put("input.payload",null != workflowRequest.getRequestContext().getPayload() ? workflowRequest.getRequestContext().getPayload() : ""); + workflowParams.put("input.action-identifiers.vnf-id",workflowRequest.getVnfContext().getId()); + workflowParams.put("input.action-identifiers.vnfc-name",workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName():""); + workflowParams.put("input.action-identifiers.service-instance-id",workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId():""); + workflowParams.put("input.action-identifiers.vf-module-id",workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId():""); + workflowParams.put("input.action-identifiers.vserver-id",workflowRequest.getRequestContext().getActionIdentifiers().getVserverId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVserverId():""); + final Map additionalContext; + if ((additionalContext = workflowRequest.getRequestContext().getAdditionalContext())!=null) { + for (Map.Entry entry : additionalContext.entrySet()) { + workflowParams.put("input." + entry.getKey(), null != entry.getValue() ? entry.getValue() : ""); + } + } + } + + /** + * Check if workflow (DG) exists in database + * + * @param workflowQueryParams workflow request with command and vnf Type + * @return True if workflow exists else False. + */ + @Override + public WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams) { + WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false,false); + if (logger.isTraceEnabled()) { + logger.trace("Entering to workflowExists with WorkflowRequest = "+ObjectUtils.toString(workflowQueryParams.toString())); + } + + try { + WorkflowKey workflowKey = workflowResolver.resolve( + workflowQueryParams.getRequestContext().getAction().name(), + workflowQueryParams.getVnfContext().getType(), + workflowQueryParams.getVnfContext().getVersion(), + workflowQueryParams.getRequestContext().getCommonHeader().getApiVer()); + if (workflowKey != null) { + workflowExistsOutput.setMappingExist(true); + workflowExistsOutput.setWorkflowModule(workflowKey.module()); + workflowExistsOutput.setWorkflowName(workflowKey.name()); + workflowExistsOutput.setWorkflowVersion(workflowKey.version()); + if (isDGExists(workflowKey)) { + workflowExistsOutput.setDgExist(true); + }else{ + logger.warn( + String.format("SLI doesn't have DG for resolved mapping entry: DG module - '%s', DG name - '%s', DG version - '%s'", + workflowKey.module(), workflowKey.name(), workflowKey.version())); + } + }else{ + logger.warn( + String.format("Unable to resolve recipe matching action '%s', VNF type '%s' and VNF version '%s'", + workflowQueryParams.getRequestContext().getAction().name(), workflowQueryParams.getVnfContext().getType(), null)); + } + } catch (RuntimeException e) { + logger.error("Error querying workflow from database"+e.getMessage()); + throw e; + }catch (SvcLogicException e) { + logger.error("Error querying workflow from database"+e.getMessage()); + throw new RuntimeException(e); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting workflowExists"); + } + return workflowExistsOutput; + } + + + private boolean isDGExists(WorkflowKey workflowKey) throws SvcLogicException { + return svcLogic.hasGraph(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync"); + } + + private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext, Properties workflowParams, WorkflowResponse workflowResponse) { + if (logger.isTraceEnabled()) { + logger.trace("Entering SVCLogicServiceExecute"); + } + + Properties respProps = null; + + try { + respProps = svcLogic.execute(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync", workflowParams); + } catch (Exception e) { + setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure", "Unexpected SLI Adapter failure", 200); + + if (logger.isDebugEnabled()) { + logger.debug("Error while executing DG " + e.getMessage() + e.getStackTrace()); + } + logger.error("Error in DG", e.getMessage()+e.getStackTrace().toString()); + } + + if (respProps != null) { + if (!requestContext.getCommonHeader().getApiVer().startsWith("1.")) { + fillResponseContextByOutputFieldsFromDgContext(workflowResponse.getResponseContext(), respProps); + } + + final String commonStatus = respProps.getProperty(Constants.DG_ATTRIBUTE_STATUS); + final String specificStatusMessage = respProps.getProperty(Constants.DG_OUTPUT_STATUS_MESSAGE); + String dgOutputStatusCode = respProps.getProperty(Constants.DG_OUTPUT_STATUS_CODE); + int specificStatusCode = 0; + if (dgOutputStatusCode != null) { + specificStatusCode = Integer.parseInt(dgOutputStatusCode); + } + + setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage, specificStatusCode); + + if (logger.isDebugEnabled()) { + logger.debug("DG Execution Status: " + commonStatus); + } + } + + if (logger.isTraceEnabled()) { + logger.trace("Exiting from SVCLogicServiceExecute"); + } + } + + /** + * Filling response context by output.* fields from DG context. Works only for 2.* API version + * + * @param responseContext response context which you need to fill + * @param respProps DG context in a properties format + */ + private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext, Properties respProps) { + + Enumeration e = respProps.propertyNames(); + while (e.hasMoreElements()){ + String key = (String) e.nextElement(); + if (key.startsWith("output.")){ + if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")){ + + if (key.equalsIgnoreCase("output.payload")){ + responseContext.setPayload(respProps.getProperty(key)); + } else { + responseContext.addKeyValueToAdditionalContext(key, respProps.getProperty(key)); + } + } + } + } + } + + /** + * Filling responceContext status code amd message according to responce messages and codes from DG. + * + * @param responseContext response cotext + * @param commonStatus common status message from DG ("success" or "failure") + * @param specificStatusMessage specific status message from specific DG node + * @param specificStatusCode specific status code from specific DG node + */ + private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus, String specificStatusMessage, int specificStatusCode) { + if (null == specificStatusMessage) { specificStatusMessage = ""; } + if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)){ + if (specificStatusCode != 0 ){ + fillStatus(specificStatusCode, specificStatusMessage, responseContext); + } else { + fillStatus(400, commonStatus, responseContext); + } + } else { + String errorMsg = StringUtils.isEmpty(specificStatusMessage) ? "DG execution failure" : specificStatusMessage; + if (specificStatusCode != 0){ + fillStatus(specificStatusCode, specificStatusMessage, responseContext); + } else { + fillStatus(401, specificStatusMessage, responseContext); + } + } + } + + /** + * filling responseContext by status code and status message + * + * @param code 3-digit status code + * @param message explanation of a status code + * @param responceContext response context which will be store status code and status message + */ + private void fillStatus(int code, String message, ResponseContext responceContext) { + responceContext.setStatus(new Status(code, message)); + } + +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowKey.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowKey.java new file mode 100644 index 000000000..d61628fc9 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowKey.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.impl; + +class WorkflowKey { + private final String name; + private final String version; + private final String module; + + WorkflowKey(String name, String version, String module) { + this.name = name; + this.version = version; + this.module = module; + } + + String name() { + return name; + } + + String version() { + return version; + } + + String module() { + return module; + } + + @Override + public String toString() { + StringBuilder buff = new StringBuilder(128); + buff.append("{"); + buff.append("module = ").append(module); + buff.append(", "); + buff.append("name = ").append(name); + buff.append(", "); + buff.append("version = ").append(version); + buff.append("}"); + return buff.toString(); + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolver.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolver.java new file mode 100644 index 000000000..1f4a5b406 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolver.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.impl; + +import java.util.concurrent.locks.ReentrantLock; + +import org.onap.appc.rankingframework.RankedAttributesContext; +import org.onap.appc.rankingframework.RankedAttributesResolver; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +class WorkflowResolver { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class); + + private long interval; + + private volatile long lastUpdate = 0l; + private volatile boolean isUpdateInProgress = false; + private volatile RankedAttributesResolver dgResolver; + + private final ReentrantLock INIT_LOCK = new ReentrantLock(); + + WorkflowResolver(long interval) { + this.interval = interval * 1000; + } + + private RankedAttributesResolver createResolver() { + WorkflowResolverDataReader reader = new WorkflowResolverDataReader(); + return reader.read(); + } + + private boolean isExpired() { + return (System.currentTimeMillis() - lastUpdate) > interval; + } + + private RankedAttributesResolver resolver() { + + /* + * In general case, the method implementation is non-blocking. The first + * thread that identifies data expiration will be used to refresh it. In + * meanwhile, any other thread will get the old instance without waiting + * for the updated one. The only exception is the very first time when + * previous instance doesn't exist - in such a cases all the threads + * will be waiting on INIT_LOCK while one of them initializes the + * resolver instance. NOTE: The initialization is intentionally + * implemented in lazy manner to make sure the bundle is initialized + * properly on startup regardless whether or not the data is correct. + * Afterwards, the resolver may be instantiated as many times as needed. + */ + + try { + + if (dgResolver == null) { + INIT_LOCK.lock(); + if (dgResolver != null) { + INIT_LOCK.unlock(); + } + } + + if (!isUpdateInProgress && isExpired()) { + + boolean doUpgrade = false; + + synchronized (this) { + if (!isUpdateInProgress) { + isUpdateInProgress = true; + doUpgrade = true; + } + } + + if (doUpgrade) { + + logger.info("DG resolver configuration data has expired - initiating refresh"); + + try { + RankedAttributesResolver temp = createResolver(); + dgResolver = temp; + lastUpdate = System.currentTimeMillis(); + + logger.info("DG resolver configuration data has been refreshed successfully"); + } finally { + isUpdateInProgress = false; + } + } + } + } finally { + if (INIT_LOCK.isHeldByCurrentThread()) { + INIT_LOCK.unlock(); + } + } + + return dgResolver; + } + + WorkflowKey resolve(final String action, final String vnfType, final String vnfVersion,final String apiVersion) { + + RankedAttributesContext context = new RankedAttributesContext() { + @Override + public Object getAttributeValue(String name) { + switch (name) { + case "action": + return action; + case "api_version": + return apiVersion; + case "vnf_type": + return vnfType; + case "vnf_version": + return vnfVersion; + default: + throw new IllegalStateException(name); + } + } + }; + + WorkflowKey wfKey = resolver().resolve(context); + + return wfKey; + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolverDataReader.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolverDataReader.java new file mode 100644 index 000000000..9cb04c42a --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkflowResolverDataReader.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; + +import org.onap.appc.dao.util.DBUtils; +import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; +import org.onap.appc.rankingframework.ConfigurationEntry; +import org.onap.appc.rankingframework.ConfigurationSet; +import org.onap.appc.rankingframework.RankedAttributesResolver; + +class WorkflowResolverDataReader { + + private static final String QUERY_STMT = "SELECT action,api_version,vnf_type,vnf_version,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; + + private static final Collection ATTRIBUTE_NAMES = Arrays.asList("action","api_version", "vnf_type", "vnf_version"); + + private static class ConfigurationSetAdaptor implements ConfigurationSet { + + private final ResultSet resultSet; + + private class ResultSetIterator implements Iterator>, ConfigurationEntry { + @Override + public boolean hasNext() { + try { + return resultSet.next(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public ConfigurationEntry next() { + return this; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public Object getAttributeValue(String name) { + try { + return resultSet.getObject(name); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public WorkflowKey getResult() { + try { + return new WorkflowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + } + + ConfigurationSetAdaptor(ResultSet resultSet) { + this.resultSet = resultSet; + } + + @Override + public Iterable> getEntries() { + return new Iterable>() { + + @Override + public Iterator> iterator() { + return new ResultSetIterator(); + } + }; + } + + @Override + public Collection getRankedAttributeNames() { + return ATTRIBUTE_NAMES; + } + } + + RankedAttributesResolver read() { + try { + try (Connection conn = DBUtils.getConnection("sdnctl")) { + try (PreparedStatement stmt = conn.prepareStatement(QUERY_STMT)) { + try (ResultSet res = stmt.executeQuery()) { + if (res.next()) { + res.beforeFirst(); + ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); + return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); + } else { + // TODO: Return empty object + throw new IllegalStateException(); + } + } + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/common/constant/Constants.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/common/constant/Constants.java deleted file mode 100644 index ebac2d001..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/common/constant/Constants.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.common.constant; - -public class Constants { - - public static final String DG_ATTRIBUTE_STATUS = "SvcLogic.status"; - public static final String DG_STATUS_SUCCESS = "success"; - public static final String DG_ATTRIBUTE_STATUS_CODE = "SvcLogic.status.code"; - public static final String DG_OUTPUT_STATUS_CODE = "output.status.code"; - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - - - /** - * The name of the property that contains the VM id value in the graph's context - */ - public static final String VF_ID = "org.onap.appc.vfid"; - - /** - * The name of the property that contains the VF Type value in the graph's context - */ - public static final String VF_TYPE = "org.onap.appc.vftype"; - - /** - * The name of the property that contains the service request id value in the graph's context - */ - public static final String REQUEST_ID = "org.onap.appc.reqid"; - - /** - * The name of the property that indicates which method of the IaaS adapter to call - */ - public static final String ACTION = "org.onap.appc.action"; - - public static final String PAYLOAD = "payload"; - - public static final String CONF_ID = "org.onap.appc.confid"; - - public static final String API_VERSION = "org.onap.appc.apiversion"; - - public static final String ORIGINATOR_ID = "org.onap.appc.originatorid"; - - public static final String OBJECT_ID ="org.onap.appc.objectid"; - - public static final String SUB_REQUEST_ID = "org.onap.appc.subrequestid"; - - public static final String ERROR_MESSAGE = "error-message"; - -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkFlowManagerImpl.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkFlowManagerImpl.java deleted file mode 100644 index ceae5677c..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkFlowManagerImpl.java +++ /dev/null @@ -1,347 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.impl; - -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.common.constant.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.Status; -import org.onap.appc.util.ObjectMapper; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.appc.workflow.objects.WorkflowResponse; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Enumeration; -import java.util.Map; -import java.util.Properties; - - -public class WorkFlowManagerImpl implements WorkFlowManager{ - private SvcLogicService svcLogic = null; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class); - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - private final WorkflowResolver workflowResolver = new WorkflowResolver( - configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300) - ); - - public void setSvcLogicServiceRef(SvcLogicService svcLogic) { - this.svcLogic = svcLogic; - } - - /** - * Execute workflow and return response. - * This method execute workflow with following steps. - * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request. - * Execute workflow (DG) using SVC Logic Service reference - * Return response of workflow (DG) to caller. - * - * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID; - * @return Workflow Response which contains execution status and payload from DG if any - */ - - @Override - public WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to executeWorkflow with WorkflowRequest = "+ ObjectUtils.toString(workflowRequest.toString())); - } - WorkflowResponse workflowResponse = new WorkflowResponse(); - workflowResponse.setResponseContext(workflowRequest.getResponseContext()); - - try { - - - WorkflowKey workflowKey = workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(), workflowRequest.getVnfContext().getType(), null,workflowRequest.getRequestContext().getCommonHeader().getApiVer()); - - Properties workflowParams = new Properties(); - String actionProperty = null; - String requestIdProperty=null; - String vfIdProperty =null; - if(!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){ - /* - The following method call (populateDGContext) populates DG context with the - request parameters to maintain backward compatibility with old DGs, - we are not altering the old way of passing (org.onap.appc.vnfId and so on..) - This is still a temporary solution, the end solution should be agreed with - all stakeholders and implemented. - */ - populateDGContext(workflowParams,workflowRequest); - } else { - actionProperty = configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION)); - requestIdProperty = configuration.getProperty("org.onap.appc.workflow.request.id", String.valueOf(Constants.REQUEST_ID)); - vfIdProperty = configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID)); - String payloadProperty = configuration.getProperty("org.onap.appc.workflow.payload", String.valueOf(Constants.PAYLOAD)); - String vfTypeProperty = configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE)); - String apiVerProperty = configuration.getProperty("org.onap.appc.workflow.apiVersion", String.valueOf(Constants.API_VERSION)); - String originatorIdProperty = configuration.getProperty("org.onap.appc.workflow.originatorId",Constants.ORIGINATOR_ID); - String subRequestId = configuration.getProperty("org.onap.appc.workflow.subRequestId",Constants.SUB_REQUEST_ID); - - workflowParams.put(actionProperty,workflowRequest.getRequestContext().getAction().name()); - workflowParams.put(requestIdProperty, workflowRequest.getRequestContext().getCommonHeader().getRequestId()); - workflowParams.put(vfIdProperty, workflowRequest.getVnfContext().getId()); - workflowParams.put(vfTypeProperty,workflowRequest.getVnfContext().getType()); - workflowParams.put(apiVerProperty,workflowRequest.getRequestContext().getCommonHeader().getApiVer()); - workflowParams.put(originatorIdProperty,workflowRequest.getRequestContext().getCommonHeader().getOriginatorId()); - workflowParams.put(subRequestId,workflowRequest.getRequestContext().getCommonHeader().getSubRequestId()); - - Object payloadJson = workflowRequest.getRequestContext().getPayload(); - if(payloadJson!=null) { - try { - Map payloadProperties = ObjectMapper.map(payloadJson); - workflowParams.putAll(payloadProperties); - - if (logger.isDebugEnabled()) { - logger.debug("DG properties: " + workflowParams); - } - } catch (Exception e) { - logger.error("Error parsing payload json string", e); - Properties workflowPrp = new Properties(); - workflowPrp.setProperty("error-message", "Error parsing payload json string"); - fillStatus(501, "Error parsing payload json string: "+e.getMessage(), workflowRequest.getResponseContext()); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from executeWorkflow with (workflowResponse = "+ObjectUtils.toString(workflowResponse)+")"); - } - return workflowResponse; - } - } - if (logger.isDebugEnabled()) { - logger.debug("DG parameters "+ actionProperty +":"+ workflowRequest.getRequestContext().getAction().name()+", "+ - requestIdProperty +":"+ workflowRequest.getRequestContext().getCommonHeader().getRequestId()+", "+ - vfIdProperty +":"+ workflowRequest.getVnfContext().getId()); - - logger.debug("Starting DG Execution for request "+workflowRequest.getRequestContext().getCommonHeader().getRequestId()); - } - } - if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){ - workflowParams.put("isBwcMode","true"); - } else { - workflowParams.put("isBwcMode", "false"); - } - - SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams , workflowResponse); - if (logger.isTraceEnabled()) { - logger.trace("Completed DG Execution for Request id: " + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + "with response code: " + workflowResponse.getResponseContext().getStatus().getCode()); - } - }catch (Exception e){ - logger.error("Error Executing DG " +e.getMessage()); - fillStatus(501, "Error Executing DG "+e.getMessage(), workflowRequest.getResponseContext()); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from executeWorkflow with (workflowResponse = "+ ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage())+")"); - } - return workflowResponse; - } - - private void populateDGContext(Properties workflowParams, WorkflowRequest workflowRequest) { - workflowParams.put("input.common-header.timestamp",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(Date.from(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()))); - workflowParams.put("input.common-header.api-ver",workflowRequest.getRequestContext().getCommonHeader().getApiVer()); - workflowParams.put("input.common-header.request-id",workflowRequest.getRequestContext().getCommonHeader().getRequestId()); - workflowParams.put("input.common-header.originator-id",workflowRequest.getRequestContext().getCommonHeader().getOriginatorId()); - workflowParams.put("input.common-header.sub-request-id",workflowRequest.getRequestContext().getCommonHeader().getSubRequestId()!=null ? workflowRequest.getRequestContext().getCommonHeader().getSubRequestId():""); - workflowParams.put("input.action",workflowRequest.getRequestContext().getAction().toString()); - workflowParams.put("input.payload",null != workflowRequest.getRequestContext().getPayload() ? workflowRequest.getRequestContext().getPayload() : ""); - workflowParams.put("input.action-identifiers.vnf-id",workflowRequest.getVnfContext().getId()); - workflowParams.put("input.action-identifiers.vnfc-name",workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName():""); - workflowParams.put("input.action-identifiers.service-instance-id",workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId():""); - workflowParams.put("input.action-identifiers.vf-module-id",workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId():""); - workflowParams.put("input.action-identifiers.vserver-id",workflowRequest.getRequestContext().getActionIdentifiers().getVserverId()!=null?workflowRequest.getRequestContext().getActionIdentifiers().getVserverId():""); - final Map additionalContext; - if ((additionalContext = workflowRequest.getRequestContext().getAdditionalContext())!=null) { - for (Map.Entry entry : additionalContext.entrySet()) { - workflowParams.put("input." + entry.getKey(), null != entry.getValue() ? entry.getValue() : ""); - } - } - } - - /** - * Check if workflow (DG) exists in database - * - * @param workflowQueryParams workflow request with command and vnf Type - * @return True if workflow exists else False. - */ - @Override - public WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams) { - WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false,false); - if (logger.isTraceEnabled()) { - logger.trace("Entering to workflowExists with WorkflowRequest = "+ObjectUtils.toString(workflowQueryParams.toString())); - } - - try { - WorkflowKey workflowKey = workflowResolver.resolve( - workflowQueryParams.getRequestContext().getAction().name(), - workflowQueryParams.getVnfContext().getType(), - workflowQueryParams.getVnfContext().getVersion(), - workflowQueryParams.getRequestContext().getCommonHeader().getApiVer()); - if (workflowKey != null) { - workflowExistsOutput.setMappingExist(true); - workflowExistsOutput.setWorkflowModule(workflowKey.module()); - workflowExistsOutput.setWorkflowName(workflowKey.name()); - workflowExistsOutput.setWorkflowVersion(workflowKey.version()); - if (isDGExists(workflowKey)) { - workflowExistsOutput.setDgExist(true); - }else{ - logger.warn( - String.format("SLI doesn't have DG for resolved mapping entry: DG module - '%s', DG name - '%s', DG version - '%s'", - workflowKey.module(), workflowKey.name(), workflowKey.version())); - } - }else{ - logger.warn( - String.format("Unable to resolve recipe matching action '%s', VNF type '%s' and VNF version '%s'", - workflowQueryParams.getRequestContext().getAction().name(), workflowQueryParams.getVnfContext().getType(), null)); - } - } catch (RuntimeException e) { - logger.error("Error querying workflow from database"+e.getMessage()); - throw e; - }catch (SvcLogicException e) { - logger.error("Error querying workflow from database"+e.getMessage()); - throw new RuntimeException(e); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting workflowExists"); - } - return workflowExistsOutput; - } - - - private boolean isDGExists(WorkflowKey workflowKey) throws SvcLogicException { - return svcLogic.hasGraph(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync"); - } - - private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext, Properties workflowParams, WorkflowResponse workflowResponse) { - if (logger.isTraceEnabled()) { - logger.trace("Entering SVCLogicServiceExecute"); - } - - Properties respProps = null; - - try { - respProps = svcLogic.execute(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync", workflowParams); - } catch (Exception e) { - setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure", "Unexpected SLI Adapter failure", 200); - - if (logger.isDebugEnabled()) { - logger.debug("Error while executing DG " + e.getMessage() + e.getStackTrace()); - } - logger.error("Error in DG", e.getMessage()+e.getStackTrace().toString()); - } - - if (respProps != null) { - if (!requestContext.getCommonHeader().getApiVer().startsWith("1.")) { - fillResponseContextByOutputFieldsFromDgContext(workflowResponse.getResponseContext(), respProps); - } - - final String commonStatus = respProps.getProperty(Constants.DG_ATTRIBUTE_STATUS); - final String specificStatusMessage = respProps.getProperty(Constants.DG_OUTPUT_STATUS_MESSAGE); - String dgOutputStatusCode = respProps.getProperty(Constants.DG_OUTPUT_STATUS_CODE); - int specificStatusCode = 0; - if (dgOutputStatusCode != null) { - specificStatusCode = Integer.parseInt(dgOutputStatusCode); - } - - setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage, specificStatusCode); - - if (logger.isDebugEnabled()) { - logger.debug("DG Execution Status: " + commonStatus); - } - } - - if (logger.isTraceEnabled()) { - logger.trace("Exiting from SVCLogicServiceExecute"); - } - } - - /** - * Filling response context by output.* fields from DG context. Works only for 2.* API version - * - * @param responseContext response context which you need to fill - * @param respProps DG context in a properties format - */ - private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext, Properties respProps) { - - Enumeration e = respProps.propertyNames(); - while (e.hasMoreElements()){ - String key = (String) e.nextElement(); - if (key.startsWith("output.")){ - if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")){ - - if (key.equalsIgnoreCase("output.payload")){ - responseContext.setPayload(respProps.getProperty(key)); - } else { - responseContext.addKeyValueToAdditionalContext(key, respProps.getProperty(key)); - } - } - } - } - } - - /** - * Filling responceContext status code amd message according to responce messages and codes from DG. - * - * @param responseContext response cotext - * @param commonStatus common status message from DG ("success" or "failure") - * @param specificStatusMessage specific status message from specific DG node - * @param specificStatusCode specific status code from specific DG node - */ - private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus, String specificStatusMessage, int specificStatusCode) { - if (null == specificStatusMessage) { specificStatusMessage = ""; } - if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)){ - if (specificStatusCode != 0 ){ - fillStatus(specificStatusCode, specificStatusMessage, responseContext); - } else { - fillStatus(400, commonStatus, responseContext); - } - } else { - String errorMsg = StringUtils.isEmpty(specificStatusMessage) ? "DG execution failure" : specificStatusMessage; - if (specificStatusCode != 0){ - fillStatus(specificStatusCode, specificStatusMessage, responseContext); - } else { - fillStatus(401, specificStatusMessage, responseContext); - } - } - } - - /** - * filling responseContext by status code and status message - * - * @param code 3-digit status code - * @param message explanation of a status code - * @param responceContext response context which will be store status code and status message - */ - private void fillStatus(int code, String message, ResponseContext responceContext) { - responceContext.setStatus(new Status(code, message)); - } - -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowKey.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowKey.java deleted file mode 100644 index d61628fc9..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.impl; - -class WorkflowKey { - private final String name; - private final String version; - private final String module; - - WorkflowKey(String name, String version, String module) { - this.name = name; - this.version = version; - this.module = module; - } - - String name() { - return name; - } - - String version() { - return version; - } - - String module() { - return module; - } - - @Override - public String toString() { - StringBuilder buff = new StringBuilder(128); - buff.append("{"); - buff.append("module = ").append(module); - buff.append(", "); - buff.append("name = ").append(name); - buff.append(", "); - buff.append("version = ").append(version); - buff.append("}"); - return buff.toString(); - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolver.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolver.java deleted file mode 100644 index 1f4a5b406..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolver.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.impl; - -import java.util.concurrent.locks.ReentrantLock; - -import org.onap.appc.rankingframework.RankedAttributesContext; -import org.onap.appc.rankingframework.RankedAttributesResolver; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -class WorkflowResolver { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class); - - private long interval; - - private volatile long lastUpdate = 0l; - private volatile boolean isUpdateInProgress = false; - private volatile RankedAttributesResolver dgResolver; - - private final ReentrantLock INIT_LOCK = new ReentrantLock(); - - WorkflowResolver(long interval) { - this.interval = interval * 1000; - } - - private RankedAttributesResolver createResolver() { - WorkflowResolverDataReader reader = new WorkflowResolverDataReader(); - return reader.read(); - } - - private boolean isExpired() { - return (System.currentTimeMillis() - lastUpdate) > interval; - } - - private RankedAttributesResolver resolver() { - - /* - * In general case, the method implementation is non-blocking. The first - * thread that identifies data expiration will be used to refresh it. In - * meanwhile, any other thread will get the old instance without waiting - * for the updated one. The only exception is the very first time when - * previous instance doesn't exist - in such a cases all the threads - * will be waiting on INIT_LOCK while one of them initializes the - * resolver instance. NOTE: The initialization is intentionally - * implemented in lazy manner to make sure the bundle is initialized - * properly on startup regardless whether or not the data is correct. - * Afterwards, the resolver may be instantiated as many times as needed. - */ - - try { - - if (dgResolver == null) { - INIT_LOCK.lock(); - if (dgResolver != null) { - INIT_LOCK.unlock(); - } - } - - if (!isUpdateInProgress && isExpired()) { - - boolean doUpgrade = false; - - synchronized (this) { - if (!isUpdateInProgress) { - isUpdateInProgress = true; - doUpgrade = true; - } - } - - if (doUpgrade) { - - logger.info("DG resolver configuration data has expired - initiating refresh"); - - try { - RankedAttributesResolver temp = createResolver(); - dgResolver = temp; - lastUpdate = System.currentTimeMillis(); - - logger.info("DG resolver configuration data has been refreshed successfully"); - } finally { - isUpdateInProgress = false; - } - } - } - } finally { - if (INIT_LOCK.isHeldByCurrentThread()) { - INIT_LOCK.unlock(); - } - } - - return dgResolver; - } - - WorkflowKey resolve(final String action, final String vnfType, final String vnfVersion,final String apiVersion) { - - RankedAttributesContext context = new RankedAttributesContext() { - @Override - public Object getAttributeValue(String name) { - switch (name) { - case "action": - return action; - case "api_version": - return apiVersion; - case "vnf_type": - return vnfType; - case "vnf_version": - return vnfVersion; - default: - throw new IllegalStateException(name); - } - } - }; - - WorkflowKey wfKey = resolver().resolve(context); - - return wfKey; - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolverDataReader.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolverDataReader.java deleted file mode 100644 index 9cb04c42a..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/openecomp/appc/workflow/impl/WorkflowResolverDataReader.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow.impl; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; - -import org.onap.appc.dao.util.DBUtils; -import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; -import org.onap.appc.rankingframework.ConfigurationEntry; -import org.onap.appc.rankingframework.ConfigurationSet; -import org.onap.appc.rankingframework.RankedAttributesResolver; - -class WorkflowResolverDataReader { - - private static final String QUERY_STMT = "SELECT action,api_version,vnf_type,vnf_version,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; - - private static final Collection ATTRIBUTE_NAMES = Arrays.asList("action","api_version", "vnf_type", "vnf_version"); - - private static class ConfigurationSetAdaptor implements ConfigurationSet { - - private final ResultSet resultSet; - - private class ResultSetIterator implements Iterator>, ConfigurationEntry { - @Override - public boolean hasNext() { - try { - return resultSet.next(); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public ConfigurationEntry next() { - return this; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Object getAttributeValue(String name) { - try { - return resultSet.getObject(name); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public WorkflowKey getResult() { - try { - return new WorkflowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - } - - ConfigurationSetAdaptor(ResultSet resultSet) { - this.resultSet = resultSet; - } - - @Override - public Iterable> getEntries() { - return new Iterable>() { - - @Override - public Iterator> iterator() { - return new ResultSetIterator(); - } - }; - } - - @Override - public Collection getRankedAttributeNames() { - return ATTRIBUTE_NAMES; - } - } - - RankedAttributesResolver read() { - try { - try (Connection conn = DBUtils.getConnection("sdnctl")) { - try (PreparedStatement stmt = conn.prepareStatement(QUERY_STMT)) { - try (ResultSet res = stmt.executeQuery()) { - if (res.next()) { - res.beforeFirst(); - ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); - return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); - } else { - // TODO: Return empty object - throw new IllegalStateException(); - } - } - } - } - } catch (SQLException e) { - throw new RuntimeException(e); - } - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..55249d0f9 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,43 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-WF-MGMT-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + + +# Tolerance interval (in seconds) between invalidation of DG resolver configuration +org.onap.appc.workflow.resolver.refresh_interval=300 + diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 55249d0f9..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,43 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-WF-MGMT-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - - -# Tolerance interval (in seconds) between invalidation of DG resolver configuration -org.onap.appc.workflow.resolver.refresh_interval=300 - diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/TestWorkFlowManager.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/TestWorkFlowManager.java new file mode 100644 index 000000000..74828a5d2 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/TestWorkFlowManager.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workflow; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.workflow.impl.WorkFlowManagerImpl; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicActivator; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest( {SvcLogicActivator.class, FrameworkUtil.class, WorkFlowManagerImpl.class} ) +public class TestWorkFlowManager { + public TestWorkFlowManager() { + } + + private WorkFlowManagerImpl workflowManger ; + private String command="Configure"; + protected SvcLogicGraph svcLogicGraph=null; + + + // + private final SvcLogicStore svcLogicStore= Mockito.mock(SvcLogicStore.class); + private final BundleContext bundleContext=Mockito.mock(BundleContext.class); + private final Bundle bundleSvcLogicService=Mockito.mock(Bundle.class); + private final ServiceReference serviceReferenceSvcLogicService=Mockito.mock(ServiceReference.class); + + + + @Before + public void setupMock() throws Exception { + /* + // DAO Mock + dao = Mockito.mock(AppcDAOImpl.class); + PowerMockito.whenNew(AppcDAOImpl.class).withNoArguments().thenReturn(dao); + + // SVC Logic Mock + SvcLogicServiceImpl svcLogicService=new SvcLogicServiceImpl(); + PowerMockito.mockStatic(SvcLogicActivator.class); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(SvcLogicActivator.getStore()).thenReturn(svcLogicStore); + PowerMockito.when(FrameworkUtil.getBundle(SvcLogicService.class)).thenReturn(bundleSvcLogicService); + PowerMockito.when(bundleSvcLogicService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(SvcLogicService.NAME)).thenReturn(serviceReferenceSvcLogicService); + PowerMockito.when(bundleContext.getService(serviceReferenceSvcLogicService)).thenReturn(svcLogicService); + + try { + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Configure"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Configure")); + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Restart"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Restart")); + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Test"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Test")); + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Rebuild"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Rebuild")); + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Terminate"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Terminate")); + PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Start"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Start")); + svcLogicService.registerExecutor("switch", new SwitchNodeExecutor()); + svcLogicService.registerExecutor("execute",new ReturnNodeExecutor()); + svcLogicService.registerExecutor("return",new ReturnNodeExecutor()); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + + workflowManger = new WorkFlowManagerImpl(); + + PowerMockito.when(getDao().retrieveWorkflowDetails("FIREWALL","Configure")).thenReturn(getWorkflow()); + PowerMockito.when(getDao().retrieveWorkflowDetails("FIREWALL","")).thenThrow(new DAOException()); + PowerMockito.when(getDao().retrieveWorkflowDetails("","Configure")).thenThrow(new DAOException()); + */ + } + + @Test + public void testEmptyVnfTypeFlow(){ + /* + WorkflowRequest workflowRequest = getWorkflowRequest("","1","1",command); + setSvcLogicGraph(createGraph(""+"_"+command)); + WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); + assertFalse(response.isExecutionSuccess()); + */ + } + + /* + @Test + public void testExecuteWorkflow(){ + //PowerMockito.when(getDao().retrieveWorkflowDetails(anyString(),anyString())).thenReturn(getWorkflow()); + WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); + setSvcLogicGraph(createGraph("FIREWALL"+"_"+command)); + WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); + assertFalse(response.isExecutionSuccess()); + } + + @Test + public void testExecuteWorkflowEmptyPayload(){ + //PowerMockito.when(getDao().retrieveWorkflowDetails(anyString(),anyString())).thenReturn(getWorkflow()); + WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); + workflowRequest.setPayload("{payload:\"payload\"}"); + setSvcLogicGraph(createGraph(""+"_"+command)); + WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); + assertFalse(response.isExecutionSuccess()); + } + + @Test + public void testWorkflowExist(){ + //PowerMockito.when(getDao().queryWorkflow(anyString(),anyString())).thenReturn(true); + WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); + boolean success = workflowManger.workflowExists(workflowRequest); + assertTrue(success); + } + + @Test + public void testWorkflowExistFalse(){ + //PowerMockito.when(getDao().queryWorkflow(anyString(),anyString())).thenReturn(false); + WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); + setSvcLogicGraph(createGraph(""+"_"+command)); + boolean success = workflowManger.workflowExists(workflowRequest); + assertFalse(success); + } + + + @Test + public void testEmptyCommandFlow(){ + WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",""); + WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); + assertFalse(response.isExecutionSuccess()); + } + */ + + + public void setSvcLogicGraph(SvcLogicGraph svcLogicGraph) { + this.svcLogicGraph = svcLogicGraph; + } + + public SvcLogicGraph getSvcLogicGraph() { + return svcLogicGraph; + } + + protected SvcLogicGraph createGraph(String rpc) { + SvcLogicGraph svcLogicGraph = new SvcLogicGraph(); + svcLogicGraph.setModule("APPC"); + svcLogicGraph.setRpc(rpc); + svcLogicGraph.setMode("sync"); + svcLogicGraph.setVersion("2.0.0"); + SvcLogicNode svcLogicRootNode = new SvcLogicNode(1, "switch", svcLogicGraph); + SvcLogicNode svcLogicConfigureNode = new SvcLogicNode(2, "return", svcLogicGraph); + SvcLogicNode svcLogicOtherNode = new SvcLogicNode(3, "return", svcLogicGraph); + try { + svcLogicConfigureNode.setAttribute("status", "success"); + svcLogicOtherNode.setAttribute("status", "failure"); + svcLogicRootNode.setAttribute("test", "$org.onap.appc.action"); + svcLogicRootNode.addOutcome("Configure", svcLogicConfigureNode); + svcLogicRootNode.addOutcome("Other", svcLogicOtherNode); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + svcLogicGraph.setRootNode(svcLogicRootNode); + return svcLogicGraph; + } +} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/openecomp/appc/workflow/TestWorkFlowManager.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/openecomp/appc/workflow/TestWorkFlowManager.java deleted file mode 100644 index 74828a5d2..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/openecomp/appc/workflow/TestWorkFlowManager.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workflow; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.workflow.impl.WorkFlowManagerImpl; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.SvcLogicNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicActivator; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest( {SvcLogicActivator.class, FrameworkUtil.class, WorkFlowManagerImpl.class} ) -public class TestWorkFlowManager { - public TestWorkFlowManager() { - } - - private WorkFlowManagerImpl workflowManger ; - private String command="Configure"; - protected SvcLogicGraph svcLogicGraph=null; - - - // - private final SvcLogicStore svcLogicStore= Mockito.mock(SvcLogicStore.class); - private final BundleContext bundleContext=Mockito.mock(BundleContext.class); - private final Bundle bundleSvcLogicService=Mockito.mock(Bundle.class); - private final ServiceReference serviceReferenceSvcLogicService=Mockito.mock(ServiceReference.class); - - - - @Before - public void setupMock() throws Exception { - /* - // DAO Mock - dao = Mockito.mock(AppcDAOImpl.class); - PowerMockito.whenNew(AppcDAOImpl.class).withNoArguments().thenReturn(dao); - - // SVC Logic Mock - SvcLogicServiceImpl svcLogicService=new SvcLogicServiceImpl(); - PowerMockito.mockStatic(SvcLogicActivator.class); - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(SvcLogicActivator.getStore()).thenReturn(svcLogicStore); - PowerMockito.when(FrameworkUtil.getBundle(SvcLogicService.class)).thenReturn(bundleSvcLogicService); - PowerMockito.when(bundleSvcLogicService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(SvcLogicService.NAME)).thenReturn(serviceReferenceSvcLogicService); - PowerMockito.when(bundleContext.getService(serviceReferenceSvcLogicService)).thenReturn(svcLogicService); - - try { - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Configure"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Configure")); - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Restart"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Restart")); - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Test"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Test")); - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Rebuild"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Rebuild")); - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Terminate"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Terminate")); - PowerMockito.when(svcLogicStore.fetch(anyString(), eq("FIREWALL_Start"), anyString(), anyString())).thenReturn(createGraph("FIREWALL_Start")); - svcLogicService.registerExecutor("switch", new SwitchNodeExecutor()); - svcLogicService.registerExecutor("execute",new ReturnNodeExecutor()); - svcLogicService.registerExecutor("return",new ReturnNodeExecutor()); - } catch (SvcLogicException e) { - e.printStackTrace(); - } - - workflowManger = new WorkFlowManagerImpl(); - - PowerMockito.when(getDao().retrieveWorkflowDetails("FIREWALL","Configure")).thenReturn(getWorkflow()); - PowerMockito.when(getDao().retrieveWorkflowDetails("FIREWALL","")).thenThrow(new DAOException()); - PowerMockito.when(getDao().retrieveWorkflowDetails("","Configure")).thenThrow(new DAOException()); - */ - } - - @Test - public void testEmptyVnfTypeFlow(){ - /* - WorkflowRequest workflowRequest = getWorkflowRequest("","1","1",command); - setSvcLogicGraph(createGraph(""+"_"+command)); - WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); - assertFalse(response.isExecutionSuccess()); - */ - } - - /* - @Test - public void testExecuteWorkflow(){ - //PowerMockito.when(getDao().retrieveWorkflowDetails(anyString(),anyString())).thenReturn(getWorkflow()); - WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); - setSvcLogicGraph(createGraph("FIREWALL"+"_"+command)); - WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); - assertFalse(response.isExecutionSuccess()); - } - - @Test - public void testExecuteWorkflowEmptyPayload(){ - //PowerMockito.when(getDao().retrieveWorkflowDetails(anyString(),anyString())).thenReturn(getWorkflow()); - WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); - workflowRequest.setPayload("{payload:\"payload\"}"); - setSvcLogicGraph(createGraph(""+"_"+command)); - WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); - assertFalse(response.isExecutionSuccess()); - } - - @Test - public void testWorkflowExist(){ - //PowerMockito.when(getDao().queryWorkflow(anyString(),anyString())).thenReturn(true); - WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); - boolean success = workflowManger.workflowExists(workflowRequest); - assertTrue(success); - } - - @Test - public void testWorkflowExistFalse(){ - //PowerMockito.when(getDao().queryWorkflow(anyString(),anyString())).thenReturn(false); - WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",command); - setSvcLogicGraph(createGraph(""+"_"+command)); - boolean success = workflowManger.workflowExists(workflowRequest); - assertFalse(success); - } - - - @Test - public void testEmptyCommandFlow(){ - WorkflowRequest workflowRequest = getWorkflowRequest("FIREWALL","1","1",""); - WorkflowResponse response =workflowManger.executeWorkflow(workflowRequest); - assertFalse(response.isExecutionSuccess()); - } - */ - - - public void setSvcLogicGraph(SvcLogicGraph svcLogicGraph) { - this.svcLogicGraph = svcLogicGraph; - } - - public SvcLogicGraph getSvcLogicGraph() { - return svcLogicGraph; - } - - protected SvcLogicGraph createGraph(String rpc) { - SvcLogicGraph svcLogicGraph = new SvcLogicGraph(); - svcLogicGraph.setModule("APPC"); - svcLogicGraph.setRpc(rpc); - svcLogicGraph.setMode("sync"); - svcLogicGraph.setVersion("2.0.0"); - SvcLogicNode svcLogicRootNode = new SvcLogicNode(1, "switch", svcLogicGraph); - SvcLogicNode svcLogicConfigureNode = new SvcLogicNode(2, "return", svcLogicGraph); - SvcLogicNode svcLogicOtherNode = new SvcLogicNode(3, "return", svcLogicGraph); - try { - svcLogicConfigureNode.setAttribute("status", "success"); - svcLogicOtherNode.setAttribute("status", "failure"); - svcLogicRootNode.setAttribute("test", "$org.onap.appc.action"); - svcLogicRootNode.addOutcome("Configure", svcLogicConfigureNode); - svcLogicRootNode.addOutcome("Other", svcLogicOtherNode); - } catch (SvcLogicException e) { - e.printStackTrace(); - } - svcLogicGraph.setRootNode(svcLogicRootNode); - return svcLogicGraph; - } -} diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..227a83753 --- /dev/null +++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,90 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +#org.onap.appc.bootstrap.file=executor-test.properties +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + + +# +# Certificate keystore and truststore +# +#org.openecomp.sdnc.sli.aai.ssl.trust= +#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin +#org.openecomp.sdnc.sli.aai.ssl.key= +#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin +org.openecomp.sdnc.sli.aai.host.certificate.ignore=true +org.openecomp.sdnc.sli.aai.certificate.trust.all=true + +# +# Configuration file for A&AI Adapter +# + +# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT +org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 + +org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query + +# service instance +org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances +org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance + +# complex +org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes +org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} + +# vservers +org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers +org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} + +# generic-vnf +org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ +org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} + +# +# Formatting +# +org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s +org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type +org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id +org.openecomp.sdnc.sli.aai.param.service.type=service-type + + +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + +org.onap.appc.db.url.%s", schema), ""); +org.onap.appc.db.user.%s", schema), ""); +org.onap.appc.db.pass.%s", schema), ""); + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-WF-MGMT-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 227a83753..000000000 --- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,90 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -#org.onap.appc.bootstrap.file=executor-test.properties -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - - -# -# Certificate keystore and truststore -# -#org.openecomp.sdnc.sli.aai.ssl.trust= -#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin -#org.openecomp.sdnc.sli.aai.ssl.key= -#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin -org.openecomp.sdnc.sli.aai.host.certificate.ignore=true -org.openecomp.sdnc.sli.aai.certificate.trust.all=true - -# -# Configuration file for A&AI Adapter -# - -# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT -org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 - -org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query - -# service instance -org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances -org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance - -# complex -org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes -org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} - -# vservers -org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers -org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} - -# generic-vnf -org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ -org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} - -# -# Formatting -# -org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s -org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type -org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id -org.openecomp.sdnc.sli.aai.param.service.type=service-type - - -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - -org.onap.appc.db.url.%s", schema), ""); -org.onap.appc.db.user.%s", schema), ""); -org.onap.appc.db.pass.%s", schema), ""); - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-WF-MGMT-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AbstractListener.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AbstractListener.java new file mode 100644 index 000000000..89c75a357 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AbstractListener.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import java.security.SecureRandom; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.onap.appc.listener.impl.EventHandlerImpl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public abstract class AbstractListener implements Listener { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractListener.class); + + protected AtomicBoolean run = new AtomicBoolean(false); + + protected int QUEUED_MIN = 1; + protected int QUEUED_MAX = 10; + + protected int THREAD_MIN = 4; + protected int THREAD_MAX = THREAD_MIN; // Fixed thread pool + protected int THREAD_SCALE_DOWN_SEC = 10; // Number of seconds to wait until we remove idle threads + + protected ThreadPoolExecutor executor; + + protected EventHandler dmaap; + + protected ListenerProperties props; + + private String listenerId; + + public AbstractListener(ListenerProperties props) { + updateProperties(props); + + dmaap = new EventHandlerImpl(props); + if (dmaap.getClientId().equals("0")) { + dmaap.setClientId(String.valueOf(new SecureRandom().nextInt(1000))); + } + + BlockingQueue threadQueue = new ArrayBlockingQueue(QUEUED_MAX + QUEUED_MIN + 1); + executor = new ThreadPoolExecutor(THREAD_MIN, THREAD_MAX, THREAD_SCALE_DOWN_SEC, TimeUnit.SECONDS, threadQueue, + new JobRejectionHandler()); + + // Custom Named thread factory + BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("DMaaP-Worker-%d").build(); + executor.setThreadFactory(threadFactory); + + run.set(true); + } + + /** + * Starts a loop that will only end after stop() or stopNow() are called. The loop will read messages off the DMaaP + * topic and perform some action on them while writing messages back to DMaaP at critical points in the execution. + * Inherited from Runnable. + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + LOG.error("Listener.run() has not been implemented"); + } + + @Override + public void stop() { + run.set(false); + LOG.info(String.format("Stopping with %d messages in queue", executor.getQueue().size())); + executor.shutdown(); + try { + executor.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOG.error("Listener graceful stop() failed", e); + } + + // close DMaaP clients + if (dmaap != null) { + dmaap.closeClients(); + } + LOG.info("Listener Thread Pool Finished"); + } + + @Override + public void stopNow() { + run.set(false); + LOG.info(String.format("StopNow called. Orphaning %d messages in the queue", executor.getQueue().size())); + executor.getQueue().clear(); + stop(); + } + + @Override + public String getBenchmark() { + return String.format("%s - No benchmarking implemented.", getListenerId()); + } + + @Override + public String getListenerId() { + return listenerId; + } + + // Sets the id of the listener in + @Override + public void setListenerId(String id) { + listenerId = id; + } + + private void updateProperties(ListenerProperties properties) { + this.props = properties; + QUEUED_MIN = + Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_QUEUE, String.valueOf(QUEUED_MIN))); + QUEUED_MAX = + Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_QUEUE, String.valueOf(QUEUED_MAX))); + THREAD_MIN = + Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_POOL, String.valueOf(THREAD_MIN))); + THREAD_MAX = + Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_POOL, String.valueOf(THREAD_MAX))); + + listenerId = props.getPrefix(); + } + + /** + * This class will be used to handle what happens when we cannot add a job because of a ThreadPool issue. It does + * not get invoked if there is any fault with the job. NOTE: So far, this has only been seen when doing a + * {@link Listener#stopNow} + * + */ + class JobRejectionHandler implements RejectedExecutionHandler { + @Override + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + LOG.error(String.format("A job was rejected. [%s]", r)); + } + + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AppcEventListenerActivator.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AppcEventListenerActivator.java new file mode 100644 index 000000000..0b1eb5328 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/AppcEventListenerActivator.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.listener.impl.ControllerImpl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +/** + * This activator is used to initialize and terminate the dmaap listener controller and pool(s) + *

+ * The DMaaP listener is responsible for listening to a topic on the Universal Event Bus and reading in messages that + * conform to the DCAE message format for APPC. These messages will then be parsed and passed along to the APPC Provider + * to take action on. The listener will also send messages out on DMaaP during critical phases. The messages sent out + * will have a status of: + *

    + *
  • PENDING - The listener has read the message off of DMaaP and has put it in the queue to be processed
  • + *
  • ACTIVE - The listener has begun actually processing the request and is waiting on the appc provider to + * complete the request
  • + *
  • SUCCESS or FAILURE - The listener has gotten a response back from the appc provider. If it is a + * FAILURE, a message should also be included
  • + *
+ *

+ *

+ * Activation of the bundle will provision 1 controller that in turn will provision 1 (or in the future more) listener + * to interact with DMaaP. Each listener will have a queue of messages read off of DMaaP and a thread pool of workers to + * process them. This worker is responsible for contacting appc provider to perform the action + *

+ *

+ * When the bundle is deactivated, the stopNow() method is called and the thread pool is emptied and all remaining jobs + * are orphaned. Alternatively stop() could be called which would allow all remaining jobs in the queue to complete at + * the cost of longer run time. + *

+ * + * @since Aug 30, 2015 + * @version $Id$ + */ +public class AppcEventListenerActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The configuration object + */ + private Configuration configuration; + + /** + * The bundle context + */ + private static BundleContext context; + + /** + * The reference to the actual implementation object that implements the services + */ + private Controller adapter; + + /** + * The logger to be used + */ + private final EELFLogger LOG = EELFManager.getInstance().getLogger(AppcEventListenerActivator.class); + + /** + * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start + * this bundle. This method can be used to register services or to allocate any resources that this bundle needs. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param ctx + * The execution context of the bundle being started. + * @throws java.lang.Exception + * If this method throws an exception, this bundle is marked as stopped and the Framework will remove + * this bundle's listeners, unregister all services registered by this bundle, and release all services + * used by this bundle. + * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) + */ + @Override + public void start(BundleContext ctx) throws Exception { + LOG.info("Starting Bundle " + getName()); + + context = ctx; + + configuration = ConfigurationFactory.getConfiguration(); + + Properties props = configuration.getProperties(); + + Set listeners = new HashSet<>(); + + // Configure event listener for the demo use case + ListenerProperties demoProps = new ListenerProperties("appc.demo", props); + demoProps.setListenerClass(org.onap.appc.listener.demo.impl.ListenerImpl.class); + listeners.add(demoProps); + + // =========================================================================== + + ListenerProperties clLCMProps = new ListenerProperties("appc.LCM", props); + clLCMProps.setListenerClass(org.onap.appc.listener.LCM.impl.ListenerImpl.class); + listeners.add(clLCMProps); + + // Configure the OAM properties + String oamPropKeyPrefix = "appc.OAM"; + ListenerProperties oamProps = new ListenerProperties(oamPropKeyPrefix, props); + if (isAppcOamPropsListenerEnabled(oamProps)) { + oamProps.setListenerClass(org.onap.appc.listener.LCM.impl.ListenerImpl.class); + listeners.add(oamProps); + } else { + LOG.warn(String.format("The listener %s is disabled and will not be run", oamPropKeyPrefix)); + } + + adapter = new ControllerImpl(listeners); + if (ctx != null && registration == null) { + LOG.info("Registering service DMaaP Controller"); + registration = ctx.registerService(Controller.class, adapter, null); + } + adapter.start(); + + LOG.info("DMaaP Listener started successfully"); + } + + /** + * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop + * the bundle. In general, this method should undo the work that the BundleActivator.start method started. There + * should be no active threads that were started by this bundle when this bundle returns. A stopped bundle must not + * call any Framework objects. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param ctx + * The execution context of the bundle being stopped. + * @throws java.lang.Exception + * If this method throws an exception, the bundle is still marked as stopped, and the Framework will + * remove the bundle's listeners, unregister all services registered by the bundle, and release all + * services used by the bundle. * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + */ + @Override + public void stop(BundleContext ctx) throws Exception { + boolean stopNow = true; + LOG.info("Stopping DMaaP Listener. StopNow=" + stopNow); + adapter.stop(stopNow); + if (registration != null) { + registration.unregister(); + registration = null; + } + LOG.info("DMaaP Listener stopped successfully"); + } + + public String getName() { + return "DMaaP Listener"; + } + + /** + * Check if AppcOam props disable listener or not + * + * @param listenerProperties of ListenerProperties objext + * @return false only if AppcOam disabled key is defined and equal to true. Otherwise, return true. + */ + private boolean isAppcOamPropsListenerEnabled(ListenerProperties listenerProperties) { + final Properties appcOamProperties = listenerProperties.getProperties(); + + return appcOamProperties == null + || !Boolean.parseBoolean(appcOamProperties.getProperty( + ListenerProperties.KEYS.DISABLED.getPropertySuffix())); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Controller.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Controller.java new file mode 100644 index 000000000..4fce8972b --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Controller.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import java.util.Map; + +/** + * A controller is responsible for creating a listener for each ListenerProperties object that is passed in to it on + * instantiation. The controller will create a thread pool that will contain all of the listener threads so no listener + * can crash the controller. + * + */ +public interface Controller { + + /** + * Creates a new thread in the thread pool for an implementation of the {@see #Listener} class set in the + * ListenerProperties. This thread is run immediately after it is created. + */ + public void start(); + + /** + * Stops each of the listeners known by this controller. Takes an optional parameter that indicates the the listener + * should stop immediately rather than waiting for all threads to complete. + * + * @param stopNow + * Determines what method the listeners should use to shutdown. If true, listeners will use the stopNow() + * method. Otherwise they will use the stop() method. + */ + public void stop(boolean stopNow); + + /** + * @return A Map of ListenerProperties and the Listener object that is running in the controllers thread pool. + */ + public Map getListeners(); + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/EventHandler.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/EventHandler.java new file mode 100644 index 000000000..9ec81b831 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/EventHandler.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import java.util.Collection; +import java.util.List; +import java.util.Set; + +/** + * EventHandler defines a class that wraps DMaaP operations (most notably Get Message and Post Message) to make them + * easier to use. + * + */ +public interface EventHandler { + + /** + * Gets a list of messages as Strings on the read topic. + * + * @return A list of String messages. Never returns null. + */ + public List getIncomingEvents(); + + /** + * Gets a list of messages as String on the read topic. + * + * @param limit + * The maximum amount of entries to return + * @return A list of String messages. Never returns null. + */ + public List getIncomingEvents(int limit); + + /** + * Gets a list of messages Mapped to the given Class. If a message cannot be mapped to that class, it is discarded. + * + * @param cls + * The class to map the message to. + * @return A list of objects of the provided class. Never returns null. + */ + public List getIncomingEvents(Class cls); + + /** + * Gets a list of messages Mapped to the given Class. If a message cannot be mapped to that class, it is discarded. + * + * @param cls + * The class to map the message to. + * @param limit + * The maximum amount of entries to return + * @return A list of objects of the provided class. Never returns null. + */ + public List getIncomingEvents(Class cls, int limit); + + /** + * Posts the String message to the write topic(s). + * + * @param event + * The String to post. + */ + public void postStatus(String event); + + /** + * Posts the String message to the write topic(s) on the specified partition. Partitions are only used to guarantee + * ordering and do not impact if data is retreived. + * + * @param partition + * The partition to post to or null if no partition should be used. + * @param event + * The String to post. + */ + public void postStatus(String partition, String event); + + /** + * @return The client/group id used to read messages + */ + public String getClientId(); + + /** + * Set the client/group id used to read messages + * + * @param clientId + * The new clientId to use + */ + public void setClientId(String clientId); + + /** + * @return The client/group name to use. + */ + public String getClientName(); + + /** + * Set the client/group name used to read messages. + * + * @param clientName + * The new clientName to use + */ + public void setClientName(String clientName); + + /** + * @return The name of the topic to read from + */ + public String getReadTopic(); + + /** + * Set the name of the topic to read from. + * + * @param topic + * The new topic to read from + */ + public void setReadTopic(String topic); + + /** + * @return The name of the topic to write to + */ + public Set getWriteTopics(); + + /** + * Set the name of the topic to write to + * + * @param topic + * The new topic to write to + */ + public void setWriteTopics(Set topic); + + /** + * Adds a DMaaP host to the host pool + * + * @param host + * The host to add to the pool in <host>:<port> format + */ + public void addToPool(String host); + + /** + * Remove the host name from the pool if it exists + * + * @param host + * The host to add to the pool in <host>:<port> format + */ + public void removeFromPool(String host); + + /** + * Get all of the hosts in the DMaaP pool + * + * @return A collection of host in <host>:<port> format + */ + public Collection getPool(); + + /** + * Clear any provided api credentials and make future requests as an unauthenticated user + */ + public void clearCredentials(); + + /** + * Set the api credentials and make future requests as an authenticated user + * + * @param access + * The access portion of the credentials (either user name or api key) + * @param secret + * The secret portion of the credentials (either password or api secret) + */ + public void setCredentials(String access, String secret); + + /** + * Close consumer/producer DMaaP clients + */ + public void closeClients(); + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/conv/Converter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/conv/Converter.java new file mode 100644 index 000000000..4cef18c87 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/conv/Converter.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.conv; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.*; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; +import org.onap.appc.listener.LCM.model.DmaapMessage; +import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; +import org.onap.appc.listener.util.Mapper; + +public class Converter { + + public static DmaapOutgoingMessage convJsonNodeToDmaapOutgoingMessage(DmaapMessage event, JsonNode inObj) { + DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); + outObj.setBody(inObj); + outObj.setRpcName(event.getRpcName()); + outObj.setVersion(event.getVersion()); + outObj.setType("response"); + outObj.setCorrelationID(event.getCorrelationID()); + return outObj; + } + + public static String convDmaapOutgoingMessageToJsonString(DmaapMessage inObj) throws JsonProcessingException { +// return Mapper.toJsonString(inObj); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) + .writer().withFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + return writer.writeValueAsString(inObj); + + } + + public static DmaapOutgoingMessage buildDmaapOutgoingMessageWithUnexpectedError(DmaapMessage event,Exception inputException) { + DmaapOutgoingMessage dmaapOutgoingMessage = null; + String errMsg = StringUtils.isEmpty(inputException.getMessage())? inputException.toString() : inputException.getMessage(); + JSONObject commonHeaderJsonObject = Mapper.toJsonObject(event.getBody().get("input").get("common-header")); + JSONObject jsonObjectOutput = new JSONObject().accumulate("common-header", commonHeaderJsonObject).accumulate("status", new JSONObject().accumulate("code",200).accumulate("value",errMsg)); + dmaapOutgoingMessage = new DmaapOutgoingMessage(); + dmaapOutgoingMessage.setRpcName(event.getRpcName()); + dmaapOutgoingMessage.setCorrelationID(event.getCorrelationID()); + dmaapOutgoingMessage.setType("error"); + dmaapOutgoingMessage.setVersion(event.getVersion()); + JSONObject jsonObjectBody = new JSONObject().accumulate("output",jsonObjectOutput); + JsonNode jsonNodeBody = Mapper.toJsonNodeFromJsonString(jsonObjectBody.toString()); + dmaapOutgoingMessage.setBody(jsonNodeBody); + return dmaapOutgoingMessage; + } + + public static String extractRequestIdWithSubId(JsonNode dmaapBody) { + //TODO: null pointer exception if dmaapBody is null, check if null or ensure is not null before calling + JsonNode commonHeaderJsonNode = dmaapBody.get("input").get("common-header"); + String requestId = getValue(commonHeaderJsonNode,"request-id",""); + String subRequestId = getValue(commonHeaderJsonNode,"sub-request-id",""); + if(!StringUtils.isEmpty(subRequestId)){ + requestId = requestId +"-"+subRequestId; + } + return requestId; + } + + public static Integer extractStatusCode(JsonNode event) { + Integer statusCode; + statusCode = event.get("output").get("status").get("code").asInt(); + return statusCode; + } + + private static String getValue(JsonNode jsonNode,String name,String defaultValue){ + if(jsonNode == null){ + return defaultValue; + } + JsonNode childJsonNode = jsonNode.get(name); + if(childJsonNode == null){ + return defaultValue; + } + String value = childJsonNode.asText(); + if(value == null){ + return defaultValue; + } + return value; + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/ListenerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/ListenerImpl.java new file mode 100644 index 000000000..41a6f92ee --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/ListenerImpl.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.impl; + +import com.fasterxml.jackson.databind.JsonNode; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.LCM.conv.Converter; +import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; +import org.onap.appc.listener.LCM.operation.ProviderOperations; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.RejectedExecutionException; + +public class ListenerImpl extends AbstractListener { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class); + + private long startTime = 0; + + private final ProviderOperations providerOperations; + + public ListenerImpl(ListenerProperties props) { + super(props); + + String url = props.getProperty("provider.url"); + LOG.info("DMaaP Provider Endpoint: " + url); + providerOperations = new ProviderOperations(); + providerOperations.setUrl(url); + + // Set Basic Auth + String user = props.getProperty("provider.user"); + String pass = props.getProperty("provider.pass"); + providerOperations.setAuthentication(user, pass); + } + + @Override + public void run() { + // Some vars for benchmarking + startTime = System.currentTimeMillis(); + + LOG.info("Running DMaaP Listener"); + + while (run.get()) { + // Only update if the queue is low. otherwise we read in more + // messages than we need + try { + if (executor.getQueue().size() <= QUEUED_MIN) { + LOG.debug("DMaaP queue running low. Querying for more jobs"); + + + List messages = dmaap.getIncomingEvents(DmaapIncomingMessage.class, QUEUED_MAX); + LOG.debug(String.format("Read %d messages from dmaap", messages.size())); + for (DmaapIncomingMessage incoming : messages) { + // Acknowledge that we read the event + if (isValid(incoming)) { + String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody()); + LOG.info("Acknowledging Message: " + requestIdWithSubId); + } + } + for (DmaapIncomingMessage incoming : messages) { + String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody()); + // Add to pool if still running + if (run.get()) { + if (isValid(incoming)) { + LOG.info(String.format("Adding DMaaP message to pool queue [%s]", requestIdWithSubId)); + try { + executor.execute(new WorkerImpl(incoming, dmaap, providerOperations)); + } catch (RejectedExecutionException rejectEx) { + LOG.error("Task Rejected: ", rejectEx); + } + } else { + // Badly formed message + LOG.error("Message was not valid. Rejecting message: "+incoming); + } + } else { + if (isValid(incoming)) { + LOG.info("Run stopped. Orphaning Message: " + requestIdWithSubId); + } + else { + // Badly formed message + LOG.error("Message was not valid. Rejecting message: "+incoming); + } + } + } + } + } catch (Exception e) { + LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener"); + LOG.error(EELFResourceManager.format(e)); + LOG.error("DMaaP Listener logging and ignoring the exception, continue..."); + } + } + + LOG.info("Stopping DMaaP Listener thread"); + + // We've told the listener to stop + // TODO - Should we: + // 1) Put a message back on the queue indicating that APP-C never got to + // the message + // or + // 2) Let downstream figure it out after timeout between PENDING and + // ACTIVE messages + } + + private boolean isValid(DmaapIncomingMessage incoming) { + return ((incoming != null) && + incoming.getBody() != null + && !StringUtils.isEmpty(incoming.getRpcName())); + } + + @Override + public String getBenchmark() { + long time = System.currentTimeMillis(); + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String runningTime = df.format(new Date(time - startTime)); + + String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime, + executor.getCompletedTaskCount(), executor.getPoolSize()); + LOG.info("***BENCHMARK*** " + out); + return out; + } + + private String getRequestIdWithSubId(JsonNode event){ + String requestId = ""; + try { + requestId = Converter.extractRequestIdWithSubId(event); + } catch (Exception e) { + LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e); + } + return requestId; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/WorkerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/WorkerImpl.java new file mode 100644 index 000000000..9334a8fad --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/impl/WorkerImpl.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.LCM.conv.Converter; +import org.onap.appc.listener.LCM.model.DmaapMessage; +import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; +import org.onap.appc.listener.LCM.operation.ProviderOperations; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; + +public class WorkerImpl implements Runnable { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(WorkerImpl.class); + + // Should have all of the data we need for processing + private DmaapMessage event; + + // So we can post messages from inside the worker. + private EventHandler dmaap; + + //so we know were to post the messages + private final ProviderOperations providerOperations; + + + public WorkerImpl(DmaapMessage message, EventHandler dmaap, ProviderOperations providerOperations) { + this.event = message; + this.dmaap = dmaap; + this.providerOperations = providerOperations; + } + + @Override + public void run() { + String requestIdWithSubId = extractRequestIdWithSubId(event.getBody()); + LOG.debug(String.format("Started working on %s", requestIdWithSubId)); + + // Run the dg in a try catch to handle all exceptions and update the + // message at the end + try { + JsonNode outputJsonNode = doDG(event.getRpcName(), event.getBody()); + DmaapOutgoingMessage dmaapOutgoingMessage= Converter.convJsonNodeToDmaapOutgoingMessage(event, outputJsonNode); + postMessageToDMaaP(dmaapOutgoingMessage,requestIdWithSubId); + Integer statusCode = extractStatusCode(dmaapOutgoingMessage.getBody()); + if (ProviderOperations.isSucceeded(statusCode)) { + LOG.debug(String.format("Event %s finished successfully", requestIdWithSubId)); + } else { + LOG.warn(String.format("Event %s failed", requestIdWithSubId)); + } + + } catch (Exception e) { + // Unknown exception from DG method. Fail and pass the exception + // along + String msg = "Exception: " + e.getMessage(); + LOG.error(String.format("Event %s finished with failure. %s", requestIdWithSubId, msg)); + DmaapOutgoingMessage dmaapOutgoingMessage= Converter.buildDmaapOutgoingMessageWithUnexpectedError(event, e); + postMessageToDMaaP(dmaapOutgoingMessage,requestIdWithSubId); + } + + LOG.debug("Done working on " + requestIdWithSubId); + } + + + private Integer extractStatusCode(JsonNode event) { + Integer statusCode = null; + try { + statusCode = Converter.extractStatusCode(event); + } catch (Exception e) { + LOG.error("failed to parse statusCode. Json not in expected format", e); + } + return statusCode; + } + + + private String extractRequestIdWithSubId(JsonNode event){ + String requestId = ""; + try { + requestId = Converter.extractRequestIdWithSubId(event); + } catch (Exception e) { + LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e); + } + return requestId; + } + + + + private void postMessageToDMaaP(DmaapOutgoingMessage dmaapOutgoingMessage,String requestIdWithSubId) { + String dmaapOutgoingMessageJsonString; + try { + dmaapOutgoingMessageJsonString = Converter.convDmaapOutgoingMessageToJsonString(dmaapOutgoingMessage); + dmaap.postStatus(dmaapOutgoingMessage.getCambriaPartition(),dmaapOutgoingMessageJsonString); + } catch (JsonProcessingException e) { + LOG.error("failed to postMessageToDMaaP requestIdWithSubId: "+requestIdWithSubId+" dmaapOutgoingMessage: "+dmaapOutgoingMessage, e); + } + } + + private JsonNode doDG(String rpcName, JsonNode msg) throws APPCException { + return providerOperations.topologyDG(rpcName,msg); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ActionIdentifiers.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ActionIdentifiers.java new file mode 100644 index 000000000..2419bed65 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ActionIdentifiers.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + + +public class ActionIdentifiers implements Serializable { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + @JsonProperty("vnf-id") + private String vnfID; + @JsonProperty("vnfc-name") + private String vnfcName; + @JsonProperty("vserver-id") + private String vserverId; + + public ActionIdentifiers() { + } + + public ActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.serviceInstanceId=actionIdentifiers.getServiceInstanceId(); + this.vnfID=actionIdentifiers.getVnfID(); + this.vnfcName=actionIdentifiers.getVnfcName(); + this.vserverId=actionIdentifiers.getVserverId(); + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfID() { + return vnfID; + } + + public void setVnfID(String vnfID) { + this.vnfID = vnfID; + } + + public String getVnfcName() { + return vnfcName; + } + + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + public String getVserverId() { + return vserverId; + } + + public void setVserverId(String vserverId) { + this.vserverId = vserverId; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/CommonHeader.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/CommonHeader.java new file mode 100644 index 000000000..b7dcc1bb7 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/CommonHeader.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Map; + +import org.onap.appc.util.Time; + +public class CommonHeader implements Serializable { + @JsonProperty("timestamp") + private String timeStamp; + @JsonProperty("api-ver") + private String apiVer; + @JsonProperty("originator-id") + private String originatorId; + @JsonProperty("request-id") + private String requestID; + @JsonProperty("sub-request-id") + private String subRequestId; + @JsonProperty("flags") + private Map flags; + + private static final DateFormat ZULU_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); + + public CommonHeader() { + } + + public CommonHeader(CommonHeader commonHeader) { + // changed to current system time + timeStamp = ZULU_FORMATTER.format(Time.utcDate()); + + apiVer = commonHeader.getApiVer(); + originatorId = commonHeader.getOriginatorId(); + requestID = commonHeader.getRequestID(); + subRequestId = commonHeader.getSubRequestId(); + flags = commonHeader.getFlags(); + } + + + + public String getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; + } + + public String getApiVer() { + return apiVer; + } + + public void setApiVer(String apiVer) { + this.apiVer = apiVer; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public String getOriginatorId() { + return originatorId; + } + + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + public String getSubRequestId() { + return subRequestId; + } + + public void setSubRequestId(String subRequestId) { + this.subRequestId = subRequestId; + } + + public Map getFlags() { + return flags; + } + + public void setFlags(Map flags) { + this.flags = flags; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessage.java new file mode 100644 index 000000000..32b70d100 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessage.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.json.JSONObject; +import org.onap.appc.listener.util.Mapper; + +/** + * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapIncomingMessage extends DmaapMessage{ + private final static String defaultCambriaPartition = "APP-C"; + + public DmaapIncomingMessage() { + super(); + setCambriaPartition(defaultCambriaPartition); + } + + + @Override + public String toString() { + return "DmaapIncomingMessage{"+super.toString()+"}"; + } +} + diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapMessage.java new file mode 100644 index 000000000..214783d10 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapMessage.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.JsonNode; + + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapMessage{ + + @JsonProperty("version") + private String version; + + @JsonProperty("type") + private String type; + + @JsonProperty("correlation-id") + private String correlationID; + + @JsonProperty("cambria.partition") + private String cambriaPartition; + + @JsonProperty("rpc-name") + private String rpcName; + + @JsonProperty("body") + private JsonNode body; + + public DmaapMessage() { + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCorrelationID() { + return correlationID; + } + + public void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + public String getCambriaPartition() { + return cambriaPartition; + } + + public void setCambriaPartition(String cambriaPartition) { + this.cambriaPartition = cambriaPartition; + } + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public JsonNode getBody() { + return body; + } + + public void setBody(JsonNode body) { + this.body = body; + } + + @Override + public String toString() { + return "DmaapMessage{" + + "version='" + version + '\'' + + ", type='" + type + '\'' + + ", correlationId='" + correlationID + '\'' + + ", cambriaPartition='" + cambriaPartition + '\'' + + ", rpcName='" + rpcName + '\'' + + ", body=" + body + + '}'; + } + +} + diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessage.java new file mode 100644 index 000000000..acf4461aa --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessage.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.json.JSONObject; +import org.onap.appc.listener.util.Mapper; + +/** + * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapOutgoingMessage extends DmaapMessage{ + private final static String defaultCambriaPartition = "MSO"; + + public DmaapOutgoingMessage() { + super(); + setCambriaPartition(defaultCambriaPartition); + } + + + @Override + public String toString() { + return "DmaapOutgoingMessage{"+super.toString()+"}"; + } +} + diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/InputBody.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/InputBody.java new file mode 100644 index 000000000..85aed42d8 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/InputBody.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class InputBody { + + @JsonProperty("common-header") + private CommonHeader commonHeader; + + @JsonProperty("action-identifiers") + private ActionIdentifiers actionIdentifiers; + + @JsonProperty("action") + private String action; + + @JsonProperty("payload") + private Object payload; + + + public Object getPayload() { + return payload; + } + + public void setPayload(Object payload) { + this.payload = payload; + } + @JsonIgnore + public void setPayloadAsString(String payload) { + this.payload = payload; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public ActionIdentifiers getActionIdentifiers() { + return actionIdentifiers; + } + + public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { + this.actionIdentifiers = actionIdentifiers; + } + + public CommonHeader getCommonHeader() { + return commonHeader; + } + + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + @JsonIgnore + public boolean isValid() { + return getCommonHeader() != null; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/OutputBody.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/OutputBody.java new file mode 100644 index 000000000..11714e8fb --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/OutputBody.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.json.JSONObject; +import org.onap.appc.listener.util.Mapper; + +/** + * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class OutputBody { + + @JsonProperty("common-header") + private CommonHeader header; + + @JsonProperty("status") + private ResponseStatus status; + + @JsonProperty("payload") + private String payload; + + @JsonProperty("locked") + private String locked; + + public OutputBody() { + } + + + public JSONObject toResponse() { + return Mapper.toJsonObject(this); + } + + public OutputBody(InputBody msg) { + this.header = new CommonHeader(msg.getCommonHeader()); + } + + public String getLocked() { + return locked; + } + + public void setLocked(String locked) { + this.locked = locked; + } + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public CommonHeader getHeader() { + return header; + } + + public void setHeader(CommonHeader header) { + this.header = header; + } + + public ResponseStatus getStatus() { + return status; + } + + public void setStatus(ResponseStatus status) { + this.status = status; + } + + @Override + public String toString() { + return String.format("%s - %s(%s)", getHeader().getRequestID(), getStatus().getCode(), getStatus().getValue()); + } +} + diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ResponseStatus.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ResponseStatus.java new file mode 100644 index 000000000..114b97b35 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/model/ResponseStatus.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResponseStatus { + @JsonProperty("code") + private Integer code; + @JsonProperty("message") + private String value; + + public ResponseStatus() { + } + + public ResponseStatus(Integer code, String value) { + this.code = code; + this.value = value; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + code = code; + } + + public String getValue() { + return value; + } + + + + public void setValue(String value) { + value = value; + } + + @Override + public String toString() { + return "ResponseStatus{" + + "code=" + code + + ", value='" + value + '\'' + + '}'; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java new file mode 100644 index 000000000..8fbe4af24 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import org.json.JSONObject; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.LCM.model.InputBody; +import org.onap.appc.listener.LCM.model.ResponseStatus; +import org.onap.appc.listener.util.Mapper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.net.URL; + +public class GenericProviderOperationRequestFormatter implements ProviderOperationRequestFormatter { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(GenericProviderOperationRequestFormatter.class); + + //@formatter:off + @SuppressWarnings("nls") + private final static String TEMPLATE = "{\"input\": %s}"; + //@formatter:on + + @Override + public String buildPath(URL url, String rpcName) { + return url.getPath() + ":"+rpcName; + } + + @Override + public String buildRequest(InputBody msg) { + JSONObject jsonObject = Mapper.toJsonObject(msg); + return String.format(TEMPLATE, jsonObject.toString()); + } + + @Override + public ResponseStatus getResponseStatus(JsonNode responseBody)throws APPCException{ + try { + JsonNode status = responseBody.get("output").get("status"); + return new ResponseStatus(status.get("code").asInt(), status.get("message").asText()); + } catch (Exception e) { + LOG.error("Unknown error processing failed response from provider. Json not in expected format", e); + throw new APPCException("APPC has an unknown RPC error"); + } + } + + @Override + public String getLocked(JSONObject responseBody) throws APPCException { + try { + JSONObject outputObject=responseBody.getJSONObject("output"); + if(outputObject.has("locked")){ + return outputObject.getString("locked"); + }else{ + return null; + } + } catch (Exception e) { + LOG.error("Unknown error processing failed response from provider. Json not in expected format", e); + throw new APPCException("APPC has an unknown RPC error"); + } + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java new file mode 100644 index 000000000..1e9909a1f --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import org.json.JSONObject; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.LCM.model.InputBody; +import org.onap.appc.listener.LCM.model.ResponseStatus; + +import java.net.URL; + + +public interface ProviderOperationRequestFormatter { + + String buildPath(URL url, String rpcName); + + String buildRequest(InputBody msg); + + ResponseStatus getResponseStatus(JsonNode json)throws APPCException; + + String getLocked(JSONObject json)throws APPCException; +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperations.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperations.java new file mode 100644 index 000000000..d3ac83d1b --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/LCM/operation/ProviderOperations.java @@ -0,0 +1,263 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.LCM.model.ResponseStatus; +import org.onap.appc.listener.util.Mapper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class ProviderOperations { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); + + private URL url; + private String basic_auth; + + private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter(); + + /** + * Calls the AppcProvider to run a topology directed graph + * + * @param msg The incoming message to be run + * @return True if the result is success. Never returns false and throws an exception instead. + * @throws UnsupportedEncodingException + * @throws Exception if there was a failure processing the request. The exception message is the failure reason. + */ + @SuppressWarnings("nls") + public JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException { + if (msg == null) { + throw new APPCException("Provided message was null"); + } + + HttpPost post = null; + try { + + // Concatenate the "action" on the end of the URL + String path = requestFormatter.buildPath(url, rpcName); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + + post = new HttpPost(serviceUrl.toExternalForm()); + post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + post.setHeader(HttpHeaders.ACCEPT, "application/json"); + + // Set Auth + if (basic_auth != null) { + post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth); + } + + String body = Mapper.toJsonString(msg); + StringEntity entity = new StringEntity(body); + entity.setContentType("application/json"); + post.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + int httpCode = 0; + String respBody = null; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + throw new APPCException(e); + } + + if (httpCode >= 200 && httpCode < 300 && respBody != null) { + JsonNode json; + try { + json = Mapper.toJsonNodeFromJsonString(respBody); + } catch (Exception e) { + LOG.error("Error processing response from provider. Could not map response to json", e); + throw new APPCException("APPC has an unknown RPC error"); + } + + ResponseStatus responseStatus = requestFormatter.getResponseStatus(json); + + if (!isSucceeded(responseStatus.getCode())) { + LOG.warn(String.format("Operation failed [%s]", msg.toString())); + } + + return json; + } + + throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody)); + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public String getUrl() { + return url.toExternalForm(); + } + + public void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basic_auth = null; + } + return basic_auth; + } + + @SuppressWarnings("deprecation") + private HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals("https")) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); + registry.register(new Scheme("https", sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + client = new DefaultHttpClient(); + } + } else if (url.getProtocol().equals("http")) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + public static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + public static boolean isSucceeded(Integer code) { + if (code == null) { + return false; + } + return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Listener.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Listener.java new file mode 100644 index 000000000..50589c89d --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/Listener.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +/** + * This interface defines a listener that subscribes to a DMaaP topic and continually polls for messages. The + * listener does all operations in the run() method and long running operations should be created in a separate worker + * thread. + * + */ +public interface Listener extends Runnable { + + /** + * Should start a continuous poll to get messages from the message bus only ending when stop() or stopNow() are + * called. + * + * @see java.lang.Runnable#run() + */ + @Override + public void run(); + + /** + * Signals the listener to stop accepting new messages to the queue and to cleanly finish processing all remaining + * messages in the queue. This can take a significant amount of time to complete depending on the thread pool + * characteristics. Similar to {@link #stopNow()} + */ + public void stop(); + + /** + * Signals the listener to stop accepting new messages to the queue and to destroy all remaining messages in the + * queue. This will complete quicker than {@link #stop()} at the cost of discarded requests. Recovery of these + * requests would have to be caught downstream. Similar to {@link #stop()} + */ + public void stopNow(); + + /** + * @return A string that shows various benchmarking data. Can be used by humans to tune the thread pool. + */ + public String getBenchmark(); + + /** + * @return The listener's id when requesting messages from DMaaP. Also known as the group id. + */ + public String getListenerId(); + + /** + * Sets the listener's id to use when requesting messages from DMaaP. Also known as the group id. + * + * @param idString + * The new listener id + */ + public void setListenerId(String idString); +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/ListenerProperties.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/ListenerProperties.java new file mode 100644 index 000000000..7908d3a1b --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/ListenerProperties.java @@ -0,0 +1,285 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import java.util.Properties; + +/** + * A class for instantiating Listener objects. It is primarily used to hold properties that start with the given prefix. + * It also holds a class that implements {@see Listener} and will be used by the controller to spawn a new listener + * object. + * + * @since Apr 25, 2016 + * @version $Id$ + */ +public class ListenerProperties { + + private String prefix; + + private Class listenerClass; + + private Properties props; + + /** + * Creates a new listener object with the given prefix and properties. Any property starting with the prefix is + * added to the internal properties object with the prefix removed. All other properties are ignored. + * ListenerProperties constructor + * + * @param prefix + * The prefix of the properties to load + * @param allProps + * The properties object to load from. + */ + public ListenerProperties(String prefix, Properties allProps) { + this.prefix = prefix; + props = new Properties(); + + String dottedPrefix = String.format("%s.", prefix); + for (String key : allProps.stringPropertyNames()) { + if (key.startsWith(dottedPrefix) && key.length() > dottedPrefix.length()) { + props.put(key.substring(dottedPrefix.length()), allProps.get(key)); + } + } + } + + /** + * @return The prefix of these properties + */ + public String getPrefix() { + return prefix; + } + + /** + * Sets the listener class. Will be used by {@see Controller} to instantiate the Listener thread for this object + * + * @param cls + * The class to be created. Implements {@see Listener} + */ + public void setListenerClass(Class cls) { + this.listenerClass = cls; + } + + /** + * @return The class that will be used by {@see Controller} to instantiate the Listener thread for this object + */ + public Class getListenerClass() { + return listenerClass; + } + + /** + * Returns a property matching a given KEYS + * + * @param key + * The KEYS object who's value to return. + * @return The value of the property or null if none exists + */ + public String getProperty(KEYS key) { + return getProperty(key, null); + } + + /** + * Returns a property matching a given string. + * + * @param key + * The key who's value to return. + * @return The value of the property or null if none exists + */ + public String getProperty(String key) { + return getProperty(key, null); + } + + /** + * Returns a property matching a given KEYS + * + * @param key + * The KEYS object who's value to return. + * @param defaultValue + * The value to return if the property is not found + * @return The value of the property or null if none exists + */ + public String getProperty(KEYS key, String defaultValue) { + return getProperty(key.getPropertySuffix(), defaultValue); + } + + /** + * Returns a property matching a given string. + * + * @param key + * The key who's value to return. + * @param defaultValue + * The value to return if the property is not found + * @return The value of the property or null if none exists + */ + public String getProperty(String key, String defaultValue) { + return props.getProperty(key, defaultValue); + } + + /** + * @return The properties object containing all properties + */ + public Properties getProperties() { + return props; + } + + /** + * Reads the prefix.disabled property to determine if the listener is disabled and should not be run by the + * controller. Defaults to false if property not set or value cannot be parsed. + * + * @return true if the listener is disabled and should not be started. false if the listener should be start + * normally (default). + */ + public boolean isDisabled() { + return Boolean.valueOf(getProperty(KEYS.DISABLED, "false")); + } + + @Override + public String toString() { + return String.format("%s", prefix); + } + + + /** + * Set of common properties that will be used by most systems. Primarily relating to DMaaP and ThreadPools + * + * @since Apr 25, 2016 + * @version $Id$ + */ + public enum KEYS { + /** + * Property to determine if the listener should be disabled. If not set, defaults to false + */ + DISABLED("disabled"), + + /** + * Property for the message service type. Should be a lower case string. See MessageService. + */ + MESSAGE_SERVICE("service"), + + /** + * A hostname or comma separated list (no spaces) of hostnames of servers in a cluster. Can have ports included + * as well.
+ * Examples: + *
    + *
  • server1.appc.openecomp.org
  • + *
  • server1.appc.openecomp.org:3904
  • + *
  • server1.appc.openecomp.org,server2.appc.openecomp.org
  • + *
+ */ + HOSTS("poolMembers"), + + /** + * The topic that will be used for DMaaP read operations. Can only support a single topic. + */ + TOPIC_READ("topic.read"), + + /** + * The topic or topics that will be used to write to. If multiple topics are provided, should be in a comma + * seperated list with no spaces.
+ * Examples: + *
    + *
  • TOPIC-1
  • + *
  • TOPIC-1,TOPIC-2,ANOTHER-TOPIC
  • + *
+ */ + TOPIC_WRITE("topic.write"), + + /** + * The highland park filter to use on read requests. If you are reading and writing to the same topic this must + * be provided. Filter should be in JSON format (not url escaped). + */ + TOPIC_READ_FILTER("topic.read.filter"), + + /** + * The amount of time in seconds that the DMaaP polling connection should stay open for. Recommended to be set + * high (around 60 seconds) as most clients will return immediately and not wait until the timeout is up to + * return if they have data. + */ + TOPIC_READ_TIMEOUT("topic.read.timeout"), + + /** + * The name of the client to use. Should be unique to the application. + */ + CLIENT_NAME("client.name"), + + /** + * The id of the client to use. Should be unique for each instance of the application in an environment. + */ + CLIENT_ID("client.name.id"), + + /** + * The User (DMaaP) to use for authentication. If a user is provided, you must include the + * domain name (e.g. example@example.com). + */ + AUTH_USER_KEY("client.key"), + + /** + * The password (DMaaP) to use for authentication. + */ + AUTH_SECRET_KEY("client.secret"), + + /** + * The minimum amount of size of the queue. A client should request new messages once the queue has dropped + * below this size. + */ + THREADS_MIN_QUEUE("threads.queuesize.min"), + + /** + * The maximum size of the queue. A client will request no new messages once this maximum size has been reached. + */ + THREADS_MAX_QUEUE("threads.queuesize.max"), + + /** + * The minimum size of the worker threads pool. This is the pool each listener will use to launch longer running + * operations. + */ + THREADS_MIN_POOL("threads.poolsize.min"), + + /** + * The maximum size of the worker threads pool. This is the pool each listener will use to launch longer running + * operations. + */ + THREADS_MAX_POOL("threads.poolsize.max"); + + private String suffix; + + private KEYS(String val) { + this.suffix = val; + } + + /** + * @param prefix + * The prefix to prepend + * @return a fully property name that corroponds to what is used in the properties file. Format is PREFIX.KEY + */ + public String getFullProp(String prefix) { + return String.format("%s.%s", prefix, suffix); + } + + public String getPropertySuffix() { + return suffix; + } + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ListenerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ListenerImpl.java new file mode 100644 index 000000000..c7599dd1a --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ListenerImpl.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.impl; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.RejectedExecutionException; + +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.demo.model.IncomingMessage; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; + +public class ListenerImpl extends AbstractListener { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class); + + private long startTime = 0; + + public ListenerImpl(ListenerProperties props) { + super(props); + String url = props.getProperty("provider.url"); + LOG.info("DMaaP Provider Endpoint: " + url); + ProviderOperations.setUrl(url); + + // Set Basic Auth + String user = props.getProperty("provider.user"); + String pass = props.getProperty("provider.pass"); + ProviderOperations.setAuthentication(user, pass); + } + + @Override + public void run() { + // Some vars for benchmarking + startTime = System.currentTimeMillis(); + + LOG.info("Running DMaaP Listener"); + + while (run.get()) { + // Only update if the queue is low. otherwise we read in more + // messages than we need + try { + if (executor.getQueue().size() <= QUEUED_MIN) { + LOG.debug("DMaaP queue running low. Querying for more jobs"); + List messages = dmaap.getIncomingEvents(IncomingMessage.class, QUEUED_MAX); + LOG.debug(String.format("Read %d messages from dmaap", messages.size())); + for (IncomingMessage incoming : messages) { + // Acknowledge that we read the event + LOG.info("Acknowledging Message: " + incoming.getHeader().getRequestID()); + + //TODO: Should we post a pending status for 1607 + //dmaap.postStatus(incoming.toOutgoing(Status.PENDING, null).toString()); + } + for (IncomingMessage incoming : messages) { + // Add to pool if still running + if (run.get()) { + LOG.info(String.format("Adding DMaaP message to pool queue [%s]", incoming.getHeader().getRequestID())); + if (incoming.isValid()) { + try { + executor.execute(new WorkerImpl(incoming, dmaap)); + } catch (RejectedExecutionException rejectEx) { + LOG.error("Task Rejected: ", rejectEx); + } + } else { + // Badly formed message + LOG.error("Message was not valid. Rejecting"); + } + } else { + LOG.info("Run stopped. Orphaning Message: " + incoming.getHeader().getRequestID()); + } + } + } + } catch (Exception e) { + LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener"); + LOG.error(EELFResourceManager.format(e)); + LOG.error("DMaaP Listener logging and ignoring the exception, continue..."); + } + } + + LOG.info("Stopping DMaaP Listener thread"); + + // We've told the listener to stop + // TODO - Should we: + // 1) Put a message back on the queue indicating that APP-C never got to + // the message + // or + // 2) Let downstream figure it out after timeout between PENDING and + // ACTIVE messages + } + + @Override + public String getBenchmark() { + long time = System.currentTimeMillis(); + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String runningTime = df.format(new Date(time - startTime)); + + String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime, + executor.getCompletedTaskCount(), executor.getPoolSize()); + LOG.info("***BENCHMARK*** " + out); + return out; + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ProviderOperations.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ProviderOperations.java new file mode 100644 index 000000000..9337edfbf --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/ProviderOperations.java @@ -0,0 +1,294 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.impl; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.json.JSONObject; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.onap.appc.listener.util.Mapper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ProviderOperations { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); + + private static URL url; + + private static String basic_auth; + + //@formatter:off + @SuppressWarnings("nls") + private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}"; + //@formatter:on + + /** + * Calls the AppcProvider to run a topology directed graph + * + * @param msg + * The incoming message to be run + * @return True if the result is success. Never returns false and throws an exception instead. + * @throws UnsupportedEncodingException + * @throws Exception + * if there was a failure processing the request. The exception message is the failure reason. + */ + @SuppressWarnings("nls") + public static boolean topologyDG(IncomingMessage msg) throws APPCException { + if (msg == null) { + throw new APPCException("Provided message was null"); + } + + HttpPost post = null; + try { + // Concatenate the "action" on the end of the URL + String path = url.getPath() + ":" + msg.getAction().getValue(); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + + post = new HttpPost(serviceUrl.toExternalForm()); + post.setHeader("Content-Type", "application/json"); + post.setHeader("Accept", "application/json"); + + // Set Auth + if (basic_auth != null) { + post.setHeader("Authorization", "Basic " + basic_auth); + } + + //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl()); + String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getPgStreams()); + StringEntity entity = new StringEntity(body); + entity.setContentType("application/json"); + post.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + int httpCode = 0; + String respBody = null; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + throw new APPCException(e); + } + + if (httpCode == 200 && respBody != null) { + JSONObject json; + try { + json = Mapper.toJsonObject(respBody); + } catch (Exception e) { + LOG.error("Error prcoessing response from provider. Could not map response to json", e); + throw new APPCException("APPC has an unknown RPC error"); + } + boolean success; + String reason; + try { + JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header"); + success = header.getBoolean("success"); + reason = header.getString("reason"); + } catch (Exception e) { + LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e); + throw new APPCException("APPC has an unknown RPC error"); + } + if (success) { + return true; + } + String reasonStr = reason == null ? "Unknown" : reason; + LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr)); + throw new APPCException(reasonStr); + + } + throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody)); + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user + * The user with optional domain name + * @param password + * The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basic_auth = null; + } + return basic_auth; + } + + /** + * Builds the request body for a topology operation + * + * @param id + * The request id + * @param url + * The vm's url + * + * @param pgstreams + * The streams to send to the traffic generator + * + * @return A String containing the request body + */ + private static String buildReqest(String id, String url, String pgstreams) { + + return String.format(TEMPLATE, id, url, pgstreams); + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals("https")) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); + registry.register(new Scheme("https", sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + client = new DefaultHttpClient(); + } + } else if (url.getProtocol().equals("http")) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + public static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[] { + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/WorkerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/WorkerImpl.java new file mode 100644 index 000000000..ef72c6e12 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/impl/WorkerImpl.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.onap.appc.listener.demo.model.Status; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class WorkerImpl implements Runnable { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(WorkerImpl.class); + + // Should have all of the data we need for processing + private IncomingMessage event; + + // So we can post messages from inside the worker. + private EventHandler dmaap; + + public WorkerImpl(IncomingMessage message, EventHandler dmaap) { + this.event = message; + this.dmaap = dmaap; + } + + @Override + public void run() { + LOG.debug(String.format("Started working on %s", event.getHeader().getRequestID())); + + dmaap.postStatus(event.toOutgoing(Status.ACCEPTED)); + // Run the dg in a try catch to handle all exceptions and update the + // message at the end + try { + if (doDG(event)) { + dmaap.postStatus(event.toOutgoing(Status.SUCCESS)); + LOG.debug(String.format("Event %s finished successfully", event.getHeader().getRequestID())); + } else { + // Should never happen. Exception with message should be thrown instead. + LOG.error(String.format( + "We somehow returned false from doDG() instead of throwing exception. Incoming event [%s]", + event.toJson().toString())); + dmaap.postStatus(event.toOutgoing(Status.FAILURE)); + } + + } catch (Exception e) { + // Unknown exception from DG method. Fail and pass the exception + // along + String msg = "Exception: " + e.getMessage(); + LOG.warn(String.format("Event %s finished with failure. %s", event.getHeader().getRequestID(), msg)); + //TODO: should a message be included? there is nothing in the API spec for a msg? + //dmaap.postStatus(event.toOutgoing(Status.FAILURE, msg)); + dmaap.postStatus(event.toOutgoing(Status.FAILURE)); + } + + LOG.debug("Done working on " + event.getHeader().getRequestID()); + } + + private boolean doDG(IncomingMessage msg) throws APPCException { + return ProviderOperations.topologyDG(msg); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Action.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Action.java new file mode 100644 index 000000000..eecc99b4c --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Action.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +public enum Action { + Restart("Restart"), Rebuild("Rebuild"), Migrate("Migrate"), Evacuate("Evacuate"), Snapshot("Snapshot"),modifyconfig("ModifyConfig"); + + /** + * Converts the string to an Action + * + * @param value + * The string to try and convert. Is case insensitive + * @return The action matching the string or null if no match was found. + */ + public static Action toAction(String value) { + if (value != null) { + for (Action e : values()) { + if (e.getValue().toUpperCase().equals(value.toUpperCase())) { + return e; + } + } + } + + return null; + } + + private String value; + + private Action(String valueToUse) { + value = valueToUse; + } + + public final String getValue() { + return value; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/CommonMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/CommonMessage.java new file mode 100644 index 000000000..75a618754 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/CommonMessage.java @@ -0,0 +1,343 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +import java.io.Serializable; +import java.util.Collection; + +import org.json.JSONObject; +import org.onap.appc.listener.util.Mapper; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * This class holds attributes that are common to DMaaP messages both coming in from DCAE and being sent out by APPC + * + */ +@JsonSerialize(include = Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommonMessage implements Serializable { + /* + * { "CommonHeader": { "TimeStamp": "0000-00-00T00:00:00.000Z", "APIver": "1.01", "OriginatorID": "policy.pdp01", + * "RequestID": "b74d13c5-bb26-4b04-992c-4679dfc8280e", "SubrequestID": "1" }, "Action": "RESTART", "Payload": { + * "VServerSelfLink": + * "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345", + * "VNF_NAME": "test", "VMID": "abc12345-1234-5678-890a-abcdefg12345", "TenantID": + * "abcde12345fghijk6789lmnopq123rst", "LOC_ID": "Test", "in-maint": "false", "Identity": + * "http://example.com:5000/v2.0", "Prov_status": "ACTIVE", "OAM_IPV4": "192.168.1.2", + * "is-closed-loop-disabled": "false", "VM_NAME": "basx0001vm034", "OAM_IPV6": "aaaa::bbbb:cccc:dddd:eeee/64" } } + */ + + private static final long serialVersionUID = 1L; + + /* + * The common header + */ + @JsonProperty("CommonHeader") + private CommonHeader header; + + /* + * The payload + */ + @JsonProperty("Payload") + private Payload payload; + + @JsonIgnore + private long startTime = System.currentTimeMillis(); + + /* + * Getters and Setters + */ + + public long getStartTime() { + return startTime; + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + /** + * @return the header + */ + public CommonHeader getHeader() { + return header; + } + + /** + * @param header + * the header to set + */ + public void setHeader(CommonHeader header) { + this.header = header; + } + + /** + * @return the payload + */ + public Payload getPayload() { + return payload; + } + + /** + * @param payload + * the payload to set + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + + /** + * Convenience method to return a json representation of this object. + * + * @return The json representation of this object + */ + public JSONObject toJson() { + return Mapper.toJsonObject(this); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class CommonHeader { + /* + * "CommonHeader": { "TimeStamp": "2016-05-11T13:53:53.146Z", "APIver": "1.01", "OriginatorID": "policy.pdp01", + * "RequestID": "b74d13c5-bb26-4b04-992c-4679dfc8280e", "SubrequestID": "1" } + */ + + /* + * The timestamp of the message + */ + @JsonProperty("TimeStamp") + private String timeStamp; + + /* + * The API version of the message + */ + @JsonProperty("APIver") + private String apiVer; + + /* + * The Originator ID of the message + */ + @JsonProperty("OriginatorID") + private String originatorId; + + /* + * The Request Id of the message + */ + @JsonProperty("RequestID") + private String requestID; + + /* + * The Subrequest Id of the message + */ + @JsonProperty("SubrequestID") + private String subRequestId; + + /** + * @return the timeStamp + */ + public String getTimeStamp() { + return timeStamp; + } + + /** + * @param timeStamp + * the timeStamp to set + */ + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; + } + + /** + * @return the apiVer + */ + public String getApiVer() { + return apiVer; + } + + /** + * @param apiVer + * the apiVer to set + */ + public void setApiVer(String apiVer) { + this.apiVer = apiVer; + } + + /** + * @return the originatorId + */ + public String getOriginatorId() { + return originatorId; + } + + /** + * @param originatorId + * the originatorId to set + */ + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + /** + * @return the requestID + */ + public String getRequestID() { + return requestID; + } + + /** + * @param requestID + * the requestID to set + */ + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + /** + * @return the subRequestId + */ + public String getSubRequestId() { + return subRequestId; + } + + /** + * @param subRequestId + * the subRequestId to set + */ + public void setSubRequestId(String subRequestId) { + this.subRequestId = subRequestId; + } + }; + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Payload { + /* + * "Payload": { "VServerSelfLink": + * "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345", + * "VNF_NAME": "test", "VMID": "abc12345-1234-5678-890a-abcdefg12345", "TenantID": + * "abcde12345fghijk6789lmnopq123rst", "LOC_ID": "Test", "in-maint": "false", "Identity": + * "http://example.com:5000/v2.0", "Prov_status": "ACTIVE", "OAM_IPV4": "192.168.1.2", + * "is-closed-loop-disabled": "false", "VM_NAME": "test", "OAM_IPV6": "aaaa::bbbb:cccc:dddd:eeee/64" } + */ + + /* + * The TenantID of the message + */ + @JsonProperty("generic-vnf.vnf-id") + private String genericVnfId; + + /** + * @return the TenantID + */ + public String getGenericVnfId() { + return genericVnfId; + } + + /** + * @param TenantID + * the TenantID to set + */ + public void setGenericVnfId(String genericVnfId) { + this.genericVnfId = genericVnfId; + } + + @JsonProperty("pg-streams") + private pgStreams pgStreams; + + /** + * @return the TenantID + */ + + public String getPgStreams() { + String r = "{\\\"pg-streams\\\": {\\\"pg-stream\\\":["; + boolean first = true; + for(pgStream p : this.pgStreams.streams){ + String n = "{\\\"id\\\":\\\""+p.getId()+"\\\", \\\"is-enabled\\\":\\\""+p.getIsEnabled()+"\\\"}"; + if(!first){ + r = r.concat(","); + } + first = false; + r = r.concat(n); + } + r= r.concat("]}}"); + return r; + } + + /** + * @param TenantID + * the TenantID to set + */ + public void setPgStreams(pgStreams pgStreams) { + this.pgStreams = pgStreams; + } + + + + + + }; + @JsonIgnoreProperties(ignoreUnknown = true) + public static class pgStreams { + @JsonProperty("pg-stream") + private Collection streams; + + public Collection getStreams() { + return streams; + } + + public void setStreams(Collection streams) { + this.streams = streams; + } + + + }; + @JsonIgnoreProperties(ignoreUnknown = true) + public static class pgStream{ + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getIsEnabled() { + return isEnabled; + } + public void setIsEnabled(String isEnabled) { + this.isEnabled = isEnabled; + } + @JsonProperty("id") + private String id; + @JsonProperty("is-enabled") + private String isEnabled; + }; + + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/IncomingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/IncomingMessage.java new file mode 100644 index 000000000..555329106 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/IncomingMessage.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; + +/** + * This class represents a message coming in from DCAE. + * + */ +@JsonSerialize(include = Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class IncomingMessage extends CommonMessage { + + private static final long serialVersionUID = 1L; + + /* + * The action being requested. Its presence signals that it is an incoming message and it is not present on outgoing + * messages + */ + //TODO; use enum + @JsonProperty("Action") + private String action; + + + public String getRequest() { + return action; + } + + @JsonIgnore + public Action getAction() { + return Action.toAction(action); + } + + public void setRequest(String request) { + this.action = request; + } + +// @Override +// public String toString() { +// String time = getRequestTime() != null ? getRequestTime() : "N/A"; +// // String req = request != null ? request : "N/A"; +// return String.format("[%s - %s]", time, getId()); +// } + +// public String toOutgoing(Status status) { +// return toOutgoing(status); +// } + + public String toOutgoing(Status status) { + OutgoingMessage out = new OutgoingMessage(this); + out.setResponse(status); + return out.toResponse().toString(); + } + + /** + * Determines if this message should be parsed parsed. Will eventually check that the message is well formed, has + * all required fields, and had not exceeded any timing restrictions. + * + * @return True if the message should be parsed. False otherwise + */ + public boolean isValid() { + return true; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/OutgoingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/OutgoingMessage.java new file mode 100644 index 000000000..a3294dd8c --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/OutgoingMessage.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +import java.net.InetAddress; +import java.security.SecureRandom; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import org.json.JSONObject; +import org.onap.appc.listener.util.Mapper; +import org.onap.appc.util.Time; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; + +/** + * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request + * + */ +@JsonSerialize(include = Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class OutgoingMessage extends CommonMessage { + + public OutgoingMessage() { + + } + + public OutgoingMessage(IncomingMessage msg) { + setHeader(msg.getHeader()); + setPayload(msg.getPayload()); +// setId(msg.getId()); +// setOriginalRequest(msg.getRequest()); +// setRequestClient(msg.getRequestClient()); +// setRequestTime(msg.getRequestTime()); +// setVmName(msg.getVmName()); +// setFromSystem(generateFrom()); +// setResponse(Status.PENDING); +// setPolicyName(msg.getPolicyName()); +// setPolicyVersion(msg.getPolicyVersion()); +// setStartTime(msg.getStartTime()); + } + + private static final long serialVersionUID = -5447940920271469613L; + /* + * The status of the response + */ + @JsonProperty("Status") + private OutStatus status; + + /** + * @return the status + */ + public OutStatus getStatus() { + return status; + } + + /** + * @param status the status to set + */ + public void setStatus(OutStatus status) { + this.status = status; + } + + public void updateResponseTime() { + SecureRandom rand = new SecureRandom(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String date = df.format(new Date(Time.utcTime())); + //this.responseTime = String.format("%s%03d", date, rand.nextInt(1000)); + } + + public String generateFrom() { + String name; + try { + InetAddress iAddress = InetAddress.getLocalHost(); + name = iAddress.getCanonicalHostName(); + } catch (Exception e) { + // Could not get anything from the InetAddress + name = "UnknownHost"; + } + return "appc@" + name; + } + + public JSONObject toResponse() { + updateResponseTime(); + JSONObject json = Mapper.toJsonObject(this); + + if (!json.has("message")) { + // If there is no message, parrot the status (response field) + // TODO - Can this be removed for 1602 making message truely optional? + //json.put("message", this.getResponse().toString()); + } + + // Removed duplication of status from message for 1602 + // json.put("message", String.format("%s: %s", request, json.get("message"))); + + return json; + } + +// @Override +// public String toString() { +// return String.format("%s - %s", getId(), getResponse()); +// } + + public static class OutStatus{ + @JsonProperty("Code") + private String code; + + @JsonProperty("Value") + private String value; + + /** + * @return the code + */ + public String getCode() { + return code; + } + + /** + * @param code the code to set + */ + public void setCode(String code) { + this.code = code; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + } + + public void setResponse(Status newStatus) { + if(this.status == null){ + this.status = new OutStatus(); + } + + switch (newStatus){ + case ACCEPTED: + this.status.setValue(newStatus.getValue()); + this.status.setCode("100"); + break; + + case FAILURE: + this.status.setValue(newStatus.getValue()); + this.status.setCode("500"); + break; + + case SUCCESS: + this.status.setValue(newStatus.getValue()); + this.status.setCode("400"); + break; + default: + break; + + } + + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Status.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Status.java new file mode 100644 index 000000000..09db11402 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/demo/model/Status.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +public enum Status { + /* + * APP-C acknowledges that it has read the event off of the wire. This is the initial status of an OutgoingEvent + */ + ACCEPTED("ACCEPTED"), + + /* + * APP-C has finished processing the event without errors + */ + SUCCESS("SUCCESS"), + + /* + * APP-C has finished processing the event with errors + */ + FAILURE("FAILURE"); + + /** + * Converts the string to an Status + * + * @param value + * The string to try and convert. Is case insensitive + * @return The status matching the string or null if no match was found. + */ + public static Status toStatus(String value) { + if (value != null) { + for (Status e : values()) { + if (e.getValue().toUpperCase().equals(value.toUpperCase())) { + return e; + } + } + } + + return null; + } + + private String value; + + private Status(String valueToUse) { + value = valueToUse; + } + + public final String getValue() { + return value; + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/ControllerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/ControllerImpl.java new file mode 100644 index 000000000..b830b6fc7 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/ControllerImpl.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.impl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.onap.appc.listener.Controller; +import org.onap.appc.listener.Listener; +import org.onap.appc.listener.ListenerProperties; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +/** + * A common implementation of a controller. This controller should not need to be modified to implement new listeners + * + */ +public class ControllerImpl implements Controller { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(ControllerImpl.class); + + private int LISTENER_COUNT = 1; + + private Map listeners = null; + + private ThreadPoolExecutor executor; + + /** + * Creates a Controller with the set of listener properties which will be used to start listener threads. + * + * @param properties + * A non null Set of ListenerProperties + */ + public ControllerImpl(Set properties) { + listeners = new HashMap(); + for (ListenerProperties props : properties) { + if (props.getClass() != null) { + listeners.put(props, null); + } else { + LOG.error(String.format( + "The ListenerProperties %s has no Listener class associated with it and will not run.", props)); + } + } + + LISTENER_COUNT = properties.size(); + + executor = new ThreadPoolExecutor(LISTENER_COUNT, LISTENER_COUNT, 1, TimeUnit.SECONDS, + new ArrayBlockingQueue(LISTENER_COUNT)); + + // Custom Named thread factory + BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build(); + executor.setThreadFactory(threadFactory); + } + + @Override + public void start() { + LOG.info("Starting DMaaP Controller."); + for (ListenerProperties props : listeners.keySet()) { + try { + if (props.isDisabled()) { + LOG.warn(String.format("The listener %s is disabled and will not be run", props.getPrefix())); + } else { + Listener l = props.getListenerClass().getConstructor(ListenerProperties.class).newInstance(props); + l.setListenerId(props.getPrefix()); + listeners.put(props, l); + executor.execute(l); + } + } catch (Exception e) { + e.printStackTrace(); + LOG.error(String.format("Exception while starting listener %s.", props), e); + } + } + } + + @Override + public void stop(boolean stopNow) { + LOG.info("Stopping DMaaP Controller."); + Iterator itr = listeners.values().iterator(); + while (itr.hasNext()) { + Listener l = itr.next(); + if (stopNow) { + l.stopNow(); + } else { + l.stop(); + } + itr.remove(); + } + executor.shutdown(); + try { + executor.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + } + + @Override + public Map getListeners() { + return listeners; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/EventHandlerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/EventHandlerImpl.java new file mode 100644 index 000000000..85ce93001 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/impl/EventHandlerImpl.java @@ -0,0 +1,337 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.adapter.factory.MessageService; +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.util.Mapper; +import org.onap.appc.logging.LoggingConstants; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.MDC; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * This class is a wrapper for the DMaaP client provided in appc-dmaap-adapter. Its aim is to ensure + * that only well formed messages are sent and received on DMaaP. + */ +public class EventHandlerImpl implements EventHandler { + + private final EELFLogger LOG = EELFManager.getInstance().getLogger(EventHandlerImpl.class); + + /* + * The amount of time in seconds to keep a connection to a topic open while waiting for data + */ + private int READ_TIMEOUT = 60; + + /* + * The pool of hosts to query against + */ + private Collection pool; + + /* + * The topic to read messages from + */ + private String readTopic; + + /* + * The topic to write messages to + */ + private Set writeTopics; + + /* + * The client (group) name to use for reading messages + */ + private String clientName; + + /* + * The id of the client (group) that is reading messages + */ + private String clientId; + + /* + * The api public key to use for authentication + */ + private String apiKey; + + /* + * The api secret key to use for authentication + */ + private String apiSecret; + + /* + * A json object containing filter arguments. + */ + private String filter_json; + + private MessageService messageService; + + private Consumer reader = null; + private Producer producer = null; + + public EventHandlerImpl(ListenerProperties props) { + pool = new HashSet<>(); + writeTopics = new HashSet<>(); + + if (props != null) { + readTopic = props.getProperty(ListenerProperties.KEYS.TOPIC_READ); + clientName = props.getProperty(ListenerProperties.KEYS.CLIENT_NAME, "APP-C"); + clientId = props.getProperty(ListenerProperties.KEYS.CLIENT_ID, "0"); + apiKey = props.getProperty(ListenerProperties.KEYS.AUTH_USER_KEY); + apiSecret = props.getProperty(ListenerProperties.KEYS.AUTH_SECRET_KEY); + + filter_json = props.getProperty(ListenerProperties.KEYS.TOPIC_READ_FILTER); + + READ_TIMEOUT = Integer + .valueOf(props.getProperty(ListenerProperties.KEYS.TOPIC_READ_TIMEOUT, String.valueOf(READ_TIMEOUT))); + + String hostnames = props.getProperty(ListenerProperties.KEYS.HOSTS); + if (hostnames != null && !hostnames.isEmpty()) { + for (String name : hostnames.split(",")) { + pool.add(name); + } + } + + String writeTopicStr = props.getProperty(ListenerProperties.KEYS.TOPIC_WRITE); + if (writeTopicStr != null) { + for (String topic : writeTopicStr.split(",")) { + writeTopics.add(topic); + } + } + + messageService = MessageService.parse(props.getProperty(ListenerProperties.KEYS.MESSAGE_SERVICE)); + + LOG.info(String.format( + "Configured to use %s client on host pool [%s]. Reading from [%s] filtered by %s. Wriring to [%s]. Authenticated using %s", + messageService, hostnames, readTopic, filter_json, writeTopics, apiKey)); + } + } + + @Override + public List getIncomingEvents() { + return getIncomingEvents(1000); + } + + @Override + public List getIncomingEvents(int limit) { + List out = new ArrayList<>(); + LOG.info(String.format("Getting up to %d incoming events", limit)); + // reuse the consumer object instead of creating a new one every time + if (reader == null) { + LOG.info("Getting Consumer..."); + reader = getConsumer(); + } + if (reader != null) { + List items = reader.fetch(READ_TIMEOUT * 1000, limit); + for (String item : items) { + out.add(item); + } + } + LOG.info(String.format("Read %d messages from %s as %s/%s.", out.size(), readTopic, clientName, clientId)); + return out; + } + + @Override + public List getIncomingEvents(Class cls) { + return getIncomingEvents(cls, 1000); + } + + @Override + public List getIncomingEvents(Class cls, int limit) { + List incomingStrings = getIncomingEvents(limit); + return Mapper.mapList(incomingStrings, cls); + } + + @Override + public void postStatus(String event) { + postStatus(null, event); + } + + @Override + public void postStatus(String partition, String event) { + LOG.debug(String.format("Posting Message [%s]", event)); + if (producer == null) { + LOG.info("Getting Producer..."); + producer = getProducer(); + } + producer.post(partition, event); + } + + /** + * Returns a consumer object for direct access to our Cambria consumer interface + * + * @return An instance of the consumer interface + */ + protected Consumer getConsumer() { + LOG.debug(String.format("Getting Consumer: %s %s/%s/%s", pool, readTopic, clientName, clientId)); + if (filter_json == null && writeTopics.contains(readTopic)) { + LOG.error( + "*****We will be writing and reading to the same topic without a filter. This will cause an infinite loop.*****"); + } + + Consumer out = null; + BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + try { + out = ((MessageAdapterFactory) ctx.getService(svcRef)) + .createConsumer(pool, readTopic, clientName, clientId, filter_json, apiKey, apiSecret); + } catch (Exception e) { + //TODO:create eelf message + LOG.error("EvenHandlerImp.getConsumer calling MessageAdapterFactor.createConsumer", e); + } + if (out != null) { + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + out.useHttps(true); + break; + } + } + } + } + } + return out; + } + + /** + * Returns a consumer object for direct access to our Cambria producer interface + * + * @return An instance of the producer interface + */ + protected Producer getProducer() { + LOG.debug(String.format("Getting Producer: %s %s", pool, readTopic)); + + Producer out = null; + BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + out = ((MessageAdapterFactory) ctx.getService(svcRef)) + .createProducer(pool, writeTopics, apiKey, apiSecret); + if (out != null) { + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + out.useHttps(true); + break; + } + } + } + } + } + return out; + } + + @Override + public void closeClients() { + LOG.debug("Closing Consumer and Producer DMaaP clients"); + if (reader != null) { + reader.close(); + } + if (producer != null) { + producer.close(); + } + } + + @Override + public String getClientId() { + return clientId; + } + + @Override + public void setClientId(String clientId) { + this.clientId = clientId; + } + + @Override + public String getClientName() { + return clientName; + } + + @Override + public void setClientName(String clientName) { + this.clientName = clientName; + MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, clientName); + } + + @Override + public void addToPool(String hostname) { + pool.add(hostname); + } + + @Override + public Collection getPool() { + return pool; + } + + @Override + public void removeFromPool(String hostname) { + pool.remove(hostname); + } + + @Override + public String getReadTopic() { + return readTopic; + } + + @Override + public void setReadTopic(String readTopic) { + this.readTopic = readTopic; + } + + @Override + public Set getWriteTopics() { + return writeTopics; + } + + @Override + public void setWriteTopics(Set writeTopics) { + this.writeTopics = writeTopics; + } + + @Override + public void clearCredentials() { + apiKey = null; + apiSecret = null; + } + + @Override + public void setCredentials(String key, String secret) { + apiKey = key; + apiSecret = secret; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/util/Mapper.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/util/Mapper.java new file mode 100644 index 000000000..bd77041ec --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/onap/appc/listener/util/Mapper.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.util; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.databind.JsonNode; +import org.json.JSONObject; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class Mapper { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(Mapper.class); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * @return The object mapper that we are using. + */ + public static ObjectMapper getMapper() { + return mapper; + } + + /** + * Convert a String to a DcaeMessage + * + * @param data + * The json string to try and parse + * @return A DcaeMessage from the json string or null if it could not + */ + public static T mapOne(String data, Class cls) { + try { + return mapper.readValue(data, cls); + } catch (Exception e) { + LOG.warn(String.format("Could not map [ %s ] to %s", data, cls.getName()), e); + return null; + } + } + + public static List mapList(List data, Class cls) { + List out = new ArrayList(); + for (String s : data) { + T tmp = Mapper.mapOne(s, cls); + if (tmp != null) { + out.add(tmp); + } + } + return out; + } + + /** + * Convenience method to try and convert objects to json String + * + * @param obj + * The object to try and convert + * @return A json string representing the object or null if it could not be converted + */ + public static String toJsonString(Object obj) { + String jsonStr; + try { + if (obj instanceof JSONObject) { + jsonStr = obj.toString(); + }else { + jsonStr = mapper.writeValueAsString(obj); + } + return jsonStr; + } catch (Exception e) { + LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); + return null; + } + } + + public static JSONObject toJsonObject(Object obj) { + String jsonStr; + try { + if (obj.getClass().equals(String.class)) { + jsonStr = (String) obj; + } else { + jsonStr = mapper.writeValueAsString(obj); + } + return new JSONObject(jsonStr); + } catch (Exception e) { + LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); + return null; + } + } + public static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + public static JsonNode toJsonNode(Object obj) { + JsonNode jsonNode = null; + String jsonStr = toJsonString(obj); + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); + } + } + return jsonNode; + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AbstractListener.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AbstractListener.java deleted file mode 100644 index 89c75a357..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AbstractListener.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import java.security.SecureRandom; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.onap.appc.listener.impl.EventHandlerImpl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public abstract class AbstractListener implements Listener { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractListener.class); - - protected AtomicBoolean run = new AtomicBoolean(false); - - protected int QUEUED_MIN = 1; - protected int QUEUED_MAX = 10; - - protected int THREAD_MIN = 4; - protected int THREAD_MAX = THREAD_MIN; // Fixed thread pool - protected int THREAD_SCALE_DOWN_SEC = 10; // Number of seconds to wait until we remove idle threads - - protected ThreadPoolExecutor executor; - - protected EventHandler dmaap; - - protected ListenerProperties props; - - private String listenerId; - - public AbstractListener(ListenerProperties props) { - updateProperties(props); - - dmaap = new EventHandlerImpl(props); - if (dmaap.getClientId().equals("0")) { - dmaap.setClientId(String.valueOf(new SecureRandom().nextInt(1000))); - } - - BlockingQueue threadQueue = new ArrayBlockingQueue(QUEUED_MAX + QUEUED_MIN + 1); - executor = new ThreadPoolExecutor(THREAD_MIN, THREAD_MAX, THREAD_SCALE_DOWN_SEC, TimeUnit.SECONDS, threadQueue, - new JobRejectionHandler()); - - // Custom Named thread factory - BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("DMaaP-Worker-%d").build(); - executor.setThreadFactory(threadFactory); - - run.set(true); - } - - /** - * Starts a loop that will only end after stop() or stopNow() are called. The loop will read messages off the DMaaP - * topic and perform some action on them while writing messages back to DMaaP at critical points in the execution. - * Inherited from Runnable. - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - LOG.error("Listener.run() has not been implemented"); - } - - @Override - public void stop() { - run.set(false); - LOG.info(String.format("Stopping with %d messages in queue", executor.getQueue().size())); - executor.shutdown(); - try { - executor.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - LOG.error("Listener graceful stop() failed", e); - } - - // close DMaaP clients - if (dmaap != null) { - dmaap.closeClients(); - } - LOG.info("Listener Thread Pool Finished"); - } - - @Override - public void stopNow() { - run.set(false); - LOG.info(String.format("StopNow called. Orphaning %d messages in the queue", executor.getQueue().size())); - executor.getQueue().clear(); - stop(); - } - - @Override - public String getBenchmark() { - return String.format("%s - No benchmarking implemented.", getListenerId()); - } - - @Override - public String getListenerId() { - return listenerId; - } - - // Sets the id of the listener in - @Override - public void setListenerId(String id) { - listenerId = id; - } - - private void updateProperties(ListenerProperties properties) { - this.props = properties; - QUEUED_MIN = - Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_QUEUE, String.valueOf(QUEUED_MIN))); - QUEUED_MAX = - Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_QUEUE, String.valueOf(QUEUED_MAX))); - THREAD_MIN = - Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_POOL, String.valueOf(THREAD_MIN))); - THREAD_MAX = - Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_POOL, String.valueOf(THREAD_MAX))); - - listenerId = props.getPrefix(); - } - - /** - * This class will be used to handle what happens when we cannot add a job because of a ThreadPool issue. It does - * not get invoked if there is any fault with the job. NOTE: So far, this has only been seen when doing a - * {@link Listener#stopNow} - * - */ - class JobRejectionHandler implements RejectedExecutionHandler { - @Override - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - LOG.error(String.format("A job was rejected. [%s]", r)); - } - - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AppcEventListenerActivator.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AppcEventListenerActivator.java deleted file mode 100644 index 0b1eb5328..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AppcEventListenerActivator.java +++ /dev/null @@ -1,201 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.listener.impl.ControllerImpl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -/** - * This activator is used to initialize and terminate the dmaap listener controller and pool(s) - *

- * The DMaaP listener is responsible for listening to a topic on the Universal Event Bus and reading in messages that - * conform to the DCAE message format for APPC. These messages will then be parsed and passed along to the APPC Provider - * to take action on. The listener will also send messages out on DMaaP during critical phases. The messages sent out - * will have a status of: - *

    - *
  • PENDING - The listener has read the message off of DMaaP and has put it in the queue to be processed
  • - *
  • ACTIVE - The listener has begun actually processing the request and is waiting on the appc provider to - * complete the request
  • - *
  • SUCCESS or FAILURE - The listener has gotten a response back from the appc provider. If it is a - * FAILURE, a message should also be included
  • - *
- *

- *

- * Activation of the bundle will provision 1 controller that in turn will provision 1 (or in the future more) listener - * to interact with DMaaP. Each listener will have a queue of messages read off of DMaaP and a thread pool of workers to - * process them. This worker is responsible for contacting appc provider to perform the action - *

- *

- * When the bundle is deactivated, the stopNow() method is called and the thread pool is emptied and all remaining jobs - * are orphaned. Alternatively stop() could be called which would allow all remaining jobs in the queue to complete at - * the cost of longer run time. - *

- * - * @since Aug 30, 2015 - * @version $Id$ - */ -public class AppcEventListenerActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - - /** - * The configuration object - */ - private Configuration configuration; - - /** - * The bundle context - */ - private static BundleContext context; - - /** - * The reference to the actual implementation object that implements the services - */ - private Controller adapter; - - /** - * The logger to be used - */ - private final EELFLogger LOG = EELFManager.getInstance().getLogger(AppcEventListenerActivator.class); - - /** - * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start - * this bundle. This method can be used to register services or to allocate any resources that this bundle needs. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @param ctx - * The execution context of the bundle being started. - * @throws java.lang.Exception - * If this method throws an exception, this bundle is marked as stopped and the Framework will remove - * this bundle's listeners, unregister all services registered by this bundle, and release all services - * used by this bundle. - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - @Override - public void start(BundleContext ctx) throws Exception { - LOG.info("Starting Bundle " + getName()); - - context = ctx; - - configuration = ConfigurationFactory.getConfiguration(); - - Properties props = configuration.getProperties(); - - Set listeners = new HashSet<>(); - - // Configure event listener for the demo use case - ListenerProperties demoProps = new ListenerProperties("appc.demo", props); - demoProps.setListenerClass(org.onap.appc.listener.demo.impl.ListenerImpl.class); - listeners.add(demoProps); - - // =========================================================================== - - ListenerProperties clLCMProps = new ListenerProperties("appc.LCM", props); - clLCMProps.setListenerClass(org.onap.appc.listener.LCM.impl.ListenerImpl.class); - listeners.add(clLCMProps); - - // Configure the OAM properties - String oamPropKeyPrefix = "appc.OAM"; - ListenerProperties oamProps = new ListenerProperties(oamPropKeyPrefix, props); - if (isAppcOamPropsListenerEnabled(oamProps)) { - oamProps.setListenerClass(org.onap.appc.listener.LCM.impl.ListenerImpl.class); - listeners.add(oamProps); - } else { - LOG.warn(String.format("The listener %s is disabled and will not be run", oamPropKeyPrefix)); - } - - adapter = new ControllerImpl(listeners); - if (ctx != null && registration == null) { - LOG.info("Registering service DMaaP Controller"); - registration = ctx.registerService(Controller.class, adapter, null); - } - adapter.start(); - - LOG.info("DMaaP Listener started successfully"); - } - - /** - * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop - * the bundle. In general, this method should undo the work that the BundleActivator.start method started. There - * should be no active threads that were started by this bundle when this bundle returns. A stopped bundle must not - * call any Framework objects. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @param ctx - * The execution context of the bundle being stopped. - * @throws java.lang.Exception - * If this method throws an exception, the bundle is still marked as stopped, and the Framework will - * remove the bundle's listeners, unregister all services registered by the bundle, and release all - * services used by the bundle. * - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - @Override - public void stop(BundleContext ctx) throws Exception { - boolean stopNow = true; - LOG.info("Stopping DMaaP Listener. StopNow=" + stopNow); - adapter.stop(stopNow); - if (registration != null) { - registration.unregister(); - registration = null; - } - LOG.info("DMaaP Listener stopped successfully"); - } - - public String getName() { - return "DMaaP Listener"; - } - - /** - * Check if AppcOam props disable listener or not - * - * @param listenerProperties of ListenerProperties objext - * @return false only if AppcOam disabled key is defined and equal to true. Otherwise, return true. - */ - private boolean isAppcOamPropsListenerEnabled(ListenerProperties listenerProperties) { - final Properties appcOamProperties = listenerProperties.getProperties(); - - return appcOamProperties == null - || !Boolean.parseBoolean(appcOamProperties.getProperty( - ListenerProperties.KEYS.DISABLED.getPropertySuffix())); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Controller.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Controller.java deleted file mode 100644 index 4fce8972b..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Controller.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import java.util.Map; - -/** - * A controller is responsible for creating a listener for each ListenerProperties object that is passed in to it on - * instantiation. The controller will create a thread pool that will contain all of the listener threads so no listener - * can crash the controller. - * - */ -public interface Controller { - - /** - * Creates a new thread in the thread pool for an implementation of the {@see #Listener} class set in the - * ListenerProperties. This thread is run immediately after it is created. - */ - public void start(); - - /** - * Stops each of the listeners known by this controller. Takes an optional parameter that indicates the the listener - * should stop immediately rather than waiting for all threads to complete. - * - * @param stopNow - * Determines what method the listeners should use to shutdown. If true, listeners will use the stopNow() - * method. Otherwise they will use the stop() method. - */ - public void stop(boolean stopNow); - - /** - * @return A Map of ListenerProperties and the Listener object that is running in the controllers thread pool. - */ - public Map getListeners(); - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/EventHandler.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/EventHandler.java deleted file mode 100644 index 9ec81b831..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/EventHandler.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import java.util.Collection; -import java.util.List; -import java.util.Set; - -/** - * EventHandler defines a class that wraps DMaaP operations (most notably Get Message and Post Message) to make them - * easier to use. - * - */ -public interface EventHandler { - - /** - * Gets a list of messages as Strings on the read topic. - * - * @return A list of String messages. Never returns null. - */ - public List getIncomingEvents(); - - /** - * Gets a list of messages as String on the read topic. - * - * @param limit - * The maximum amount of entries to return - * @return A list of String messages. Never returns null. - */ - public List getIncomingEvents(int limit); - - /** - * Gets a list of messages Mapped to the given Class. If a message cannot be mapped to that class, it is discarded. - * - * @param cls - * The class to map the message to. - * @return A list of objects of the provided class. Never returns null. - */ - public List getIncomingEvents(Class cls); - - /** - * Gets a list of messages Mapped to the given Class. If a message cannot be mapped to that class, it is discarded. - * - * @param cls - * The class to map the message to. - * @param limit - * The maximum amount of entries to return - * @return A list of objects of the provided class. Never returns null. - */ - public List getIncomingEvents(Class cls, int limit); - - /** - * Posts the String message to the write topic(s). - * - * @param event - * The String to post. - */ - public void postStatus(String event); - - /** - * Posts the String message to the write topic(s) on the specified partition. Partitions are only used to guarantee - * ordering and do not impact if data is retreived. - * - * @param partition - * The partition to post to or null if no partition should be used. - * @param event - * The String to post. - */ - public void postStatus(String partition, String event); - - /** - * @return The client/group id used to read messages - */ - public String getClientId(); - - /** - * Set the client/group id used to read messages - * - * @param clientId - * The new clientId to use - */ - public void setClientId(String clientId); - - /** - * @return The client/group name to use. - */ - public String getClientName(); - - /** - * Set the client/group name used to read messages. - * - * @param clientName - * The new clientName to use - */ - public void setClientName(String clientName); - - /** - * @return The name of the topic to read from - */ - public String getReadTopic(); - - /** - * Set the name of the topic to read from. - * - * @param topic - * The new topic to read from - */ - public void setReadTopic(String topic); - - /** - * @return The name of the topic to write to - */ - public Set getWriteTopics(); - - /** - * Set the name of the topic to write to - * - * @param topic - * The new topic to write to - */ - public void setWriteTopics(Set topic); - - /** - * Adds a DMaaP host to the host pool - * - * @param host - * The host to add to the pool in <host>:<port> format - */ - public void addToPool(String host); - - /** - * Remove the host name from the pool if it exists - * - * @param host - * The host to add to the pool in <host>:<port> format - */ - public void removeFromPool(String host); - - /** - * Get all of the hosts in the DMaaP pool - * - * @return A collection of host in <host>:<port> format - */ - public Collection getPool(); - - /** - * Clear any provided api credentials and make future requests as an unauthenticated user - */ - public void clearCredentials(); - - /** - * Set the api credentials and make future requests as an authenticated user - * - * @param access - * The access portion of the credentials (either user name or api key) - * @param secret - * The secret portion of the credentials (either password or api secret) - */ - public void setCredentials(String access, String secret); - - /** - * Close consumer/producer DMaaP clients - */ - public void closeClients(); - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/conv/Converter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/conv/Converter.java deleted file mode 100644 index 4cef18c87..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/conv/Converter.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.conv; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.*; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; -import org.onap.appc.listener.LCM.model.DmaapMessage; -import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; -import org.onap.appc.listener.util.Mapper; - -public class Converter { - - public static DmaapOutgoingMessage convJsonNodeToDmaapOutgoingMessage(DmaapMessage event, JsonNode inObj) { - DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); - outObj.setBody(inObj); - outObj.setRpcName(event.getRpcName()); - outObj.setVersion(event.getVersion()); - outObj.setType("response"); - outObj.setCorrelationID(event.getCorrelationID()); - return outObj; - } - - public static String convDmaapOutgoingMessageToJsonString(DmaapMessage inObj) throws JsonProcessingException { -// return Mapper.toJsonString(inObj); - ObjectMapper objectMapper = new ObjectMapper(); - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) - .writer().withFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); - return writer.writeValueAsString(inObj); - - } - - public static DmaapOutgoingMessage buildDmaapOutgoingMessageWithUnexpectedError(DmaapMessage event,Exception inputException) { - DmaapOutgoingMessage dmaapOutgoingMessage = null; - String errMsg = StringUtils.isEmpty(inputException.getMessage())? inputException.toString() : inputException.getMessage(); - JSONObject commonHeaderJsonObject = Mapper.toJsonObject(event.getBody().get("input").get("common-header")); - JSONObject jsonObjectOutput = new JSONObject().accumulate("common-header", commonHeaderJsonObject).accumulate("status", new JSONObject().accumulate("code",200).accumulate("value",errMsg)); - dmaapOutgoingMessage = new DmaapOutgoingMessage(); - dmaapOutgoingMessage.setRpcName(event.getRpcName()); - dmaapOutgoingMessage.setCorrelationID(event.getCorrelationID()); - dmaapOutgoingMessage.setType("error"); - dmaapOutgoingMessage.setVersion(event.getVersion()); - JSONObject jsonObjectBody = new JSONObject().accumulate("output",jsonObjectOutput); - JsonNode jsonNodeBody = Mapper.toJsonNodeFromJsonString(jsonObjectBody.toString()); - dmaapOutgoingMessage.setBody(jsonNodeBody); - return dmaapOutgoingMessage; - } - - public static String extractRequestIdWithSubId(JsonNode dmaapBody) { - //TODO: null pointer exception if dmaapBody is null, check if null or ensure is not null before calling - JsonNode commonHeaderJsonNode = dmaapBody.get("input").get("common-header"); - String requestId = getValue(commonHeaderJsonNode,"request-id",""); - String subRequestId = getValue(commonHeaderJsonNode,"sub-request-id",""); - if(!StringUtils.isEmpty(subRequestId)){ - requestId = requestId +"-"+subRequestId; - } - return requestId; - } - - public static Integer extractStatusCode(JsonNode event) { - Integer statusCode; - statusCode = event.get("output").get("status").get("code").asInt(); - return statusCode; - } - - private static String getValue(JsonNode jsonNode,String name,String defaultValue){ - if(jsonNode == null){ - return defaultValue; - } - JsonNode childJsonNode = jsonNode.get(name); - if(childJsonNode == null){ - return defaultValue; - } - String value = childJsonNode.asText(); - if(value == null){ - return defaultValue; - } - return value; - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/ListenerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/ListenerImpl.java deleted file mode 100644 index 41a6f92ee..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/ListenerImpl.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.impl; - -import com.fasterxml.jackson.databind.JsonNode; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.listener.AbstractListener; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.LCM.conv.Converter; -import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; -import org.onap.appc.listener.LCM.operation.ProviderOperations; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; -import java.util.concurrent.RejectedExecutionException; - -public class ListenerImpl extends AbstractListener { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class); - - private long startTime = 0; - - private final ProviderOperations providerOperations; - - public ListenerImpl(ListenerProperties props) { - super(props); - - String url = props.getProperty("provider.url"); - LOG.info("DMaaP Provider Endpoint: " + url); - providerOperations = new ProviderOperations(); - providerOperations.setUrl(url); - - // Set Basic Auth - String user = props.getProperty("provider.user"); - String pass = props.getProperty("provider.pass"); - providerOperations.setAuthentication(user, pass); - } - - @Override - public void run() { - // Some vars for benchmarking - startTime = System.currentTimeMillis(); - - LOG.info("Running DMaaP Listener"); - - while (run.get()) { - // Only update if the queue is low. otherwise we read in more - // messages than we need - try { - if (executor.getQueue().size() <= QUEUED_MIN) { - LOG.debug("DMaaP queue running low. Querying for more jobs"); - - - List messages = dmaap.getIncomingEvents(DmaapIncomingMessage.class, QUEUED_MAX); - LOG.debug(String.format("Read %d messages from dmaap", messages.size())); - for (DmaapIncomingMessage incoming : messages) { - // Acknowledge that we read the event - if (isValid(incoming)) { - String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody()); - LOG.info("Acknowledging Message: " + requestIdWithSubId); - } - } - for (DmaapIncomingMessage incoming : messages) { - String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody()); - // Add to pool if still running - if (run.get()) { - if (isValid(incoming)) { - LOG.info(String.format("Adding DMaaP message to pool queue [%s]", requestIdWithSubId)); - try { - executor.execute(new WorkerImpl(incoming, dmaap, providerOperations)); - } catch (RejectedExecutionException rejectEx) { - LOG.error("Task Rejected: ", rejectEx); - } - } else { - // Badly formed message - LOG.error("Message was not valid. Rejecting message: "+incoming); - } - } else { - if (isValid(incoming)) { - LOG.info("Run stopped. Orphaning Message: " + requestIdWithSubId); - } - else { - // Badly formed message - LOG.error("Message was not valid. Rejecting message: "+incoming); - } - } - } - } - } catch (Exception e) { - LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener"); - LOG.error(EELFResourceManager.format(e)); - LOG.error("DMaaP Listener logging and ignoring the exception, continue..."); - } - } - - LOG.info("Stopping DMaaP Listener thread"); - - // We've told the listener to stop - // TODO - Should we: - // 1) Put a message back on the queue indicating that APP-C never got to - // the message - // or - // 2) Let downstream figure it out after timeout between PENDING and - // ACTIVE messages - } - - private boolean isValid(DmaapIncomingMessage incoming) { - return ((incoming != null) && - incoming.getBody() != null - && !StringUtils.isEmpty(incoming.getRpcName())); - } - - @Override - public String getBenchmark() { - long time = System.currentTimeMillis(); - DateFormat df = new SimpleDateFormat("HH:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String runningTime = df.format(new Date(time - startTime)); - - String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime, - executor.getCompletedTaskCount(), executor.getPoolSize()); - LOG.info("***BENCHMARK*** " + out); - return out; - } - - private String getRequestIdWithSubId(JsonNode event){ - String requestId = ""; - try { - requestId = Converter.extractRequestIdWithSubId(event); - } catch (Exception e) { - LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e); - } - return requestId; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/WorkerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/WorkerImpl.java deleted file mode 100644 index 9334a8fad..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/impl/WorkerImpl.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.EventHandler; -import org.onap.appc.listener.LCM.conv.Converter; -import org.onap.appc.listener.LCM.model.DmaapMessage; -import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; -import org.onap.appc.listener.LCM.operation.ProviderOperations; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; - -public class WorkerImpl implements Runnable { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(WorkerImpl.class); - - // Should have all of the data we need for processing - private DmaapMessage event; - - // So we can post messages from inside the worker. - private EventHandler dmaap; - - //so we know were to post the messages - private final ProviderOperations providerOperations; - - - public WorkerImpl(DmaapMessage message, EventHandler dmaap, ProviderOperations providerOperations) { - this.event = message; - this.dmaap = dmaap; - this.providerOperations = providerOperations; - } - - @Override - public void run() { - String requestIdWithSubId = extractRequestIdWithSubId(event.getBody()); - LOG.debug(String.format("Started working on %s", requestIdWithSubId)); - - // Run the dg in a try catch to handle all exceptions and update the - // message at the end - try { - JsonNode outputJsonNode = doDG(event.getRpcName(), event.getBody()); - DmaapOutgoingMessage dmaapOutgoingMessage= Converter.convJsonNodeToDmaapOutgoingMessage(event, outputJsonNode); - postMessageToDMaaP(dmaapOutgoingMessage,requestIdWithSubId); - Integer statusCode = extractStatusCode(dmaapOutgoingMessage.getBody()); - if (ProviderOperations.isSucceeded(statusCode)) { - LOG.debug(String.format("Event %s finished successfully", requestIdWithSubId)); - } else { - LOG.warn(String.format("Event %s failed", requestIdWithSubId)); - } - - } catch (Exception e) { - // Unknown exception from DG method. Fail and pass the exception - // along - String msg = "Exception: " + e.getMessage(); - LOG.error(String.format("Event %s finished with failure. %s", requestIdWithSubId, msg)); - DmaapOutgoingMessage dmaapOutgoingMessage= Converter.buildDmaapOutgoingMessageWithUnexpectedError(event, e); - postMessageToDMaaP(dmaapOutgoingMessage,requestIdWithSubId); - } - - LOG.debug("Done working on " + requestIdWithSubId); - } - - - private Integer extractStatusCode(JsonNode event) { - Integer statusCode = null; - try { - statusCode = Converter.extractStatusCode(event); - } catch (Exception e) { - LOG.error("failed to parse statusCode. Json not in expected format", e); - } - return statusCode; - } - - - private String extractRequestIdWithSubId(JsonNode event){ - String requestId = ""; - try { - requestId = Converter.extractRequestIdWithSubId(event); - } catch (Exception e) { - LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e); - } - return requestId; - } - - - - private void postMessageToDMaaP(DmaapOutgoingMessage dmaapOutgoingMessage,String requestIdWithSubId) { - String dmaapOutgoingMessageJsonString; - try { - dmaapOutgoingMessageJsonString = Converter.convDmaapOutgoingMessageToJsonString(dmaapOutgoingMessage); - dmaap.postStatus(dmaapOutgoingMessage.getCambriaPartition(),dmaapOutgoingMessageJsonString); - } catch (JsonProcessingException e) { - LOG.error("failed to postMessageToDMaaP requestIdWithSubId: "+requestIdWithSubId+" dmaapOutgoingMessage: "+dmaapOutgoingMessage, e); - } - } - - private JsonNode doDG(String rpcName, JsonNode msg) throws APPCException { - return providerOperations.topologyDG(rpcName,msg); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ActionIdentifiers.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ActionIdentifiers.java deleted file mode 100644 index 2419bed65..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ActionIdentifiers.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; - - -public class ActionIdentifiers implements Serializable { - - @JsonProperty("service-instance-id") - private String serviceInstanceId; - @JsonProperty("vnf-id") - private String vnfID; - @JsonProperty("vnfc-name") - private String vnfcName; - @JsonProperty("vserver-id") - private String vserverId; - - public ActionIdentifiers() { - } - - public ActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.serviceInstanceId=actionIdentifiers.getServiceInstanceId(); - this.vnfID=actionIdentifiers.getVnfID(); - this.vnfcName=actionIdentifiers.getVnfcName(); - this.vserverId=actionIdentifiers.getVserverId(); - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getVnfID() { - return vnfID; - } - - public void setVnfID(String vnfID) { - this.vnfID = vnfID; - } - - public String getVnfcName() { - return vnfcName; - } - - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - public String getVserverId() { - return vserverId; - } - - public void setVserverId(String vserverId) { - this.vserverId = vserverId; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/CommonHeader.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/CommonHeader.java deleted file mode 100644 index b7dcc1bb7..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/CommonHeader.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Map; - -import org.onap.appc.util.Time; - -public class CommonHeader implements Serializable { - @JsonProperty("timestamp") - private String timeStamp; - @JsonProperty("api-ver") - private String apiVer; - @JsonProperty("originator-id") - private String originatorId; - @JsonProperty("request-id") - private String requestID; - @JsonProperty("sub-request-id") - private String subRequestId; - @JsonProperty("flags") - private Map flags; - - private static final DateFormat ZULU_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); - - public CommonHeader() { - } - - public CommonHeader(CommonHeader commonHeader) { - // changed to current system time - timeStamp = ZULU_FORMATTER.format(Time.utcDate()); - - apiVer = commonHeader.getApiVer(); - originatorId = commonHeader.getOriginatorId(); - requestID = commonHeader.getRequestID(); - subRequestId = commonHeader.getSubRequestId(); - flags = commonHeader.getFlags(); - } - - - - public String getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(String timeStamp) { - this.timeStamp = timeStamp; - } - - public String getApiVer() { - return apiVer; - } - - public void setApiVer(String apiVer) { - this.apiVer = apiVer; - } - - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - public String getOriginatorId() { - return originatorId; - } - - public void setOriginatorId(String originatorId) { - this.originatorId = originatorId; - } - - public String getSubRequestId() { - return subRequestId; - } - - public void setSubRequestId(String subRequestId) { - this.subRequestId = subRequestId; - } - - public Map getFlags() { - return flags; - } - - public void setFlags(Map flags) { - this.flags = flags; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapIncomingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapIncomingMessage.java deleted file mode 100644 index 32b70d100..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapIncomingMessage.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.json.JSONObject; -import org.onap.appc.listener.util.Mapper; - -/** - * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapIncomingMessage extends DmaapMessage{ - private final static String defaultCambriaPartition = "APP-C"; - - public DmaapIncomingMessage() { - super(); - setCambriaPartition(defaultCambriaPartition); - } - - - @Override - public String toString() { - return "DmaapIncomingMessage{"+super.toString()+"}"; - } -} - diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapMessage.java deleted file mode 100644 index 214783d10..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapMessage.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.JsonNode; - - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapMessage{ - - @JsonProperty("version") - private String version; - - @JsonProperty("type") - private String type; - - @JsonProperty("correlation-id") - private String correlationID; - - @JsonProperty("cambria.partition") - private String cambriaPartition; - - @JsonProperty("rpc-name") - private String rpcName; - - @JsonProperty("body") - private JsonNode body; - - public DmaapMessage() { - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCorrelationID() { - return correlationID; - } - - public void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - public String getCambriaPartition() { - return cambriaPartition; - } - - public void setCambriaPartition(String cambriaPartition) { - this.cambriaPartition = cambriaPartition; - } - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public JsonNode getBody() { - return body; - } - - public void setBody(JsonNode body) { - this.body = body; - } - - @Override - public String toString() { - return "DmaapMessage{" + - "version='" + version + '\'' + - ", type='" + type + '\'' + - ", correlationId='" + correlationID + '\'' + - ", cambriaPartition='" + cambriaPartition + '\'' + - ", rpcName='" + rpcName + '\'' + - ", body=" + body + - '}'; - } - -} - diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapOutgoingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapOutgoingMessage.java deleted file mode 100644 index acf4461aa..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/DmaapOutgoingMessage.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.json.JSONObject; -import org.onap.appc.listener.util.Mapper; - -/** - * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapOutgoingMessage extends DmaapMessage{ - private final static String defaultCambriaPartition = "MSO"; - - public DmaapOutgoingMessage() { - super(); - setCambriaPartition(defaultCambriaPartition); - } - - - @Override - public String toString() { - return "DmaapOutgoingMessage{"+super.toString()+"}"; - } -} - diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/InputBody.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/InputBody.java deleted file mode 100644 index 85aed42d8..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/InputBody.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class InputBody { - - @JsonProperty("common-header") - private CommonHeader commonHeader; - - @JsonProperty("action-identifiers") - private ActionIdentifiers actionIdentifiers; - - @JsonProperty("action") - private String action; - - @JsonProperty("payload") - private Object payload; - - - public Object getPayload() { - return payload; - } - - public void setPayload(Object payload) { - this.payload = payload; - } - @JsonIgnore - public void setPayloadAsString(String payload) { - this.payload = payload; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public ActionIdentifiers getActionIdentifiers() { - return actionIdentifiers; - } - - public void setActionIdentifiers(ActionIdentifiers actionIdentifiers) { - this.actionIdentifiers = actionIdentifiers; - } - - public CommonHeader getCommonHeader() { - return commonHeader; - } - - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - @JsonIgnore - public boolean isValid() { - return getCommonHeader() != null; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/OutputBody.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/OutputBody.java deleted file mode 100644 index 11714e8fb..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/OutputBody.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.json.JSONObject; -import org.onap.appc.listener.util.Mapper; - -/** - * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class OutputBody { - - @JsonProperty("common-header") - private CommonHeader header; - - @JsonProperty("status") - private ResponseStatus status; - - @JsonProperty("payload") - private String payload; - - @JsonProperty("locked") - private String locked; - - public OutputBody() { - } - - - public JSONObject toResponse() { - return Mapper.toJsonObject(this); - } - - public OutputBody(InputBody msg) { - this.header = new CommonHeader(msg.getCommonHeader()); - } - - public String getLocked() { - return locked; - } - - public void setLocked(String locked) { - this.locked = locked; - } - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public CommonHeader getHeader() { - return header; - } - - public void setHeader(CommonHeader header) { - this.header = header; - } - - public ResponseStatus getStatus() { - return status; - } - - public void setStatus(ResponseStatus status) { - this.status = status; - } - - @Override - public String toString() { - return String.format("%s - %s(%s)", getHeader().getRequestID(), getStatus().getCode(), getStatus().getValue()); - } -} - diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ResponseStatus.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ResponseStatus.java deleted file mode 100644 index 114b97b35..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/model/ResponseStatus.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class ResponseStatus { - @JsonProperty("code") - private Integer code; - @JsonProperty("message") - private String value; - - public ResponseStatus() { - } - - public ResponseStatus(Integer code, String value) { - this.code = code; - this.value = value; - } - - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - code = code; - } - - public String getValue() { - return value; - } - - - - public void setValue(String value) { - value = value; - } - - @Override - public String toString() { - return "ResponseStatus{" + - "code=" + code + - ", value='" + value + '\'' + - '}'; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java deleted file mode 100644 index 8fbe4af24..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/GenericProviderOperationRequestFormatter.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.operation; - -import com.fasterxml.jackson.databind.JsonNode; -import org.json.JSONObject; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.LCM.model.InputBody; -import org.onap.appc.listener.LCM.model.ResponseStatus; -import org.onap.appc.listener.util.Mapper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.net.URL; - -public class GenericProviderOperationRequestFormatter implements ProviderOperationRequestFormatter { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(GenericProviderOperationRequestFormatter.class); - - //@formatter:off - @SuppressWarnings("nls") - private final static String TEMPLATE = "{\"input\": %s}"; - //@formatter:on - - @Override - public String buildPath(URL url, String rpcName) { - return url.getPath() + ":"+rpcName; - } - - @Override - public String buildRequest(InputBody msg) { - JSONObject jsonObject = Mapper.toJsonObject(msg); - return String.format(TEMPLATE, jsonObject.toString()); - } - - @Override - public ResponseStatus getResponseStatus(JsonNode responseBody)throws APPCException{ - try { - JsonNode status = responseBody.get("output").get("status"); - return new ResponseStatus(status.get("code").asInt(), status.get("message").asText()); - } catch (Exception e) { - LOG.error("Unknown error processing failed response from provider. Json not in expected format", e); - throw new APPCException("APPC has an unknown RPC error"); - } - } - - @Override - public String getLocked(JSONObject responseBody) throws APPCException { - try { - JSONObject outputObject=responseBody.getJSONObject("output"); - if(outputObject.has("locked")){ - return outputObject.getString("locked"); - }else{ - return null; - } - } catch (Exception e) { - LOG.error("Unknown error processing failed response from provider. Json not in expected format", e); - throw new APPCException("APPC has an unknown RPC error"); - } - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java deleted file mode 100644 index 1e9909a1f..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperationRequestFormatter.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.operation; - -import com.fasterxml.jackson.databind.JsonNode; -import org.json.JSONObject; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.LCM.model.InputBody; -import org.onap.appc.listener.LCM.model.ResponseStatus; - -import java.net.URL; - - -public interface ProviderOperationRequestFormatter { - - String buildPath(URL url, String rpcName); - - String buildRequest(InputBody msg); - - ResponseStatus getResponseStatus(JsonNode json)throws APPCException; - - String getLocked(JSONObject json)throws APPCException; -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperations.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperations.java deleted file mode 100644 index d3ac83d1b..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/LCM/operation/ProviderOperations.java +++ /dev/null @@ -1,263 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM.operation; - -import com.fasterxml.jackson.databind.JsonNode; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.LCM.model.ResponseStatus; -import org.onap.appc.listener.util.Mapper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.*; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -public class ProviderOperations { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); - - private URL url; - private String basic_auth; - - private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter(); - - /** - * Calls the AppcProvider to run a topology directed graph - * - * @param msg The incoming message to be run - * @return True if the result is success. Never returns false and throws an exception instead. - * @throws UnsupportedEncodingException - * @throws Exception if there was a failure processing the request. The exception message is the failure reason. - */ - @SuppressWarnings("nls") - public JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException { - if (msg == null) { - throw new APPCException("Provided message was null"); - } - - HttpPost post = null; - try { - - // Concatenate the "action" on the end of the URL - String path = requestFormatter.buildPath(url, rpcName); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - - post = new HttpPost(serviceUrl.toExternalForm()); - post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - post.setHeader(HttpHeaders.ACCEPT, "application/json"); - - // Set Auth - if (basic_auth != null) { - post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth); - } - - String body = Mapper.toJsonString(msg); - StringEntity entity = new StringEntity(body); - entity.setContentType("application/json"); - post.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - int httpCode = 0; - String respBody = null; - try { - HttpResponse response = client.execute(post); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - throw new APPCException(e); - } - - if (httpCode >= 200 && httpCode < 300 && respBody != null) { - JsonNode json; - try { - json = Mapper.toJsonNodeFromJsonString(respBody); - } catch (Exception e) { - LOG.error("Error processing response from provider. Could not map response to json", e); - throw new APPCException("APPC has an unknown RPC error"); - } - - ResponseStatus responseStatus = requestFormatter.getResponseStatus(json); - - if (!isSucceeded(responseStatus.getCode())) { - LOG.warn(String.format("Operation failed [%s]", msg.toString())); - } - - return json; - } - - throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody)); - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public String getUrl() { - return url.toExternalForm(); - } - - public void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user The user with optional domain name - * @param password The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basic_auth = null; - } - return basic_auth; - } - - @SuppressWarnings("deprecation") - private HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals("https")) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme("https", sf, 443)); - registry.register(new Scheme("https", sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - client = new DefaultHttpClient(); - } - } else if (url.getProtocol().equals("http")) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - public static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[]{ - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - public static boolean isSucceeded(Integer code) { - if (code == null) { - return false; - } - return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Listener.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Listener.java deleted file mode 100644 index 50589c89d..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/Listener.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -/** - * This interface defines a listener that subscribes to a DMaaP topic and continually polls for messages. The - * listener does all operations in the run() method and long running operations should be created in a separate worker - * thread. - * - */ -public interface Listener extends Runnable { - - /** - * Should start a continuous poll to get messages from the message bus only ending when stop() or stopNow() are - * called. - * - * @see java.lang.Runnable#run() - */ - @Override - public void run(); - - /** - * Signals the listener to stop accepting new messages to the queue and to cleanly finish processing all remaining - * messages in the queue. This can take a significant amount of time to complete depending on the thread pool - * characteristics. Similar to {@link #stopNow()} - */ - public void stop(); - - /** - * Signals the listener to stop accepting new messages to the queue and to destroy all remaining messages in the - * queue. This will complete quicker than {@link #stop()} at the cost of discarded requests. Recovery of these - * requests would have to be caught downstream. Similar to {@link #stop()} - */ - public void stopNow(); - - /** - * @return A string that shows various benchmarking data. Can be used by humans to tune the thread pool. - */ - public String getBenchmark(); - - /** - * @return The listener's id when requesting messages from DMaaP. Also known as the group id. - */ - public String getListenerId(); - - /** - * Sets the listener's id to use when requesting messages from DMaaP. Also known as the group id. - * - * @param idString - * The new listener id - */ - public void setListenerId(String idString); -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/ListenerProperties.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/ListenerProperties.java deleted file mode 100644 index 7908d3a1b..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/ListenerProperties.java +++ /dev/null @@ -1,285 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import java.util.Properties; - -/** - * A class for instantiating Listener objects. It is primarily used to hold properties that start with the given prefix. - * It also holds a class that implements {@see Listener} and will be used by the controller to spawn a new listener - * object. - * - * @since Apr 25, 2016 - * @version $Id$ - */ -public class ListenerProperties { - - private String prefix; - - private Class listenerClass; - - private Properties props; - - /** - * Creates a new listener object with the given prefix and properties. Any property starting with the prefix is - * added to the internal properties object with the prefix removed. All other properties are ignored. - * ListenerProperties constructor - * - * @param prefix - * The prefix of the properties to load - * @param allProps - * The properties object to load from. - */ - public ListenerProperties(String prefix, Properties allProps) { - this.prefix = prefix; - props = new Properties(); - - String dottedPrefix = String.format("%s.", prefix); - for (String key : allProps.stringPropertyNames()) { - if (key.startsWith(dottedPrefix) && key.length() > dottedPrefix.length()) { - props.put(key.substring(dottedPrefix.length()), allProps.get(key)); - } - } - } - - /** - * @return The prefix of these properties - */ - public String getPrefix() { - return prefix; - } - - /** - * Sets the listener class. Will be used by {@see Controller} to instantiate the Listener thread for this object - * - * @param cls - * The class to be created. Implements {@see Listener} - */ - public void setListenerClass(Class cls) { - this.listenerClass = cls; - } - - /** - * @return The class that will be used by {@see Controller} to instantiate the Listener thread for this object - */ - public Class getListenerClass() { - return listenerClass; - } - - /** - * Returns a property matching a given KEYS - * - * @param key - * The KEYS object who's value to return. - * @return The value of the property or null if none exists - */ - public String getProperty(KEYS key) { - return getProperty(key, null); - } - - /** - * Returns a property matching a given string. - * - * @param key - * The key who's value to return. - * @return The value of the property or null if none exists - */ - public String getProperty(String key) { - return getProperty(key, null); - } - - /** - * Returns a property matching a given KEYS - * - * @param key - * The KEYS object who's value to return. - * @param defaultValue - * The value to return if the property is not found - * @return The value of the property or null if none exists - */ - public String getProperty(KEYS key, String defaultValue) { - return getProperty(key.getPropertySuffix(), defaultValue); - } - - /** - * Returns a property matching a given string. - * - * @param key - * The key who's value to return. - * @param defaultValue - * The value to return if the property is not found - * @return The value of the property or null if none exists - */ - public String getProperty(String key, String defaultValue) { - return props.getProperty(key, defaultValue); - } - - /** - * @return The properties object containing all properties - */ - public Properties getProperties() { - return props; - } - - /** - * Reads the prefix.disabled property to determine if the listener is disabled and should not be run by the - * controller. Defaults to false if property not set or value cannot be parsed. - * - * @return true if the listener is disabled and should not be started. false if the listener should be start - * normally (default). - */ - public boolean isDisabled() { - return Boolean.valueOf(getProperty(KEYS.DISABLED, "false")); - } - - @Override - public String toString() { - return String.format("%s", prefix); - } - - - /** - * Set of common properties that will be used by most systems. Primarily relating to DMaaP and ThreadPools - * - * @since Apr 25, 2016 - * @version $Id$ - */ - public enum KEYS { - /** - * Property to determine if the listener should be disabled. If not set, defaults to false - */ - DISABLED("disabled"), - - /** - * Property for the message service type. Should be a lower case string. See MessageService. - */ - MESSAGE_SERVICE("service"), - - /** - * A hostname or comma separated list (no spaces) of hostnames of servers in a cluster. Can have ports included - * as well.
- * Examples: - *
    - *
  • server1.appc.openecomp.org
  • - *
  • server1.appc.openecomp.org:3904
  • - *
  • server1.appc.openecomp.org,server2.appc.openecomp.org
  • - *
- */ - HOSTS("poolMembers"), - - /** - * The topic that will be used for DMaaP read operations. Can only support a single topic. - */ - TOPIC_READ("topic.read"), - - /** - * The topic or topics that will be used to write to. If multiple topics are provided, should be in a comma - * seperated list with no spaces.
- * Examples: - *
    - *
  • TOPIC-1
  • - *
  • TOPIC-1,TOPIC-2,ANOTHER-TOPIC
  • - *
- */ - TOPIC_WRITE("topic.write"), - - /** - * The highland park filter to use on read requests. If you are reading and writing to the same topic this must - * be provided. Filter should be in JSON format (not url escaped). - */ - TOPIC_READ_FILTER("topic.read.filter"), - - /** - * The amount of time in seconds that the DMaaP polling connection should stay open for. Recommended to be set - * high (around 60 seconds) as most clients will return immediately and not wait until the timeout is up to - * return if they have data. - */ - TOPIC_READ_TIMEOUT("topic.read.timeout"), - - /** - * The name of the client to use. Should be unique to the application. - */ - CLIENT_NAME("client.name"), - - /** - * The id of the client to use. Should be unique for each instance of the application in an environment. - */ - CLIENT_ID("client.name.id"), - - /** - * The User (DMaaP) to use for authentication. If a user is provided, you must include the - * domain name (e.g. example@example.com). - */ - AUTH_USER_KEY("client.key"), - - /** - * The password (DMaaP) to use for authentication. - */ - AUTH_SECRET_KEY("client.secret"), - - /** - * The minimum amount of size of the queue. A client should request new messages once the queue has dropped - * below this size. - */ - THREADS_MIN_QUEUE("threads.queuesize.min"), - - /** - * The maximum size of the queue. A client will request no new messages once this maximum size has been reached. - */ - THREADS_MAX_QUEUE("threads.queuesize.max"), - - /** - * The minimum size of the worker threads pool. This is the pool each listener will use to launch longer running - * operations. - */ - THREADS_MIN_POOL("threads.poolsize.min"), - - /** - * The maximum size of the worker threads pool. This is the pool each listener will use to launch longer running - * operations. - */ - THREADS_MAX_POOL("threads.poolsize.max"); - - private String suffix; - - private KEYS(String val) { - this.suffix = val; - } - - /** - * @param prefix - * The prefix to prepend - * @return a fully property name that corroponds to what is used in the properties file. Format is PREFIX.KEY - */ - public String getFullProp(String prefix) { - return String.format("%s.%s", prefix, suffix); - } - - public String getPropertySuffix() { - return suffix; - } - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ListenerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ListenerImpl.java deleted file mode 100644 index c7599dd1a..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ListenerImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.impl; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; -import java.util.concurrent.RejectedExecutionException; - -import org.onap.appc.listener.AbstractListener; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.demo.model.IncomingMessage; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; - -public class ListenerImpl extends AbstractListener { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class); - - private long startTime = 0; - - public ListenerImpl(ListenerProperties props) { - super(props); - String url = props.getProperty("provider.url"); - LOG.info("DMaaP Provider Endpoint: " + url); - ProviderOperations.setUrl(url); - - // Set Basic Auth - String user = props.getProperty("provider.user"); - String pass = props.getProperty("provider.pass"); - ProviderOperations.setAuthentication(user, pass); - } - - @Override - public void run() { - // Some vars for benchmarking - startTime = System.currentTimeMillis(); - - LOG.info("Running DMaaP Listener"); - - while (run.get()) { - // Only update if the queue is low. otherwise we read in more - // messages than we need - try { - if (executor.getQueue().size() <= QUEUED_MIN) { - LOG.debug("DMaaP queue running low. Querying for more jobs"); - List messages = dmaap.getIncomingEvents(IncomingMessage.class, QUEUED_MAX); - LOG.debug(String.format("Read %d messages from dmaap", messages.size())); - for (IncomingMessage incoming : messages) { - // Acknowledge that we read the event - LOG.info("Acknowledging Message: " + incoming.getHeader().getRequestID()); - - //TODO: Should we post a pending status for 1607 - //dmaap.postStatus(incoming.toOutgoing(Status.PENDING, null).toString()); - } - for (IncomingMessage incoming : messages) { - // Add to pool if still running - if (run.get()) { - LOG.info(String.format("Adding DMaaP message to pool queue [%s]", incoming.getHeader().getRequestID())); - if (incoming.isValid()) { - try { - executor.execute(new WorkerImpl(incoming, dmaap)); - } catch (RejectedExecutionException rejectEx) { - LOG.error("Task Rejected: ", rejectEx); - } - } else { - // Badly formed message - LOG.error("Message was not valid. Rejecting"); - } - } else { - LOG.info("Run stopped. Orphaning Message: " + incoming.getHeader().getRequestID()); - } - } - } - } catch (Exception e) { - LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener"); - LOG.error(EELFResourceManager.format(e)); - LOG.error("DMaaP Listener logging and ignoring the exception, continue..."); - } - } - - LOG.info("Stopping DMaaP Listener thread"); - - // We've told the listener to stop - // TODO - Should we: - // 1) Put a message back on the queue indicating that APP-C never got to - // the message - // or - // 2) Let downstream figure it out after timeout between PENDING and - // ACTIVE messages - } - - @Override - public String getBenchmark() { - long time = System.currentTimeMillis(); - DateFormat df = new SimpleDateFormat("HH:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String runningTime = df.format(new Date(time - startTime)); - - String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime, - executor.getCompletedTaskCount(), executor.getPoolSize()); - LOG.info("***BENCHMARK*** " + out); - return out; - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ProviderOperations.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ProviderOperations.java deleted file mode 100644 index 9337edfbf..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/ProviderOperations.java +++ /dev/null @@ -1,294 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.impl; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.json.JSONObject; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.demo.model.IncomingMessage; -import org.onap.appc.listener.util.Mapper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ProviderOperations { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); - - private static URL url; - - private static String basic_auth; - - //@formatter:off - @SuppressWarnings("nls") - private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}"; - //@formatter:on - - /** - * Calls the AppcProvider to run a topology directed graph - * - * @param msg - * The incoming message to be run - * @return True if the result is success. Never returns false and throws an exception instead. - * @throws UnsupportedEncodingException - * @throws Exception - * if there was a failure processing the request. The exception message is the failure reason. - */ - @SuppressWarnings("nls") - public static boolean topologyDG(IncomingMessage msg) throws APPCException { - if (msg == null) { - throw new APPCException("Provided message was null"); - } - - HttpPost post = null; - try { - // Concatenate the "action" on the end of the URL - String path = url.getPath() + ":" + msg.getAction().getValue(); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - - post = new HttpPost(serviceUrl.toExternalForm()); - post.setHeader("Content-Type", "application/json"); - post.setHeader("Accept", "application/json"); - - // Set Auth - if (basic_auth != null) { - post.setHeader("Authorization", "Basic " + basic_auth); - } - - //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl()); - String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getPgStreams()); - StringEntity entity = new StringEntity(body); - entity.setContentType("application/json"); - post.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - int httpCode = 0; - String respBody = null; - try { - HttpResponse response = client.execute(post); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - throw new APPCException(e); - } - - if (httpCode == 200 && respBody != null) { - JSONObject json; - try { - json = Mapper.toJsonObject(respBody); - } catch (Exception e) { - LOG.error("Error prcoessing response from provider. Could not map response to json", e); - throw new APPCException("APPC has an unknown RPC error"); - } - boolean success; - String reason; - try { - JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header"); - success = header.getBoolean("success"); - reason = header.getString("reason"); - } catch (Exception e) { - LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e); - throw new APPCException("APPC has an unknown RPC error"); - } - if (success) { - return true; - } - String reasonStr = reason == null ? "Unknown" : reason; - LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr)); - throw new APPCException(reasonStr); - - } - throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody)); - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public static String getUrl() { - return url.toExternalForm(); - } - - public static void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user - * The user with optional domain name - * @param password - * The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basic_auth = null; - } - return basic_auth; - } - - /** - * Builds the request body for a topology operation - * - * @param id - * The request id - * @param url - * The vm's url - * - * @param pgstreams - * The streams to send to the traffic generator - * - * @return A String containing the request body - */ - private static String buildReqest(String id, String url, String pgstreams) { - - return String.format(TEMPLATE, id, url, pgstreams); - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals("https")) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme("https", sf, 443)); - registry.register(new Scheme("https", sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - client = new DefaultHttpClient(); - } - } else if (url.getProtocol().equals("http")) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - public static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[] { - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/WorkerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/WorkerImpl.java deleted file mode 100644 index ef72c6e12..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/impl/WorkerImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.listener.EventHandler; -import org.onap.appc.listener.demo.model.IncomingMessage; -import org.onap.appc.listener.demo.model.Status; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class WorkerImpl implements Runnable { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(WorkerImpl.class); - - // Should have all of the data we need for processing - private IncomingMessage event; - - // So we can post messages from inside the worker. - private EventHandler dmaap; - - public WorkerImpl(IncomingMessage message, EventHandler dmaap) { - this.event = message; - this.dmaap = dmaap; - } - - @Override - public void run() { - LOG.debug(String.format("Started working on %s", event.getHeader().getRequestID())); - - dmaap.postStatus(event.toOutgoing(Status.ACCEPTED)); - // Run the dg in a try catch to handle all exceptions and update the - // message at the end - try { - if (doDG(event)) { - dmaap.postStatus(event.toOutgoing(Status.SUCCESS)); - LOG.debug(String.format("Event %s finished successfully", event.getHeader().getRequestID())); - } else { - // Should never happen. Exception with message should be thrown instead. - LOG.error(String.format( - "We somehow returned false from doDG() instead of throwing exception. Incoming event [%s]", - event.toJson().toString())); - dmaap.postStatus(event.toOutgoing(Status.FAILURE)); - } - - } catch (Exception e) { - // Unknown exception from DG method. Fail and pass the exception - // along - String msg = "Exception: " + e.getMessage(); - LOG.warn(String.format("Event %s finished with failure. %s", event.getHeader().getRequestID(), msg)); - //TODO: should a message be included? there is nothing in the API spec for a msg? - //dmaap.postStatus(event.toOutgoing(Status.FAILURE, msg)); - dmaap.postStatus(event.toOutgoing(Status.FAILURE)); - } - - LOG.debug("Done working on " + event.getHeader().getRequestID()); - } - - private boolean doDG(IncomingMessage msg) throws APPCException { - return ProviderOperations.topologyDG(msg); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Action.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Action.java deleted file mode 100644 index eecc99b4c..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Action.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -public enum Action { - Restart("Restart"), Rebuild("Rebuild"), Migrate("Migrate"), Evacuate("Evacuate"), Snapshot("Snapshot"),modifyconfig("ModifyConfig"); - - /** - * Converts the string to an Action - * - * @param value - * The string to try and convert. Is case insensitive - * @return The action matching the string or null if no match was found. - */ - public static Action toAction(String value) { - if (value != null) { - for (Action e : values()) { - if (e.getValue().toUpperCase().equals(value.toUpperCase())) { - return e; - } - } - } - - return null; - } - - private String value; - - private Action(String valueToUse) { - value = valueToUse; - } - - public final String getValue() { - return value; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/CommonMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/CommonMessage.java deleted file mode 100644 index 75a618754..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/CommonMessage.java +++ /dev/null @@ -1,343 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -import java.io.Serializable; -import java.util.Collection; - -import org.json.JSONObject; -import org.onap.appc.listener.util.Mapper; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; - -/** - * This class holds attributes that are common to DMaaP messages both coming in from DCAE and being sent out by APPC - * - */ -@JsonSerialize(include = Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class CommonMessage implements Serializable { - /* - * { "CommonHeader": { "TimeStamp": "0000-00-00T00:00:00.000Z", "APIver": "1.01", "OriginatorID": "policy.pdp01", - * "RequestID": "b74d13c5-bb26-4b04-992c-4679dfc8280e", "SubrequestID": "1" }, "Action": "RESTART", "Payload": { - * "VServerSelfLink": - * "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345", - * "VNF_NAME": "test", "VMID": "abc12345-1234-5678-890a-abcdefg12345", "TenantID": - * "abcde12345fghijk6789lmnopq123rst", "LOC_ID": "Test", "in-maint": "false", "Identity": - * "http://example.com:5000/v2.0", "Prov_status": "ACTIVE", "OAM_IPV4": "192.168.1.2", - * "is-closed-loop-disabled": "false", "VM_NAME": "basx0001vm034", "OAM_IPV6": "aaaa::bbbb:cccc:dddd:eeee/64" } } - */ - - private static final long serialVersionUID = 1L; - - /* - * The common header - */ - @JsonProperty("CommonHeader") - private CommonHeader header; - - /* - * The payload - */ - @JsonProperty("Payload") - private Payload payload; - - @JsonIgnore - private long startTime = System.currentTimeMillis(); - - /* - * Getters and Setters - */ - - public long getStartTime() { - return startTime; - } - - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - /** - * @return the header - */ - public CommonHeader getHeader() { - return header; - } - - /** - * @param header - * the header to set - */ - public void setHeader(CommonHeader header) { - this.header = header; - } - - /** - * @return the payload - */ - public Payload getPayload() { - return payload; - } - - /** - * @param payload - * the payload to set - */ - public void setPayload(Payload payload) { - this.payload = payload; - } - - /** - * Convenience method to return a json representation of this object. - * - * @return The json representation of this object - */ - public JSONObject toJson() { - return Mapper.toJsonObject(this); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static class CommonHeader { - /* - * "CommonHeader": { "TimeStamp": "2016-05-11T13:53:53.146Z", "APIver": "1.01", "OriginatorID": "policy.pdp01", - * "RequestID": "b74d13c5-bb26-4b04-992c-4679dfc8280e", "SubrequestID": "1" } - */ - - /* - * The timestamp of the message - */ - @JsonProperty("TimeStamp") - private String timeStamp; - - /* - * The API version of the message - */ - @JsonProperty("APIver") - private String apiVer; - - /* - * The Originator ID of the message - */ - @JsonProperty("OriginatorID") - private String originatorId; - - /* - * The Request Id of the message - */ - @JsonProperty("RequestID") - private String requestID; - - /* - * The Subrequest Id of the message - */ - @JsonProperty("SubrequestID") - private String subRequestId; - - /** - * @return the timeStamp - */ - public String getTimeStamp() { - return timeStamp; - } - - /** - * @param timeStamp - * the timeStamp to set - */ - public void setTimeStamp(String timeStamp) { - this.timeStamp = timeStamp; - } - - /** - * @return the apiVer - */ - public String getApiVer() { - return apiVer; - } - - /** - * @param apiVer - * the apiVer to set - */ - public void setApiVer(String apiVer) { - this.apiVer = apiVer; - } - - /** - * @return the originatorId - */ - public String getOriginatorId() { - return originatorId; - } - - /** - * @param originatorId - * the originatorId to set - */ - public void setOriginatorId(String originatorId) { - this.originatorId = originatorId; - } - - /** - * @return the requestID - */ - public String getRequestID() { - return requestID; - } - - /** - * @param requestID - * the requestID to set - */ - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - /** - * @return the subRequestId - */ - public String getSubRequestId() { - return subRequestId; - } - - /** - * @param subRequestId - * the subRequestId to set - */ - public void setSubRequestId(String subRequestId) { - this.subRequestId = subRequestId; - } - }; - - @JsonIgnoreProperties(ignoreUnknown = true) - public static class Payload { - /* - * "Payload": { "VServerSelfLink": - * "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345", - * "VNF_NAME": "test", "VMID": "abc12345-1234-5678-890a-abcdefg12345", "TenantID": - * "abcde12345fghijk6789lmnopq123rst", "LOC_ID": "Test", "in-maint": "false", "Identity": - * "http://example.com:5000/v2.0", "Prov_status": "ACTIVE", "OAM_IPV4": "192.168.1.2", - * "is-closed-loop-disabled": "false", "VM_NAME": "test", "OAM_IPV6": "aaaa::bbbb:cccc:dddd:eeee/64" } - */ - - /* - * The TenantID of the message - */ - @JsonProperty("generic-vnf.vnf-id") - private String genericVnfId; - - /** - * @return the TenantID - */ - public String getGenericVnfId() { - return genericVnfId; - } - - /** - * @param TenantID - * the TenantID to set - */ - public void setGenericVnfId(String genericVnfId) { - this.genericVnfId = genericVnfId; - } - - @JsonProperty("pg-streams") - private pgStreams pgStreams; - - /** - * @return the TenantID - */ - - public String getPgStreams() { - String r = "{\\\"pg-streams\\\": {\\\"pg-stream\\\":["; - boolean first = true; - for(pgStream p : this.pgStreams.streams){ - String n = "{\\\"id\\\":\\\""+p.getId()+"\\\", \\\"is-enabled\\\":\\\""+p.getIsEnabled()+"\\\"}"; - if(!first){ - r = r.concat(","); - } - first = false; - r = r.concat(n); - } - r= r.concat("]}}"); - return r; - } - - /** - * @param TenantID - * the TenantID to set - */ - public void setPgStreams(pgStreams pgStreams) { - this.pgStreams = pgStreams; - } - - - - - - }; - @JsonIgnoreProperties(ignoreUnknown = true) - public static class pgStreams { - @JsonProperty("pg-stream") - private Collection streams; - - public Collection getStreams() { - return streams; - } - - public void setStreams(Collection streams) { - this.streams = streams; - } - - - }; - @JsonIgnoreProperties(ignoreUnknown = true) - public static class pgStream{ - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getIsEnabled() { - return isEnabled; - } - public void setIsEnabled(String isEnabled) { - this.isEnabled = isEnabled; - } - @JsonProperty("id") - private String id; - @JsonProperty("is-enabled") - private String isEnabled; - }; - - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/IncomingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/IncomingMessage.java deleted file mode 100644 index 555329106..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/IncomingMessage.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; - -/** - * This class represents a message coming in from DCAE. - * - */ -@JsonSerialize(include = Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class IncomingMessage extends CommonMessage { - - private static final long serialVersionUID = 1L; - - /* - * The action being requested. Its presence signals that it is an incoming message and it is not present on outgoing - * messages - */ - //TODO; use enum - @JsonProperty("Action") - private String action; - - - public String getRequest() { - return action; - } - - @JsonIgnore - public Action getAction() { - return Action.toAction(action); - } - - public void setRequest(String request) { - this.action = request; - } - -// @Override -// public String toString() { -// String time = getRequestTime() != null ? getRequestTime() : "N/A"; -// // String req = request != null ? request : "N/A"; -// return String.format("[%s - %s]", time, getId()); -// } - -// public String toOutgoing(Status status) { -// return toOutgoing(status); -// } - - public String toOutgoing(Status status) { - OutgoingMessage out = new OutgoingMessage(this); - out.setResponse(status); - return out.toResponse().toString(); - } - - /** - * Determines if this message should be parsed parsed. Will eventually check that the message is well formed, has - * all required fields, and had not exceeded any timing restrictions. - * - * @return True if the message should be parsed. False otherwise - */ - public boolean isValid() { - return true; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/OutgoingMessage.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/OutgoingMessage.java deleted file mode 100644 index a3294dd8c..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/OutgoingMessage.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -import java.net.InetAddress; -import java.security.SecureRandom; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import org.json.JSONObject; -import org.onap.appc.listener.util.Mapper; -import org.onap.appc.util.Time; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; - -/** - * This class represents a message being sent out to DMaaP by APPC to update listeners on the status of a request - * - */ -@JsonSerialize(include = Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class OutgoingMessage extends CommonMessage { - - public OutgoingMessage() { - - } - - public OutgoingMessage(IncomingMessage msg) { - setHeader(msg.getHeader()); - setPayload(msg.getPayload()); -// setId(msg.getId()); -// setOriginalRequest(msg.getRequest()); -// setRequestClient(msg.getRequestClient()); -// setRequestTime(msg.getRequestTime()); -// setVmName(msg.getVmName()); -// setFromSystem(generateFrom()); -// setResponse(Status.PENDING); -// setPolicyName(msg.getPolicyName()); -// setPolicyVersion(msg.getPolicyVersion()); -// setStartTime(msg.getStartTime()); - } - - private static final long serialVersionUID = -5447940920271469613L; - /* - * The status of the response - */ - @JsonProperty("Status") - private OutStatus status; - - /** - * @return the status - */ - public OutStatus getStatus() { - return status; - } - - /** - * @param status the status to set - */ - public void setStatus(OutStatus status) { - this.status = status; - } - - public void updateResponseTime() { - SecureRandom rand = new SecureRandom(); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String date = df.format(new Date(Time.utcTime())); - //this.responseTime = String.format("%s%03d", date, rand.nextInt(1000)); - } - - public String generateFrom() { - String name; - try { - InetAddress iAddress = InetAddress.getLocalHost(); - name = iAddress.getCanonicalHostName(); - } catch (Exception e) { - // Could not get anything from the InetAddress - name = "UnknownHost"; - } - return "appc@" + name; - } - - public JSONObject toResponse() { - updateResponseTime(); - JSONObject json = Mapper.toJsonObject(this); - - if (!json.has("message")) { - // If there is no message, parrot the status (response field) - // TODO - Can this be removed for 1602 making message truely optional? - //json.put("message", this.getResponse().toString()); - } - - // Removed duplication of status from message for 1602 - // json.put("message", String.format("%s: %s", request, json.get("message"))); - - return json; - } - -// @Override -// public String toString() { -// return String.format("%s - %s", getId(), getResponse()); -// } - - public static class OutStatus{ - @JsonProperty("Code") - private String code; - - @JsonProperty("Value") - private String value; - - /** - * @return the code - */ - public String getCode() { - return code; - } - - /** - * @param code the code to set - */ - public void setCode(String code) { - this.code = code; - } - - /** - * @return the value - */ - public String getValue() { - return value; - } - - /** - * @param value the value to set - */ - public void setValue(String value) { - this.value = value; - } - - } - - public void setResponse(Status newStatus) { - if(this.status == null){ - this.status = new OutStatus(); - } - - switch (newStatus){ - case ACCEPTED: - this.status.setValue(newStatus.getValue()); - this.status.setCode("100"); - break; - - case FAILURE: - this.status.setValue(newStatus.getValue()); - this.status.setCode("500"); - break; - - case SUCCESS: - this.status.setValue(newStatus.getValue()); - this.status.setCode("400"); - break; - default: - break; - - } - - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Status.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Status.java deleted file mode 100644 index 09db11402..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/demo/model/Status.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -public enum Status { - /* - * APP-C acknowledges that it has read the event off of the wire. This is the initial status of an OutgoingEvent - */ - ACCEPTED("ACCEPTED"), - - /* - * APP-C has finished processing the event without errors - */ - SUCCESS("SUCCESS"), - - /* - * APP-C has finished processing the event with errors - */ - FAILURE("FAILURE"); - - /** - * Converts the string to an Status - * - * @param value - * The string to try and convert. Is case insensitive - * @return The status matching the string or null if no match was found. - */ - public static Status toStatus(String value) { - if (value != null) { - for (Status e : values()) { - if (e.getValue().toUpperCase().equals(value.toUpperCase())) { - return e; - } - } - } - - return null; - } - - private String value; - - private Status(String valueToUse) { - value = valueToUse; - } - - public final String getValue() { - return value; - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/ControllerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/ControllerImpl.java deleted file mode 100644 index b830b6fc7..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/ControllerImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.impl; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.onap.appc.listener.Controller; -import org.onap.appc.listener.Listener; -import org.onap.appc.listener.ListenerProperties; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -/** - * A common implementation of a controller. This controller should not need to be modified to implement new listeners - * - */ -public class ControllerImpl implements Controller { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(ControllerImpl.class); - - private int LISTENER_COUNT = 1; - - private Map listeners = null; - - private ThreadPoolExecutor executor; - - /** - * Creates a Controller with the set of listener properties which will be used to start listener threads. - * - * @param properties - * A non null Set of ListenerProperties - */ - public ControllerImpl(Set properties) { - listeners = new HashMap(); - for (ListenerProperties props : properties) { - if (props.getClass() != null) { - listeners.put(props, null); - } else { - LOG.error(String.format( - "The ListenerProperties %s has no Listener class associated with it and will not run.", props)); - } - } - - LISTENER_COUNT = properties.size(); - - executor = new ThreadPoolExecutor(LISTENER_COUNT, LISTENER_COUNT, 1, TimeUnit.SECONDS, - new ArrayBlockingQueue(LISTENER_COUNT)); - - // Custom Named thread factory - BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build(); - executor.setThreadFactory(threadFactory); - } - - @Override - public void start() { - LOG.info("Starting DMaaP Controller."); - for (ListenerProperties props : listeners.keySet()) { - try { - if (props.isDisabled()) { - LOG.warn(String.format("The listener %s is disabled and will not be run", props.getPrefix())); - } else { - Listener l = props.getListenerClass().getConstructor(ListenerProperties.class).newInstance(props); - l.setListenerId(props.getPrefix()); - listeners.put(props, l); - executor.execute(l); - } - } catch (Exception e) { - e.printStackTrace(); - LOG.error(String.format("Exception while starting listener %s.", props), e); - } - } - } - - @Override - public void stop(boolean stopNow) { - LOG.info("Stopping DMaaP Controller."); - Iterator itr = listeners.values().iterator(); - while (itr.hasNext()) { - Listener l = itr.next(); - if (stopNow) { - l.stopNow(); - } else { - l.stop(); - } - itr.remove(); - } - executor.shutdown(); - try { - executor.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - } - } - - @Override - public Map getListeners() { - return listeners; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java deleted file mode 100644 index 85ce93001..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/impl/EventHandlerImpl.java +++ /dev/null @@ -1,337 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.adapter.factory.MessageService; -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.listener.EventHandler; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.util.Mapper; -import org.onap.appc.logging.LoggingConstants; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.MDC; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * This class is a wrapper for the DMaaP client provided in appc-dmaap-adapter. Its aim is to ensure - * that only well formed messages are sent and received on DMaaP. - */ -public class EventHandlerImpl implements EventHandler { - - private final EELFLogger LOG = EELFManager.getInstance().getLogger(EventHandlerImpl.class); - - /* - * The amount of time in seconds to keep a connection to a topic open while waiting for data - */ - private int READ_TIMEOUT = 60; - - /* - * The pool of hosts to query against - */ - private Collection pool; - - /* - * The topic to read messages from - */ - private String readTopic; - - /* - * The topic to write messages to - */ - private Set writeTopics; - - /* - * The client (group) name to use for reading messages - */ - private String clientName; - - /* - * The id of the client (group) that is reading messages - */ - private String clientId; - - /* - * The api public key to use for authentication - */ - private String apiKey; - - /* - * The api secret key to use for authentication - */ - private String apiSecret; - - /* - * A json object containing filter arguments. - */ - private String filter_json; - - private MessageService messageService; - - private Consumer reader = null; - private Producer producer = null; - - public EventHandlerImpl(ListenerProperties props) { - pool = new HashSet<>(); - writeTopics = new HashSet<>(); - - if (props != null) { - readTopic = props.getProperty(ListenerProperties.KEYS.TOPIC_READ); - clientName = props.getProperty(ListenerProperties.KEYS.CLIENT_NAME, "APP-C"); - clientId = props.getProperty(ListenerProperties.KEYS.CLIENT_ID, "0"); - apiKey = props.getProperty(ListenerProperties.KEYS.AUTH_USER_KEY); - apiSecret = props.getProperty(ListenerProperties.KEYS.AUTH_SECRET_KEY); - - filter_json = props.getProperty(ListenerProperties.KEYS.TOPIC_READ_FILTER); - - READ_TIMEOUT = Integer - .valueOf(props.getProperty(ListenerProperties.KEYS.TOPIC_READ_TIMEOUT, String.valueOf(READ_TIMEOUT))); - - String hostnames = props.getProperty(ListenerProperties.KEYS.HOSTS); - if (hostnames != null && !hostnames.isEmpty()) { - for (String name : hostnames.split(",")) { - pool.add(name); - } - } - - String writeTopicStr = props.getProperty(ListenerProperties.KEYS.TOPIC_WRITE); - if (writeTopicStr != null) { - for (String topic : writeTopicStr.split(",")) { - writeTopics.add(topic); - } - } - - messageService = MessageService.parse(props.getProperty(ListenerProperties.KEYS.MESSAGE_SERVICE)); - - LOG.info(String.format( - "Configured to use %s client on host pool [%s]. Reading from [%s] filtered by %s. Wriring to [%s]. Authenticated using %s", - messageService, hostnames, readTopic, filter_json, writeTopics, apiKey)); - } - } - - @Override - public List getIncomingEvents() { - return getIncomingEvents(1000); - } - - @Override - public List getIncomingEvents(int limit) { - List out = new ArrayList<>(); - LOG.info(String.format("Getting up to %d incoming events", limit)); - // reuse the consumer object instead of creating a new one every time - if (reader == null) { - LOG.info("Getting Consumer..."); - reader = getConsumer(); - } - if (reader != null) { - List items = reader.fetch(READ_TIMEOUT * 1000, limit); - for (String item : items) { - out.add(item); - } - } - LOG.info(String.format("Read %d messages from %s as %s/%s.", out.size(), readTopic, clientName, clientId)); - return out; - } - - @Override - public List getIncomingEvents(Class cls) { - return getIncomingEvents(cls, 1000); - } - - @Override - public List getIncomingEvents(Class cls, int limit) { - List incomingStrings = getIncomingEvents(limit); - return Mapper.mapList(incomingStrings, cls); - } - - @Override - public void postStatus(String event) { - postStatus(null, event); - } - - @Override - public void postStatus(String partition, String event) { - LOG.debug(String.format("Posting Message [%s]", event)); - if (producer == null) { - LOG.info("Getting Producer..."); - producer = getProducer(); - } - producer.post(partition, event); - } - - /** - * Returns a consumer object for direct access to our Cambria consumer interface - * - * @return An instance of the consumer interface - */ - protected Consumer getConsumer() { - LOG.debug(String.format("Getting Consumer: %s %s/%s/%s", pool, readTopic, clientName, clientId)); - if (filter_json == null && writeTopics.contains(readTopic)) { - LOG.error( - "*****We will be writing and reading to the same topic without a filter. This will cause an infinite loop.*****"); - } - - Consumer out = null; - BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - try { - out = ((MessageAdapterFactory) ctx.getService(svcRef)) - .createConsumer(pool, readTopic, clientName, clientId, filter_json, apiKey, apiSecret); - } catch (Exception e) { - //TODO:create eelf message - LOG.error("EvenHandlerImp.getConsumer calling MessageAdapterFactor.createConsumer", e); - } - if (out != null) { - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - out.useHttps(true); - break; - } - } - } - } - } - return out; - } - - /** - * Returns a consumer object for direct access to our Cambria producer interface - * - * @return An instance of the producer interface - */ - protected Producer getProducer() { - LOG.debug(String.format("Getting Producer: %s %s", pool, readTopic)); - - Producer out = null; - BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - out = ((MessageAdapterFactory) ctx.getService(svcRef)) - .createProducer(pool, writeTopics, apiKey, apiSecret); - if (out != null) { - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - out.useHttps(true); - break; - } - } - } - } - } - return out; - } - - @Override - public void closeClients() { - LOG.debug("Closing Consumer and Producer DMaaP clients"); - if (reader != null) { - reader.close(); - } - if (producer != null) { - producer.close(); - } - } - - @Override - public String getClientId() { - return clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public String getClientName() { - return clientName; - } - - @Override - public void setClientName(String clientName) { - this.clientName = clientName; - MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, clientName); - } - - @Override - public void addToPool(String hostname) { - pool.add(hostname); - } - - @Override - public Collection getPool() { - return pool; - } - - @Override - public void removeFromPool(String hostname) { - pool.remove(hostname); - } - - @Override - public String getReadTopic() { - return readTopic; - } - - @Override - public void setReadTopic(String readTopic) { - this.readTopic = readTopic; - } - - @Override - public Set getWriteTopics() { - return writeTopics; - } - - @Override - public void setWriteTopics(Set writeTopics) { - this.writeTopics = writeTopics; - } - - @Override - public void clearCredentials() { - apiKey = null; - apiSecret = null; - } - - @Override - public void setCredentials(String key, String secret) { - apiKey = key; - apiSecret = secret; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/util/Mapper.java b/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/util/Mapper.java deleted file mode 100644 index bd77041ec..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/util/Mapper.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.util; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.databind.JsonNode; -import org.json.JSONObject; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class Mapper { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(Mapper.class); - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * @return The object mapper that we are using. - */ - public static ObjectMapper getMapper() { - return mapper; - } - - /** - * Convert a String to a DcaeMessage - * - * @param data - * The json string to try and parse - * @return A DcaeMessage from the json string or null if it could not - */ - public static T mapOne(String data, Class cls) { - try { - return mapper.readValue(data, cls); - } catch (Exception e) { - LOG.warn(String.format("Could not map [ %s ] to %s", data, cls.getName()), e); - return null; - } - } - - public static List mapList(List data, Class cls) { - List out = new ArrayList(); - for (String s : data) { - T tmp = Mapper.mapOne(s, cls); - if (tmp != null) { - out.add(tmp); - } - } - return out; - } - - /** - * Convenience method to try and convert objects to json String - * - * @param obj - * The object to try and convert - * @return A json string representing the object or null if it could not be converted - */ - public static String toJsonString(Object obj) { - String jsonStr; - try { - if (obj instanceof JSONObject) { - jsonStr = obj.toString(); - }else { - jsonStr = mapper.writeValueAsString(obj); - } - return jsonStr; - } catch (Exception e) { - LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); - return null; - } - } - - public static JSONObject toJsonObject(Object obj) { - String jsonStr; - try { - if (obj.getClass().equals(String.class)) { - jsonStr = (String) obj; - } else { - jsonStr = mapper.writeValueAsString(obj); - } - return new JSONObject(jsonStr); - } catch (Exception e) { - LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); - return null; - } - } - public static JsonNode toJsonNodeFromJsonString(String jsonStr) { - JsonNode jsonNode = null; - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); - } - } - return jsonNode; - } - public static JsonNode toJsonNode(Object obj) { - JsonNode jsonNode = null; - String jsonStr = toJsonString(obj); - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to JSONObject.", obj), e); - } - } - return jsonNode; - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/onap/appc/default.properties b/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..839faddac --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,102 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# ${user.home} usually goes to /root if instantiation uses the appc-docker approach + +### ### +### ### +###Properties below that are commented out are/need to be provided in appc.properties### +### ### +### ### + + + + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + + + + + +### ### +###Closed Loop - properties ### +### ### +appc.ClosedLoop.poolMembers=192.168.1.2:3904 +appc.ClosedLoop.topic.read=APPC-TEST2 +appc.ClosedLoop.topic.write=APPC-TEST2 +appc.ClosedLoop.topic.read.filter={"class": "And","filters": [{"class": "Assigned","field": "request"},{"class": "Unassigned","field": "response"}]} +appc.ClosedLoop.client.name=APPC-TEST-CLIENT-EVT-LST-MAIN +appc.ClosedLoop.client.name.id=0 + +# KEY AND SECRET BELOW NEED TO BE MODIFIED TO APPROPRIATE VALUES WHEN THE TOPIC IS API-KEY-BASED AUTH +#dmaap.client.key=random +#dmaap.client.secret=random + +appc.ClosedLoop.threads.queuesize.min=1 +appc.ClosedLoop.threads.queuesize.max=1000 +appc.ClosedLoop.threads.poolsize.min=1 +appc.ClosedLoop.threads.poolsize.max=2 +appc.ClosedLoop.provider.url=http://localhost:8181/restconf/operations/appc-provider +appc.ClosedLoop.provider.url.user=ODL_USER +appc.ClosedLoop.provider.url.pass=ODL_PASS + + + + + +### ### +###Closed Loop - 1607 properties ### +### ### +appc.ClosedLoop1607.poolMembers=192.168.1.2:3904 +appc.ClosedLoop1607.topic.read=MY_DMAAP_TOPIC +appc.ClosedLoop1607.topic.write=MY_DMAAP_TOPIC +appc.ClosedLoop1607.topic.read.filter={"class":"Unassigned","field":"Status"} +appc.ClosedLoop1607.client.name=MY_DMAAP_CLIENT_NAME +appc.ClosedLoop1607.client.name.id=0 +#dmaap.client.key=random +#dmaap.client.secret=random +appc.ClosedLoop1607.threads.queuesize.min=1 +appc.ClosedLoop1607.threads.queuesize.max=1000 +appc.ClosedLoop1607.threads.poolsize.min=1 +appc.ClosedLoop1607.threads.poolsize.max=2 +appc.ClosedLoop.provider.user=ODL_USER +appc.ClosedLoop.provider.pass=ODL_PASS +appc.ClosedLoop1607.provider.url=http://localhost:8181/restconf/operations/appc-provider + + + + + +### ### +### This needs to be changed so that the action can be appended to the end of the URL path ### +### ### +appc.LCM.provider.url=http://localhost:8181/restconf/operations/appc-provider +appc.LCM.poolMembers=192.168.1.2:3904 +appc.LCM.topic.read=DMAAP_TOPIC +appc.LCM.topic.write=DMAAP_TOPIC +appc.LCM.client.name=DMAAP_CLIENT_NAME +appc.LCM.provider.user=ODL_USER +appc.LCM.provider.pass=ODL_URL diff --git a/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 839faddac..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,102 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# ${user.home} usually goes to /root if instantiation uses the appc-docker approach - -### ### -### ### -###Properties below that are commented out are/need to be provided in appc.properties### -### ### -### ### - - - - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - - - - - -### ### -###Closed Loop - properties ### -### ### -appc.ClosedLoop.poolMembers=192.168.1.2:3904 -appc.ClosedLoop.topic.read=APPC-TEST2 -appc.ClosedLoop.topic.write=APPC-TEST2 -appc.ClosedLoop.topic.read.filter={"class": "And","filters": [{"class": "Assigned","field": "request"},{"class": "Unassigned","field": "response"}]} -appc.ClosedLoop.client.name=APPC-TEST-CLIENT-EVT-LST-MAIN -appc.ClosedLoop.client.name.id=0 - -# KEY AND SECRET BELOW NEED TO BE MODIFIED TO APPROPRIATE VALUES WHEN THE TOPIC IS API-KEY-BASED AUTH -#dmaap.client.key=random -#dmaap.client.secret=random - -appc.ClosedLoop.threads.queuesize.min=1 -appc.ClosedLoop.threads.queuesize.max=1000 -appc.ClosedLoop.threads.poolsize.min=1 -appc.ClosedLoop.threads.poolsize.max=2 -appc.ClosedLoop.provider.url=http://localhost:8181/restconf/operations/appc-provider -appc.ClosedLoop.provider.url.user=ODL_USER -appc.ClosedLoop.provider.url.pass=ODL_PASS - - - - - -### ### -###Closed Loop - 1607 properties ### -### ### -appc.ClosedLoop1607.poolMembers=192.168.1.2:3904 -appc.ClosedLoop1607.topic.read=MY_DMAAP_TOPIC -appc.ClosedLoop1607.topic.write=MY_DMAAP_TOPIC -appc.ClosedLoop1607.topic.read.filter={"class":"Unassigned","field":"Status"} -appc.ClosedLoop1607.client.name=MY_DMAAP_CLIENT_NAME -appc.ClosedLoop1607.client.name.id=0 -#dmaap.client.key=random -#dmaap.client.secret=random -appc.ClosedLoop1607.threads.queuesize.min=1 -appc.ClosedLoop1607.threads.queuesize.max=1000 -appc.ClosedLoop1607.threads.poolsize.min=1 -appc.ClosedLoop1607.threads.poolsize.max=2 -appc.ClosedLoop.provider.user=ODL_USER -appc.ClosedLoop.provider.pass=ODL_PASS -appc.ClosedLoop1607.provider.url=http://localhost:8181/restconf/operations/appc-provider - - - - - -### ### -### This needs to be changed so that the action can be appended to the end of the URL path ### -### ### -appc.LCM.provider.url=http://localhost:8181/restconf/operations/appc-provider -appc.LCM.poolMembers=192.168.1.2:3904 -appc.LCM.topic.read=DMAAP_TOPIC -appc.LCM.topic.write=DMAAP_TOPIC -appc.LCM.client.name=DMAAP_CLIENT_NAME -appc.LCM.provider.user=ODL_USER -appc.LCM.provider.pass=ODL_URL diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/TestConverter.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/TestConverter.java new file mode 100644 index 000000000..f9fb7f408 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/TestConverter.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.listener.LCM.conv.Converter; +import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; +import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; +import org.onap.appc.listener.util.Mapper; + +public class TestConverter { + + private String jsonInputBodyStr ="{\"input\":{ \"common-header\": { \"timestamp\": \"2016-08-03T08:50:18.97Z\", \"api-ver\": \"1\", \"originator-id\": \"1\", \"request-id\": \"123\", \"sub-request-id\": \"1\", \"flags\": { \"force\":\"TRUE\", \"ttl\":\"9900\" } }, \"action\": \"Stop\", \"action-identifiers\": { \"vnf-id\": \"TEST\" } }}"; + private String jsonOutputBodyStr ="{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\",\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\",\"request-id\":\"123\",\"originator-id\":\"1\"},\"status\":{\"value\":\"TestException\",\"code\":200}}}"; + + @Test + public void buildDmaapOutgoingMessageWithUnexpectedErrorTest() throws JsonProcessingException { + DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); + String errMsg = "TestException"; + DmaapOutgoingMessage dmaapOutgoingMessage = Converter.buildDmaapOutgoingMessageWithUnexpectedError(dmaapIncomingMessage, new Exception(errMsg)); + int code = dmaapOutgoingMessage.getBody().get("output").get("status").get("code").asInt(); + String value = dmaapOutgoingMessage.getBody().get("output").get("status").get("value").asText(); + Assert.assertEquals(200,code); + Assert.assertEquals(errMsg,value); + } + + private static String expectedDmaapOutgoingMessageAsJsonString = "{\"body\":{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\",\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\",\"request-id\":\"123\",\"originator-id\":\"1\"},\"status\":{\"value\":\"TestException\",\"code\":200}}},\"cambria.partition\":\"MSO\",\"rpc-name\":\"test\"}"; + @Test + public void convDmaapOutgoingMessageToJsonStringTest() throws JsonProcessingException { + DmaapOutgoingMessage dmaapOutgoingMessage = buildDmaapOutgoingMessage(); + String dmaapOutgoingMessageAsJsonString = Converter.convDmaapOutgoingMessageToJsonString(dmaapOutgoingMessage); +// Assert.assertEquals(dmaapOutgoingMessageAsJsonString,dmaapOutgoingMessageAsJsonString); + Assert.assertEquals(expectedDmaapOutgoingMessageAsJsonString,dmaapOutgoingMessageAsJsonString); + } + + private DmaapIncomingMessage buildDmaapIncomingMessage() { + DmaapIncomingMessage dmaapIncomingMessage = new DmaapIncomingMessage(); + dmaapIncomingMessage.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(jsonInputBodyStr); + dmaapIncomingMessage.setBody(jsonNode); + return dmaapIncomingMessage; + + } + + private DmaapOutgoingMessage buildDmaapOutgoingMessage() { + DmaapOutgoingMessage dmaapOutgoingMessage = new DmaapOutgoingMessage(); + dmaapOutgoingMessage.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(jsonOutputBodyStr); + dmaapOutgoingMessage.setBody(jsonNode); + return dmaapOutgoingMessage; + + } + + + @Test + public void extractRequestIdWithSubIdTest() { + DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); + String equestIdWithSubId = Converter.extractRequestIdWithSubId(dmaapIncomingMessage.getBody()); + Assert.assertEquals("123-1",equestIdWithSubId); + } + + @Test + public void extractStatusCodeTest() { + DmaapOutgoingMessage dmaapOutgoingMessage = buildDmaapOutgoingMessage(); + Integer statusCode = Converter.extractStatusCode(dmaapOutgoingMessage.getBody()); + Assert.assertEquals(200L,statusCode.longValue()); + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java new file mode 100644 index 000000000..f28bd8cb3 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.LCM1607.model; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +public class TestJsonGenericMessages {/* + + @Test + public void serializeIncomingMessage() { + + final String expectedJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"APIver\":\"1.01\",\"RequestTrack\":[\"1\",\"4\",\"12\",\"3\"],\"Flags\":null,\"SubrequestID\":null,\"OriginatorID\":\"2\"},\"Payload\":\"{ \\\"command\\\": \\\"start\\\", \\\"target-id\\\": \\\"111\\\", \\\"flag10\\\": {\\\"object-1\\\": {\\\"key-1\\\": \\\"key\\\", \\\"value-1\\\": \\\"value\\\" }} }\",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; + InputBody msg = createIncomingMessage(); + + String json = Mapper.toJsonObject(msg).toString(); + //System.out.println(json); + Assert.assertEquals(expectedJson, json); + } + + @Test + public void deserializeIncomingMessage() throws IOException { + final String originalJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"Flags\":{\"FORCE\":\"Y\",\"TTL\":\"12\"},\"SubrequestID\":\"2345\",\"OriginatorID\":\"2\",\"APIver\":\"1.01\"}, \"Payload\": \" \\\"Graceful\\\" : \\\"Yes\\\" \",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; + + ObjectMapper mapper = new ObjectMapper(); + InputBody msg = mapper.readValue(originalJson, InputBody.class); + + Assert.assertNotNull(msg); + Assert.assertEquals("2016-05-02 19:50:37.09", msg.getCommonHeader().getTimeStamp()); + Assert.assertEquals("1", msg.getCommonHeader().getRequestID()); + Assert.assertEquals("1.01", msg.getCommonHeader().getApiVer()); + Assert.assertEquals("200", msg.getObjectId()); + Assert.assertEquals("100", msg.getTargetId()); + Assert.assertEquals(" \"Graceful\" : \"Yes\" ", msg.getPayload()); + Assert.assertEquals("CONFIGURE", msg.getAction()); + + } + + @Test + public void serializeResponseMessage() { + InputBody imsg = createIncomingMessage(); + OutputBody omsg = new OutputBody(imsg); + omsg.setStatus(new ResponseStatus("200", "OK")); + + String json = Mapper.toJsonObject(omsg).toString(); + System.out.println(json); + //Assert.assertEquals(expectedJson, json); + Assert.assertNotEquals("", json); + + } + + private InputBody createIncomingMessage() { + InputBody msg = new InputBody(); + CommonHeader rh = new CommonHeader(); + rh.setTimeStamp("2016-05-02 19:50:37.09"); + rh.setApiVer("1.01"); + rh.setRequestID("1"); + rh.setOriginatorId("2"); + + + Map flags = new HashMap<>(); + flags.put("FORCE", "Y"); + flags.put("TTL", "12"); + + msg.setCommonHeader(rh); + msg.setAction("CONFIGURE"); + msg.setTargetId("100"); + msg.setObjectId("200"); + msg.setPayloadAsString("{ \"command\": \"start\", \"target-id\": \"111\", \"flag10\": {\"object-1\": {\"key-1\": \"key\", \"value-1\": \"value\" }} }"); + return msg; + } +*/ +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAbstractListener.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAbstractListener.java new file mode 100644 index 000000000..a21bcd416 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAbstractListener.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; +import java.util.concurrent.ThreadPoolExecutor; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; + +public class TestAbstractListener { + + private class DummyListener extends AbstractListener { + public DummyListener(ListenerProperties props) { + super(props); + } + + public boolean getRun() { + return run.get(); + } + + public ThreadPoolExecutor getExecutor() { + return executor; + } + } + + private DummyListener listener; + private ListenerProperties props; + + @Before + public void setup() throws Exception { + Properties regularProps = new Properties(); + regularProps.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); + props = new ListenerProperties("", regularProps); + listener = new DummyListener(props); + } + + @Test + public void testRun() { + Thread t = new Thread(listener); + t.run(); + assertFalse(t.isAlive()); // Should die immediately + } + + @Test + public void testStop() { + listener.stop(); + assertFalse(listener.getRun()); + assertTrue(listener.getExecutor().isShutdown()); + } + + @Test + public void testStopNow() { + listener.stopNow(); + assertFalse(listener.getRun()); + assertTrue(listener.getExecutor().isShutdown()); + } + + @Test + public void testBenchmark() { + String out = listener.getBenchmark(); + assertNotNull(out); + assertTrue(out.contains(listener.getListenerId())); + } + + @Test + public void testListenerId() { + assertEquals(props.getPrefix(), listener.getListenerId()); + listener.setListenerId("newId"); + assertEquals("newId", listener.getListenerId()); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAppcDmaapListenerActivator.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAppcDmaapListenerActivator.java new file mode 100644 index 000000000..6bb96b95c --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestAppcDmaapListenerActivator.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.appc.listener.AppcEventListenerActivator; + +public class TestAppcDmaapListenerActivator { + + @Test + public void testStartStop() { + // TODO - How do we tests activators + AppcEventListenerActivator appc = new AppcEventListenerActivator(); + try { + appc.start(null); + Thread.sleep(2000); + appc.stop(null); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + assertNotNull(appc.getName()); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestListenerProperties.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestListenerProperties.java new file mode 100644 index 000000000..42c263394 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestListenerProperties.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.adapter.factory.MessageService; +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.ListenerProperties.KEYS; + +public class TestListenerProperties { + + private Properties good, bad, both; + private String prefix; + + private ListenerProperties props; + + @Before + public void setup() { + prefix = "test"; + good = new Properties(); + bad = new Properties(); + both = new Properties(); + + good.setProperty(String.format("%s.%s", prefix, "a"), "1"); + good.setProperty(String.format("%s.%s", prefix, "a.b"), "2"); + good.setProperty(String.format("%s.%s", prefix, "a.b.c"), "3"); + + bad.setProperty(prefix, "NA"); + bad.setProperty(prefix + ".", "NA"); + bad.setProperty(String.format("%s.%s", prefix + "x", "bad"), "NA"); + bad.setProperty(String.format("%s.%s", "x" + prefix, "bad"), "NA"); + + for (String key : good.stringPropertyNames()) { + both.put(key, good.getProperty(key)); + } + for (String key : bad.stringPropertyNames()) { + both.put(key, bad.getProperty(key)); + } + + props = new ListenerProperties(prefix, both); + } + + @Test + public void testConstructor() { + props = new ListenerProperties(prefix, good); + assertEquals(prefix, props.getPrefix()); + assertEquals(good.size(), props.getProperties().size()); + + props = new ListenerProperties(prefix, bad); + assertEquals(prefix, props.getPrefix()); + assertTrue(props.getProperties().isEmpty()); + + props = new ListenerProperties(prefix, both); + assertEquals(prefix, props.getPrefix()); + assertEquals(good.size(), props.getProperties().size()); + + for (Object val : props.getProperties().values()) { + assertFalse("NA".equals(val.toString())); + } + + assertTrue(props.toString().contains(prefix)); + } + + @Test + public void testGetClass() { + assertNull(props.getListenerClass()); + props.setListenerClass(AbstractListener.class); + assertNotNull(props.getListenerClass()); + assertEquals(AbstractListener.class, props.getListenerClass()); + } + + @Test + public void testMessageServices() { + // Hardcode count so tests must be updated when values are added + assertEquals(1, MessageService.values().length); + + // Bad Input + MessageService def = MessageService.DMaaP; + assertEquals(def, MessageService.parse(null)); + assertEquals(def, MessageService.parse("")); + assertEquals(def, MessageService.parse("NotDMaaP")); + + // DMaaP case sensitivity + assertEquals(MessageService.DMaaP, MessageService.parse("dmaap")); + assertEquals(MessageService.DMaaP, MessageService.parse("DMAAP")); + assertEquals(MessageService.DMaaP, MessageService.parse("DMaaP")); + } + + @Test + public void testKeys() { + // Hardcode count so tests must be updated when values are added + assertEquals(15, ListenerProperties.KEYS.values().length); + + Properties tmp = new Properties(); + try { + tmp.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); + } catch (Exception e) { + fail("Could not load properties to test"); + } + String realPrefix = tmp.getProperty("test.prefix"); + assertNotNull(realPrefix); + props = new ListenerProperties(realPrefix, tmp); + + for (KEYS key : ListenerProperties.KEYS.values()) { + assertNotNull(key.getFullProp(realPrefix)); + assertNotNull(props.getProperty(key)); + assertNotNull(props.getProperty(key.getPropertySuffix())); + } + } + + @Test + public void testDisabled() throws Exception { + assertFalse(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "TRUE"); + assertTrue(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "N/A"); + assertFalse(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "fAlse"); + assertFalse(props.isDisabled()); + props.getProperties().remove(KEYS.DISABLED.getPropertySuffix()); + assertFalse(props.isDisabled()); + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java new file mode 100644 index 000000000..f201e02f0 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.onap.appc.listener.demo.model.Action; +import org.onap.appc.listener.demo.model.Status; + +public class TestEnums { + + @Test + public void testAction() { + assertEquals(Action.Rebuild, Action.toAction("Rebuild")); + assertEquals(Action.Restart, Action.toAction("restart")); + assertEquals(Action.Migrate, Action.toAction("MIGRATE")); + assertEquals(Action.Evacuate, Action.toAction("Evacuate")); + assertNull(Action.toAction("Unknown")); + assertNull(Action.toAction(null)); + + assertEquals(6, Action.values().length); + } + + @Test + public void testStatus() { + + assertEquals(Status.ACCEPTED, Status.toStatus("accepted")); + assertEquals(Status.SUCCESS, Status.toStatus("SuCcEsS")); + assertEquals(Status.FAILURE, Status.toStatus("Failure")); + assertNull(Status.toStatus("Unknown")); + assertNull(Status.toStatus(null)); + + assertEquals(3, Status.values().length); + + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java new file mode 100644 index 000000000..3eedd88a3 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.onap.appc.listener.demo.model.OutgoingMessage; +import org.onap.appc.listener.demo.model.Status; +import org.onap.appc.listener.util.Mapper; + +public class TestMessages { + private IncomingMessage in; + private OutgoingMessage out; + + private String incomingStr; + private String outgoingStr; + + @Before + public void setup() { + try { + incomingStr = IOUtils.toString(getClass().getResourceAsStream("/IncomingMessagedemo.txt"), "UTF-8"); + outgoingStr = IOUtils.toString(getClass().getResourceAsStream("/OutgoingMessagedemo.txt"), "UTF-8"); + assertNotNull(incomingStr); + assertNotNull(outgoingStr); + + in = Mapper.mapOne(incomingStr, IncomingMessage.class); + + out = Mapper.mapOne(outgoingStr, OutgoingMessage.class); + + assertNotNull(in); + assertNotNull(out); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + // NOTE Test Mapper will be used to test an event from dmaap. + @Test + public void testGetterSetter() { + assertNotNull(in); + assertNotNull(in.getAction()); + assertNotNull(in.getHeader().getApiVer()); + assertNotNull(in.getHeader().getOriginatorId()); + assertNotNull(in.getHeader().getRequestID()); + assertNotNull(in.getHeader().getSubRequestId()); + assertNotNull(in.getHeader().getTimeStamp()); + + assertNotNull(out); + assertNotNull(out.getHeader().getApiVer()); + assertNotNull(out.getHeader().getOriginatorId()); + assertNotNull(out.getHeader().getRequestID()); + assertNotNull(out.getHeader().getSubRequestId()); + assertNotNull(out.getHeader().getTimeStamp()); + assertNotNull(out.getStatus().getCode()); + assertNotNull(out.getStatus().getValue()); + + } + + @Test + @Ignore + public void testIncommingToOutgoing(){ + OutgoingMessage newOut; + newOut = Mapper.mapOne(in.toOutgoing(Status.ACCEPTED), OutgoingMessage.class); + assertNotNull(newOut); + assertNotNull(newOut.getHeader().getApiVer()); + assertNotNull(newOut.getHeader().getOriginatorId()); + assertNotNull(newOut.getHeader().getRequestID()); + assertNotNull(newOut.getHeader().getSubRequestId()); + assertNotNull(newOut.getHeader().getTimeStamp()); + assertNotNull(newOut.getStatus().getCode()); + assertNotNull(newOut.getStatus().getValue()); + } + + @Test + @Ignore + public void testToString() { + in = new IncomingMessage(); + assertNotNull(in.toString()); + String id = "test"; + //in.setId(id); + assertNotNull(in.toString()); + assertTrue(in.toString().contains(id)); + } + + + @Test + @Ignore + public void testOutgoingUpdateTime() { + //String old = out.getResponseTime(); + out.updateResponseTime(); + //assertFalse(old.equals(out.getResponseTime())); + } + + // Testing for 1510 + @Test + @Ignore + public void testOutgoingToJson() { + // Message Set + String message = "MSG"; + //out.setMessage(message); + JSONObject json = out.toResponse(); + assertNotNull(json); + String respStr = json.getString("response"); + //assertTrue(respStr.contains(out.getResponse().getValue())); + + String msgStr = json.getString("message"); + assertNotNull(msgStr); + //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 + //assertTrue(msgStr.contains(out.getMessage())); + + // Null Message + //out.setMessage(null); + json = out.toResponse(); + assertNotNull(json); + msgStr = json.getString("message"); + assertNotNull(msgStr); + //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 + //assertTrue(msgStr.contains(out.getResponse().getValue())); + + // Echoing request + //assertNotNull(out.getOriginalRequest()); + } + + @Test + @Ignore + public void testOutgoingToString() { + String s = out.toString(); + //assertTrue(s.contains(out.getId())); + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java new file mode 100644 index 000000000..d44bb22cc --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.impl; + +public class TestController { + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestEventHandler.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestEventHandler.java new file mode 100644 index 000000000..992566358 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestEventHandler.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.Serializable; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.impl.EventHandlerImpl; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * Test the ProviderAdapter implementation. + * + */ + +public class TestEventHandler { + + private ListenerProperties prop; + + private EventHandler adapter; + + private static final String PROP_FILE = "/org/onap/appc/default.properties"; + + private static final String MESSAGE_FILE = "/DCAEResponse.txt"; + + /** + * Setup the test environment. + * + * @throws NoSuchMethodException + * @throws SecurityException + * @throws NoSuchFieldException + */ + @Before + public void setup() { + Properties allProps = new Properties(); + try { + allProps.load(getClass().getResourceAsStream(PROP_FILE)); + allProps.remove("appc.ClosedLoop.topic.read.filter"); + prop = new ListenerProperties("appc.ClosedLoop", allProps); + } catch (IOException e) { + System.out.println("WARNING: Failed to load properties file: " + PROP_FILE); + } + adapter = new EventHandlerImpl(prop); + } + + @Test + public void testInitialProperties() { + assertEquals(prop.getProperty("topic.read"), adapter.getReadTopic()); + assertTrue(adapter.getWriteTopics().contains(prop.getProperty("topic.write"))); + assertEquals(prop.getProperty("client.name"), adapter.getClientName()); + assertEquals(prop.getProperty("client.name.id"), adapter.getClientId()); + + String hostStr = prop.getProperty("poolMembers"); + int hostCount = hostStr.length()>0 ? hostStr.split(",").length : 0; + assertEquals(hostCount, adapter.getPool().size()); + } + + @Test + public void testGettersAndSetters() { + String readTopic = "read"; + Set writeTopic = new HashSet(); + writeTopic.add("write"); + String clientName = "APPC-TEST"; + String clientId = "00"; + String newHost = "google.com"; + + adapter.setReadTopic(readTopic); + assertEquals(readTopic, adapter.getReadTopic()); + + adapter.setWriteTopics(writeTopic); + assertEquals(writeTopic, adapter.getWriteTopics()); + + adapter.setClientName(clientName); + assertEquals(clientName, adapter.getClientName()); + + adapter.setClientId(clientId); + assertEquals(clientId, adapter.getClientId()); + + adapter.setCredentials("fake", "secret"); + adapter.clearCredentials(); + + int oldSize = adapter.getPool().size(); + adapter.addToPool(newHost); + assertEquals(oldSize + 1, adapter.getPool().size()); + assertTrue(adapter.getPool().contains(newHost)); + + adapter.removeFromPool(newHost); + assertEquals(oldSize, adapter.getPool().size()); + assertFalse(adapter.getPool().contains(newHost)); + + } + +// @Test + public void testRun() { + // Runoff any old data + List result1 = adapter.getIncomingEvents(); + assertNotNull(result1); + + // Post new data + DummyObj data = new DummyObj(); + data.key = "value"; + adapter.postStatus(data.toJson()); + + // Wait to account for network delay + sleep(2000); + + // Get data back + List result2 = adapter.getIncomingEvents(DummyObj.class); + assertNotNull(result2); +// assertEquals(1, result2.size()); + assertEquals(data.toJson(), result2.get(0).toJson()); + } + + @JsonSerialize + public static class DummyObj implements Serializable { + @JsonProperty("request") // Call request for default filter + public String key; + + public DummyObj() { + } + + public String toJson() { + return String.format("{\"request\": \"%s\"}", key); + } + } + + private void sleep(long ms) { + try { + Thread.sleep(ms); + } catch (Exception e) { + return; + } + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestListener.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestListener.java new file mode 100644 index 000000000..67ad9bf1d --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestListener.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.listener.Listener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.demo.impl.ListenerImpl; + +@Ignore +public class TestListener { + + private static final String PROP_FILE = "/org/onap/appc/default.properties"; + + private Listener listener; + + private Properties props; + + @Before + public void setup() { + props = new Properties(); + try { + props.load(getClass().getResourceAsStream(PROP_FILE)); + props.setProperty("topic.read", "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM"); + } catch (Exception e) { + e.printStackTrace(); + fail("Failed to setup test: " + e.getMessage()); + } + listener = new ListenerImpl(new ListenerProperties("appc.ClosedLoop", props)); + } + + @Test + public void testListenerId() { + String originalId = listener.getListenerId(); + String newId = originalId + "-new"; + + listener.setListenerId(newId); + assertEquals(newId, listener.getListenerId()); + } + + @Test + public void testRun() { + try { + Thread t = new Thread(listener); + t.start(); + + Thread.sleep(5000); + + listener.stopNow(); + + System.out.println(listener.getBenchmark()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testUpdateProperties() { + + } + + @Test + public void printSampleData() { + try { + props.setProperty("threads.queuesize.min", "1"); + props.setProperty("threads.queuesize.max", "1"); + props.setProperty("threads.poolsize.min", "1"); + props.setProperty("threads.poolsize.max", "1"); + + Thread t = new Thread(listener); + t.start(); + + Thread.sleep(2000); + + listener.stop(); + + System.out.println(listener.getBenchmark()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java new file mode 100644 index 000000000..de726194f --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +public class TestMapper { + + private String dummyJson = "{\"a\":\"%s\"}"; + private DummyObj dummyObj = new DummyObj(); + + @JsonSerialize + public static class DummyObj implements Serializable { + @JsonProperty("a") + public String a; + + public DummyObj() { + } + } + + @Before + public void setup() { + } + + @Test + public void testGetMapper() { + assertNotNull(Mapper.getMapper()); + } + + @Test + public void testToJsonObject() { + JSONObject out; + out = Mapper.toJsonObject("."); + assertNull(out); + + String value = "b"; + out = Mapper.toJsonObject(String.format(dummyJson, value)); + assertNotNull(out); + assertEquals(value, out.get("a")); + } + + @Test + public void testConstructor() { + // Only here for code coverage + Mapper m = new Mapper(); + assertNotNull(m); + } + + @Test + public void testMap() { + List in = new ArrayList(); + in.add(""); + in.add(null); + + List out = Mapper.mapList(in, DummyObj.class); + assertNotNull(out); + assertTrue(out.isEmpty()); + + in.add(String.format(dummyJson, "1")); + in.add("{\"invalid\":\"yes\"}"); + in.add(String.format(dummyJson, "2")); + + out = Mapper.mapList(in, DummyObj.class); + assertNotNull(out); + assertEquals(2, out.size()); + assertEquals("1", out.get(0).a); + assertEquals("2", out.get(1).a); + } + +} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM/TestConverter.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM/TestConverter.java deleted file mode 100644 index f9fb7f408..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM/TestConverter.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.listener.LCM.conv.Converter; -import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; -import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; -import org.onap.appc.listener.util.Mapper; - -public class TestConverter { - - private String jsonInputBodyStr ="{\"input\":{ \"common-header\": { \"timestamp\": \"2016-08-03T08:50:18.97Z\", \"api-ver\": \"1\", \"originator-id\": \"1\", \"request-id\": \"123\", \"sub-request-id\": \"1\", \"flags\": { \"force\":\"TRUE\", \"ttl\":\"9900\" } }, \"action\": \"Stop\", \"action-identifiers\": { \"vnf-id\": \"TEST\" } }}"; - private String jsonOutputBodyStr ="{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\",\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\",\"request-id\":\"123\",\"originator-id\":\"1\"},\"status\":{\"value\":\"TestException\",\"code\":200}}}"; - - @Test - public void buildDmaapOutgoingMessageWithUnexpectedErrorTest() throws JsonProcessingException { - DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); - String errMsg = "TestException"; - DmaapOutgoingMessage dmaapOutgoingMessage = Converter.buildDmaapOutgoingMessageWithUnexpectedError(dmaapIncomingMessage, new Exception(errMsg)); - int code = dmaapOutgoingMessage.getBody().get("output").get("status").get("code").asInt(); - String value = dmaapOutgoingMessage.getBody().get("output").get("status").get("value").asText(); - Assert.assertEquals(200,code); - Assert.assertEquals(errMsg,value); - } - - private static String expectedDmaapOutgoingMessageAsJsonString = "{\"body\":{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\",\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\",\"request-id\":\"123\",\"originator-id\":\"1\"},\"status\":{\"value\":\"TestException\",\"code\":200}}},\"cambria.partition\":\"MSO\",\"rpc-name\":\"test\"}"; - @Test - public void convDmaapOutgoingMessageToJsonStringTest() throws JsonProcessingException { - DmaapOutgoingMessage dmaapOutgoingMessage = buildDmaapOutgoingMessage(); - String dmaapOutgoingMessageAsJsonString = Converter.convDmaapOutgoingMessageToJsonString(dmaapOutgoingMessage); -// Assert.assertEquals(dmaapOutgoingMessageAsJsonString,dmaapOutgoingMessageAsJsonString); - Assert.assertEquals(expectedDmaapOutgoingMessageAsJsonString,dmaapOutgoingMessageAsJsonString); - } - - private DmaapIncomingMessage buildDmaapIncomingMessage() { - DmaapIncomingMessage dmaapIncomingMessage = new DmaapIncomingMessage(); - dmaapIncomingMessage.setRpcName("test"); - JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(jsonInputBodyStr); - dmaapIncomingMessage.setBody(jsonNode); - return dmaapIncomingMessage; - - } - - private DmaapOutgoingMessage buildDmaapOutgoingMessage() { - DmaapOutgoingMessage dmaapOutgoingMessage = new DmaapOutgoingMessage(); - dmaapOutgoingMessage.setRpcName("test"); - JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(jsonOutputBodyStr); - dmaapOutgoingMessage.setBody(jsonNode); - return dmaapOutgoingMessage; - - } - - - @Test - public void extractRequestIdWithSubIdTest() { - DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); - String equestIdWithSubId = Converter.extractRequestIdWithSubId(dmaapIncomingMessage.getBody()); - Assert.assertEquals("123-1",equestIdWithSubId); - } - - @Test - public void extractStatusCodeTest() { - DmaapOutgoingMessage dmaapOutgoingMessage = buildDmaapOutgoingMessage(); - Integer statusCode = Converter.extractStatusCode(dmaapOutgoingMessage.getBody()); - Assert.assertEquals(200L,statusCode.longValue()); - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM1607/model/TestJsonGenericMessages.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM1607/model/TestJsonGenericMessages.java deleted file mode 100644 index f28bd8cb3..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/LCM1607/model/TestJsonGenericMessages.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.LCM1607.model; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.listener.util.Mapper; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - - -public class TestJsonGenericMessages {/* - - @Test - public void serializeIncomingMessage() { - - final String expectedJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"APIver\":\"1.01\",\"RequestTrack\":[\"1\",\"4\",\"12\",\"3\"],\"Flags\":null,\"SubrequestID\":null,\"OriginatorID\":\"2\"},\"Payload\":\"{ \\\"command\\\": \\\"start\\\", \\\"target-id\\\": \\\"111\\\", \\\"flag10\\\": {\\\"object-1\\\": {\\\"key-1\\\": \\\"key\\\", \\\"value-1\\\": \\\"value\\\" }} }\",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; - InputBody msg = createIncomingMessage(); - - String json = Mapper.toJsonObject(msg).toString(); - //System.out.println(json); - Assert.assertEquals(expectedJson, json); - } - - @Test - public void deserializeIncomingMessage() throws IOException { - final String originalJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"Flags\":{\"FORCE\":\"Y\",\"TTL\":\"12\"},\"SubrequestID\":\"2345\",\"OriginatorID\":\"2\",\"APIver\":\"1.01\"}, \"Payload\": \" \\\"Graceful\\\" : \\\"Yes\\\" \",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; - - ObjectMapper mapper = new ObjectMapper(); - InputBody msg = mapper.readValue(originalJson, InputBody.class); - - Assert.assertNotNull(msg); - Assert.assertEquals("2016-05-02 19:50:37.09", msg.getCommonHeader().getTimeStamp()); - Assert.assertEquals("1", msg.getCommonHeader().getRequestID()); - Assert.assertEquals("1.01", msg.getCommonHeader().getApiVer()); - Assert.assertEquals("200", msg.getObjectId()); - Assert.assertEquals("100", msg.getTargetId()); - Assert.assertEquals(" \"Graceful\" : \"Yes\" ", msg.getPayload()); - Assert.assertEquals("CONFIGURE", msg.getAction()); - - } - - @Test - public void serializeResponseMessage() { - InputBody imsg = createIncomingMessage(); - OutputBody omsg = new OutputBody(imsg); - omsg.setStatus(new ResponseStatus("200", "OK")); - - String json = Mapper.toJsonObject(omsg).toString(); - System.out.println(json); - //Assert.assertEquals(expectedJson, json); - Assert.assertNotEquals("", json); - - } - - private InputBody createIncomingMessage() { - InputBody msg = new InputBody(); - CommonHeader rh = new CommonHeader(); - rh.setTimeStamp("2016-05-02 19:50:37.09"); - rh.setApiVer("1.01"); - rh.setRequestID("1"); - rh.setOriginatorId("2"); - - - Map flags = new HashMap<>(); - flags.put("FORCE", "Y"); - flags.put("TTL", "12"); - - msg.setCommonHeader(rh); - msg.setAction("CONFIGURE"); - msg.setTargetId("100"); - msg.setObjectId("200"); - msg.setPayloadAsString("{ \"command\": \"start\", \"target-id\": \"111\", \"flag10\": {\"object-1\": {\"key-1\": \"key\", \"value-1\": \"value\" }} }"); - return msg; - } -*/ -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAbstractListener.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAbstractListener.java deleted file mode 100644 index a21bcd416..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAbstractListener.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; -import java.util.concurrent.ThreadPoolExecutor; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.listener.AbstractListener; -import org.onap.appc.listener.ListenerProperties; - -public class TestAbstractListener { - - private class DummyListener extends AbstractListener { - public DummyListener(ListenerProperties props) { - super(props); - } - - public boolean getRun() { - return run.get(); - } - - public ThreadPoolExecutor getExecutor() { - return executor; - } - } - - private DummyListener listener; - private ListenerProperties props; - - @Before - public void setup() throws Exception { - Properties regularProps = new Properties(); - regularProps.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); - props = new ListenerProperties("", regularProps); - listener = new DummyListener(props); - } - - @Test - public void testRun() { - Thread t = new Thread(listener); - t.run(); - assertFalse(t.isAlive()); // Should die immediately - } - - @Test - public void testStop() { - listener.stop(); - assertFalse(listener.getRun()); - assertTrue(listener.getExecutor().isShutdown()); - } - - @Test - public void testStopNow() { - listener.stopNow(); - assertFalse(listener.getRun()); - assertTrue(listener.getExecutor().isShutdown()); - } - - @Test - public void testBenchmark() { - String out = listener.getBenchmark(); - assertNotNull(out); - assertTrue(out.contains(listener.getListenerId())); - } - - @Test - public void testListenerId() { - assertEquals(props.getPrefix(), listener.getListenerId()); - listener.setListenerId("newId"); - assertEquals("newId", listener.getListenerId()); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAppcDmaapListenerActivator.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAppcDmaapListenerActivator.java deleted file mode 100644 index 6bb96b95c..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestAppcDmaapListenerActivator.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.onap.appc.listener.AppcEventListenerActivator; - -public class TestAppcDmaapListenerActivator { - - @Test - public void testStartStop() { - // TODO - How do we tests activators - AppcEventListenerActivator appc = new AppcEventListenerActivator(); - try { - appc.start(null); - Thread.sleep(2000); - appc.stop(null); - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - assertNotNull(appc.getName()); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestListenerProperties.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestListenerProperties.java deleted file mode 100644 index 42c263394..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/TestListenerProperties.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.adapter.factory.MessageService; -import org.onap.appc.listener.AbstractListener; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.ListenerProperties.KEYS; - -public class TestListenerProperties { - - private Properties good, bad, both; - private String prefix; - - private ListenerProperties props; - - @Before - public void setup() { - prefix = "test"; - good = new Properties(); - bad = new Properties(); - both = new Properties(); - - good.setProperty(String.format("%s.%s", prefix, "a"), "1"); - good.setProperty(String.format("%s.%s", prefix, "a.b"), "2"); - good.setProperty(String.format("%s.%s", prefix, "a.b.c"), "3"); - - bad.setProperty(prefix, "NA"); - bad.setProperty(prefix + ".", "NA"); - bad.setProperty(String.format("%s.%s", prefix + "x", "bad"), "NA"); - bad.setProperty(String.format("%s.%s", "x" + prefix, "bad"), "NA"); - - for (String key : good.stringPropertyNames()) { - both.put(key, good.getProperty(key)); - } - for (String key : bad.stringPropertyNames()) { - both.put(key, bad.getProperty(key)); - } - - props = new ListenerProperties(prefix, both); - } - - @Test - public void testConstructor() { - props = new ListenerProperties(prefix, good); - assertEquals(prefix, props.getPrefix()); - assertEquals(good.size(), props.getProperties().size()); - - props = new ListenerProperties(prefix, bad); - assertEquals(prefix, props.getPrefix()); - assertTrue(props.getProperties().isEmpty()); - - props = new ListenerProperties(prefix, both); - assertEquals(prefix, props.getPrefix()); - assertEquals(good.size(), props.getProperties().size()); - - for (Object val : props.getProperties().values()) { - assertFalse("NA".equals(val.toString())); - } - - assertTrue(props.toString().contains(prefix)); - } - - @Test - public void testGetClass() { - assertNull(props.getListenerClass()); - props.setListenerClass(AbstractListener.class); - assertNotNull(props.getListenerClass()); - assertEquals(AbstractListener.class, props.getListenerClass()); - } - - @Test - public void testMessageServices() { - // Hardcode count so tests must be updated when values are added - assertEquals(1, MessageService.values().length); - - // Bad Input - MessageService def = MessageService.DMaaP; - assertEquals(def, MessageService.parse(null)); - assertEquals(def, MessageService.parse("")); - assertEquals(def, MessageService.parse("NotDMaaP")); - - // DMaaP case sensitivity - assertEquals(MessageService.DMaaP, MessageService.parse("dmaap")); - assertEquals(MessageService.DMaaP, MessageService.parse("DMAAP")); - assertEquals(MessageService.DMaaP, MessageService.parse("DMaaP")); - } - - @Test - public void testKeys() { - // Hardcode count so tests must be updated when values are added - assertEquals(15, ListenerProperties.KEYS.values().length); - - Properties tmp = new Properties(); - try { - tmp.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); - } catch (Exception e) { - fail("Could not load properties to test"); - } - String realPrefix = tmp.getProperty("test.prefix"); - assertNotNull(realPrefix); - props = new ListenerProperties(realPrefix, tmp); - - for (KEYS key : ListenerProperties.KEYS.values()) { - assertNotNull(key.getFullProp(realPrefix)); - assertNotNull(props.getProperty(key)); - assertNotNull(props.getProperty(key.getPropertySuffix())); - } - } - - @Test - public void testDisabled() throws Exception { - assertFalse(props.isDisabled()); - props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "TRUE"); - assertTrue(props.isDisabled()); - props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "N/A"); - assertFalse(props.isDisabled()); - props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "fAlse"); - assertFalse(props.isDisabled()); - props.getProperties().remove(KEYS.DISABLED.getPropertySuffix()); - assertFalse(props.isDisabled()); - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestEnums.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestEnums.java deleted file mode 100644 index f201e02f0..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestEnums.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; -import org.onap.appc.listener.demo.model.Action; -import org.onap.appc.listener.demo.model.Status; - -public class TestEnums { - - @Test - public void testAction() { - assertEquals(Action.Rebuild, Action.toAction("Rebuild")); - assertEquals(Action.Restart, Action.toAction("restart")); - assertEquals(Action.Migrate, Action.toAction("MIGRATE")); - assertEquals(Action.Evacuate, Action.toAction("Evacuate")); - assertNull(Action.toAction("Unknown")); - assertNull(Action.toAction(null)); - - assertEquals(6, Action.values().length); - } - - @Test - public void testStatus() { - - assertEquals(Status.ACCEPTED, Status.toStatus("accepted")); - assertEquals(Status.SUCCESS, Status.toStatus("SuCcEsS")); - assertEquals(Status.FAILURE, Status.toStatus("Failure")); - assertNull(Status.toStatus("Unknown")); - assertNull(Status.toStatus(null)); - - assertEquals(3, Status.values().length); - - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestMessages.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestMessages.java deleted file mode 100644 index 3eedd88a3..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/demo/model/TestMessages.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.demo.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.listener.demo.model.IncomingMessage; -import org.onap.appc.listener.demo.model.OutgoingMessage; -import org.onap.appc.listener.demo.model.Status; -import org.onap.appc.listener.util.Mapper; - -public class TestMessages { - private IncomingMessage in; - private OutgoingMessage out; - - private String incomingStr; - private String outgoingStr; - - @Before - public void setup() { - try { - incomingStr = IOUtils.toString(getClass().getResourceAsStream("/IncomingMessagedemo.txt"), "UTF-8"); - outgoingStr = IOUtils.toString(getClass().getResourceAsStream("/OutgoingMessagedemo.txt"), "UTF-8"); - assertNotNull(incomingStr); - assertNotNull(outgoingStr); - - in = Mapper.mapOne(incomingStr, IncomingMessage.class); - - out = Mapper.mapOne(outgoingStr, OutgoingMessage.class); - - assertNotNull(in); - assertNotNull(out); - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - // NOTE Test Mapper will be used to test an event from dmaap. - @Test - public void testGetterSetter() { - assertNotNull(in); - assertNotNull(in.getAction()); - assertNotNull(in.getHeader().getApiVer()); - assertNotNull(in.getHeader().getOriginatorId()); - assertNotNull(in.getHeader().getRequestID()); - assertNotNull(in.getHeader().getSubRequestId()); - assertNotNull(in.getHeader().getTimeStamp()); - - assertNotNull(out); - assertNotNull(out.getHeader().getApiVer()); - assertNotNull(out.getHeader().getOriginatorId()); - assertNotNull(out.getHeader().getRequestID()); - assertNotNull(out.getHeader().getSubRequestId()); - assertNotNull(out.getHeader().getTimeStamp()); - assertNotNull(out.getStatus().getCode()); - assertNotNull(out.getStatus().getValue()); - - } - - @Test - @Ignore - public void testIncommingToOutgoing(){ - OutgoingMessage newOut; - newOut = Mapper.mapOne(in.toOutgoing(Status.ACCEPTED), OutgoingMessage.class); - assertNotNull(newOut); - assertNotNull(newOut.getHeader().getApiVer()); - assertNotNull(newOut.getHeader().getOriginatorId()); - assertNotNull(newOut.getHeader().getRequestID()); - assertNotNull(newOut.getHeader().getSubRequestId()); - assertNotNull(newOut.getHeader().getTimeStamp()); - assertNotNull(newOut.getStatus().getCode()); - assertNotNull(newOut.getStatus().getValue()); - } - - @Test - @Ignore - public void testToString() { - in = new IncomingMessage(); - assertNotNull(in.toString()); - String id = "test"; - //in.setId(id); - assertNotNull(in.toString()); - assertTrue(in.toString().contains(id)); - } - - - @Test - @Ignore - public void testOutgoingUpdateTime() { - //String old = out.getResponseTime(); - out.updateResponseTime(); - //assertFalse(old.equals(out.getResponseTime())); - } - - // Testing for 1510 - @Test - @Ignore - public void testOutgoingToJson() { - // Message Set - String message = "MSG"; - //out.setMessage(message); - JSONObject json = out.toResponse(); - assertNotNull(json); - String respStr = json.getString("response"); - //assertTrue(respStr.contains(out.getResponse().getValue())); - - String msgStr = json.getString("message"); - assertNotNull(msgStr); - //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 - //assertTrue(msgStr.contains(out.getMessage())); - - // Null Message - //out.setMessage(null); - json = out.toResponse(); - assertNotNull(json); - msgStr = json.getString("message"); - assertNotNull(msgStr); - //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 - //assertTrue(msgStr.contains(out.getResponse().getValue())); - - // Echoing request - //assertNotNull(out.getOriginalRequest()); - } - - @Test - @Ignore - public void testOutgoingToString() { - String s = out.toString(); - //assertTrue(s.contains(out.getId())); - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestController.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestController.java deleted file mode 100644 index d44bb22cc..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestController.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.impl; - -public class TestController { - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestEventHandler.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestEventHandler.java deleted file mode 100644 index 992566358..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestEventHandler.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.Serializable; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.listener.EventHandler; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.impl.EventHandlerImpl; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** - * Test the ProviderAdapter implementation. - * - */ - -public class TestEventHandler { - - private ListenerProperties prop; - - private EventHandler adapter; - - private static final String PROP_FILE = "/org/onap/appc/default.properties"; - - private static final String MESSAGE_FILE = "/DCAEResponse.txt"; - - /** - * Setup the test environment. - * - * @throws NoSuchMethodException - * @throws SecurityException - * @throws NoSuchFieldException - */ - @Before - public void setup() { - Properties allProps = new Properties(); - try { - allProps.load(getClass().getResourceAsStream(PROP_FILE)); - allProps.remove("appc.ClosedLoop.topic.read.filter"); - prop = new ListenerProperties("appc.ClosedLoop", allProps); - } catch (IOException e) { - System.out.println("WARNING: Failed to load properties file: " + PROP_FILE); - } - adapter = new EventHandlerImpl(prop); - } - - @Test - public void testInitialProperties() { - assertEquals(prop.getProperty("topic.read"), adapter.getReadTopic()); - assertTrue(adapter.getWriteTopics().contains(prop.getProperty("topic.write"))); - assertEquals(prop.getProperty("client.name"), adapter.getClientName()); - assertEquals(prop.getProperty("client.name.id"), adapter.getClientId()); - - String hostStr = prop.getProperty("poolMembers"); - int hostCount = hostStr.length()>0 ? hostStr.split(",").length : 0; - assertEquals(hostCount, adapter.getPool().size()); - } - - @Test - public void testGettersAndSetters() { - String readTopic = "read"; - Set writeTopic = new HashSet(); - writeTopic.add("write"); - String clientName = "APPC-TEST"; - String clientId = "00"; - String newHost = "google.com"; - - adapter.setReadTopic(readTopic); - assertEquals(readTopic, adapter.getReadTopic()); - - adapter.setWriteTopics(writeTopic); - assertEquals(writeTopic, adapter.getWriteTopics()); - - adapter.setClientName(clientName); - assertEquals(clientName, adapter.getClientName()); - - adapter.setClientId(clientId); - assertEquals(clientId, adapter.getClientId()); - - adapter.setCredentials("fake", "secret"); - adapter.clearCredentials(); - - int oldSize = adapter.getPool().size(); - adapter.addToPool(newHost); - assertEquals(oldSize + 1, adapter.getPool().size()); - assertTrue(adapter.getPool().contains(newHost)); - - adapter.removeFromPool(newHost); - assertEquals(oldSize, adapter.getPool().size()); - assertFalse(adapter.getPool().contains(newHost)); - - } - -// @Test - public void testRun() { - // Runoff any old data - List result1 = adapter.getIncomingEvents(); - assertNotNull(result1); - - // Post new data - DummyObj data = new DummyObj(); - data.key = "value"; - adapter.postStatus(data.toJson()); - - // Wait to account for network delay - sleep(2000); - - // Get data back - List result2 = adapter.getIncomingEvents(DummyObj.class); - assertNotNull(result2); -// assertEquals(1, result2.size()); - assertEquals(data.toJson(), result2.get(0).toJson()); - } - - @JsonSerialize - public static class DummyObj implements Serializable { - @JsonProperty("request") // Call request for default filter - public String key; - - public DummyObj() { - } - - public String toJson() { - return String.format("{\"request\": \"%s\"}", key); - } - } - - private void sleep(long ms) { - try { - Thread.sleep(ms); - } catch (Exception e) { - return; - } - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestListener.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestListener.java deleted file mode 100644 index 67ad9bf1d..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/impl/TestListener.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Properties; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.listener.Listener; -import org.onap.appc.listener.ListenerProperties; -import org.onap.appc.listener.demo.impl.ListenerImpl; - -@Ignore -public class TestListener { - - private static final String PROP_FILE = "/org/onap/appc/default.properties"; - - private Listener listener; - - private Properties props; - - @Before - public void setup() { - props = new Properties(); - try { - props.load(getClass().getResourceAsStream(PROP_FILE)); - props.setProperty("topic.read", "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM"); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to setup test: " + e.getMessage()); - } - listener = new ListenerImpl(new ListenerProperties("appc.ClosedLoop", props)); - } - - @Test - public void testListenerId() { - String originalId = listener.getListenerId(); - String newId = originalId + "-new"; - - listener.setListenerId(newId); - assertEquals(newId, listener.getListenerId()); - } - - @Test - public void testRun() { - try { - Thread t = new Thread(listener); - t.start(); - - Thread.sleep(5000); - - listener.stopNow(); - - System.out.println(listener.getBenchmark()); - - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testUpdateProperties() { - - } - - @Test - public void printSampleData() { - try { - props.setProperty("threads.queuesize.min", "1"); - props.setProperty("threads.queuesize.max", "1"); - props.setProperty("threads.poolsize.min", "1"); - props.setProperty("threads.poolsize.max", "1"); - - Thread t = new Thread(listener); - t.start(); - - Thread.sleep(2000); - - listener.stop(); - - System.out.println(listener.getBenchmark()); - - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/util/TestMapper.java b/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/util/TestMapper.java deleted file mode 100644 index de726194f..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/java/org/openecomp/appc/listener/util/TestMapper.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.listener.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.listener.util.Mapper; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class TestMapper { - - private String dummyJson = "{\"a\":\"%s\"}"; - private DummyObj dummyObj = new DummyObj(); - - @JsonSerialize - public static class DummyObj implements Serializable { - @JsonProperty("a") - public String a; - - public DummyObj() { - } - } - - @Before - public void setup() { - } - - @Test - public void testGetMapper() { - assertNotNull(Mapper.getMapper()); - } - - @Test - public void testToJsonObject() { - JSONObject out; - out = Mapper.toJsonObject("."); - assertNull(out); - - String value = "b"; - out = Mapper.toJsonObject(String.format(dummyJson, value)); - assertNotNull(out); - assertEquals(value, out.get("a")); - } - - @Test - public void testConstructor() { - // Only here for code coverage - Mapper m = new Mapper(); - assertNotNull(m); - } - - @Test - public void testMap() { - List in = new ArrayList(); - in.add(""); - in.add(null); - - List out = Mapper.mapList(in, DummyObj.class); - assertNotNull(out); - assertTrue(out.isEmpty()); - - in.add(String.format(dummyJson, "1")); - in.add("{\"invalid\":\"yes\"}"); - in.add(String.format(dummyJson, "2")); - - out = Mapper.mapList(in, DummyObj.class); - assertNotNull(out); - assertEquals(2, out.size()); - assertEquals("1", out.get(0).a); - assertEquals("2", out.get(1).a); - } - -} diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/onap/appc/default.properties b/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..3bd5bf409 --- /dev/null +++ b/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,92 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + + + + + +### ### +### ### +###Properties below are default values to be provided with real valuesin appc.properties### +### ### +### ### + + + + + +### ### +###Closed Loop - properties ### +### ### +test.prefix=appc.ClosedLoop +appc.ClosedLoop.disabled=false +appc.ClosedLoop.service=dmaap +appc.ClosedLoop.poolMembers=192.168.1.2:3904 +appc.ClosedLoop.topic.read=APPC-TEST1 +appc.ClosedLoop.topic.read.timeout=5 +appc.ClosedLoop.topic.write=APPC-TEST1 +appc.ClosedLoop.topic.read.filter={"class":"Assigned","field":"request"} +appc.ClosedLoop.client.name=APPC-TEST1-CLOSED-LOOP +appc.ClosedLoop.client.name.id=0 + +# KEY AND SECRET BELOW NEED TO BE MODIFIED TO APPROPRIATE VALUES WHEN THE TOPIC IS API-KEY-BASED AUTH +appc.ClosedLoop.client.key=MY_API_KEY +appc.ClosedLoop.client.secret=MY_API_SECRET + +appc.ClosedLoop.threads.queuesize.min=1 +appc.ClosedLoop.threads.queuesize.max=1000 +appc.ClosedLoop.threads.poolsize.min=1 +appc.ClosedLoop.threads.poolsize.max=2 +appc.ClosedLoop.provider.url=https://admin:password@localhost:8443/restconf/operations/appc-provider:topology-operation + + + + + +### ### +###Closed Loop - 1607 properties ### +### ### +appc.ClosedLoop1607.poolMembers=192.168.1.2:3904 +appc.ClosedLoop1607.topic.read=MY_DMAAP_TOPIC +appc.ClosedLoop1607.topic.write=MY_DMAAP_TOPIC +appc.ClosedLoop1607.topic.read.filter={"class":"Unassigned","field":"Status"} +appc.ClosedLoop1607.client.name=DMAAP-CLIENT-NAME +appc.ClosedLoop1607.client.name.id=0 +#dmaap.client.key=random +#dmaap.client.secret=random +appc.ClosedLoop1607.threads.queuesize.min=1 +appc.ClosedLoop1607.threads.queuesize.max=1000 +appc.ClosedLoop1607.threads.poolsize.min=1 +appc.ClosedLoop1607.threads.poolsize.max=2 +appc.ClosedLoop1607.provider.url=https://admin:password@localhost:8443/restconf/operations/appc-provider:topology-operation + + + + + +### ### +### POINT TO AN ACTIVE TEST VM IN OPENSTACK INSTANCE ### +### ### +test.vm_url=https://example.com/v2/123/servers/123-345 + diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 3bd5bf409..000000000 --- a/appc-event-listener/appc-event-listener-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,92 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - - - - - -### ### -### ### -###Properties below are default values to be provided with real valuesin appc.properties### -### ### -### ### - - - - - -### ### -###Closed Loop - properties ### -### ### -test.prefix=appc.ClosedLoop -appc.ClosedLoop.disabled=false -appc.ClosedLoop.service=dmaap -appc.ClosedLoop.poolMembers=192.168.1.2:3904 -appc.ClosedLoop.topic.read=APPC-TEST1 -appc.ClosedLoop.topic.read.timeout=5 -appc.ClosedLoop.topic.write=APPC-TEST1 -appc.ClosedLoop.topic.read.filter={"class":"Assigned","field":"request"} -appc.ClosedLoop.client.name=APPC-TEST1-CLOSED-LOOP -appc.ClosedLoop.client.name.id=0 - -# KEY AND SECRET BELOW NEED TO BE MODIFIED TO APPROPRIATE VALUES WHEN THE TOPIC IS API-KEY-BASED AUTH -appc.ClosedLoop.client.key=MY_API_KEY -appc.ClosedLoop.client.secret=MY_API_SECRET - -appc.ClosedLoop.threads.queuesize.min=1 -appc.ClosedLoop.threads.queuesize.max=1000 -appc.ClosedLoop.threads.poolsize.min=1 -appc.ClosedLoop.threads.poolsize.max=2 -appc.ClosedLoop.provider.url=https://admin:password@localhost:8443/restconf/operations/appc-provider:topology-operation - - - - - -### ### -###Closed Loop - 1607 properties ### -### ### -appc.ClosedLoop1607.poolMembers=192.168.1.2:3904 -appc.ClosedLoop1607.topic.read=MY_DMAAP_TOPIC -appc.ClosedLoop1607.topic.write=MY_DMAAP_TOPIC -appc.ClosedLoop1607.topic.read.filter={"class":"Unassigned","field":"Status"} -appc.ClosedLoop1607.client.name=DMAAP-CLIENT-NAME -appc.ClosedLoop1607.client.name.id=0 -#dmaap.client.key=random -#dmaap.client.secret=random -appc.ClosedLoop1607.threads.queuesize.min=1 -appc.ClosedLoop1607.threads.queuesize.max=1000 -appc.ClosedLoop1607.threads.poolsize.min=1 -appc.ClosedLoop1607.threads.poolsize.max=2 -appc.ClosedLoop1607.provider.url=https://admin:password@localhost:8443/restconf/operations/appc-provider:topology-operation - - - - - -### ### -### POINT TO AN ACTIVE TEST VM IN OPENSTACK INSTANCE ### -### ### -test.vm_url=https://example.com/v2/123/servers/123-345 - diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/ArtifactHandlerProvider.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/ArtifactHandlerProvider.java new file mode 100644 index 000000000..d5ccd45b0 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/ArtifactHandlerProvider.java @@ -0,0 +1,213 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler; + +import java.util.HashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.DataChangeListener; +import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.ArtifactHandlerService; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.uploadartifact.output.ConfigDocumentResponseBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Services; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.ServicesBuilder; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; +import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.Futures; + + + +public class ArtifactHandlerProvider implements AutoCloseable, ArtifactHandlerService, DataChangeListener { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerProvider.class); + private final String appName = "ArtifactsHandler"; + private final ExecutorService executor; + protected DataBroker dataBroker; + protected NotificationProviderService notificationService; + protected RpcProviderRegistry rpcRegistry; + private ListenerRegistration dclServices; + + protected BindingAwareBroker.RpcRegistration rpcRegistration; + + public ArtifactHandlerProvider(DataBroker dataBroker2, + NotificationProviderService notificationProviderService, + RpcProviderRegistry rpcProviderRegistry) { + this.log.info("Creating provider for " + appName); + executor = Executors.newFixedThreadPool(10); + dataBroker = dataBroker2; + notificationService = notificationProviderService; + rpcRegistry = rpcProviderRegistry; + initialize(); + + } + + public void initialize() { + log.info("Initializing provider for " + appName); + // Create the top level containers + createContainers(); + try { + ArtifactHandlerProviderUtil.loadProperties(); + } catch (Exception e) { + log.error("Caught Exception while trying to load properties file"); + } + // Listener for changes to Services tree + + rpcRegistration = rpcRegistry.addRpcImplementation( + ArtifactHandlerService.class, this); + + log.info("Initialization complete for " + appName); + } + private void createContainers() { + final WriteTransaction t = dataBroker.newReadWriteTransaction(); + // Create the Services container + t.merge(LogicalDatastoreType.CONFIGURATION,InstanceIdentifier.create(Services.class),new ServicesBuilder().build()); + t.merge(LogicalDatastoreType.OPERATIONAL,InstanceIdentifier.create(Services.class),new ServicesBuilder().build()); + + try { + CheckedFuture checkedFuture = t.submit(); + checkedFuture.get(); + log.info("Create Containers succeeded!: "); + + } catch (InterruptedException | ExecutionException e) { + log.error("Create Containers Failed: " + e); + e.printStackTrace(); + } + } + + + @Override + public void onDataChanged(AsyncDataChangeEvent, DataObject> arg0) { + // TODO Auto-generated method stub + + } + + + + @Override + public void close() throws Exception { + + log.info("Closing provider for " + appName); + if(this.executor != null){ + executor.shutdown(); + } + if(this.rpcRegistration != null){ + rpcRegistration.close(); + } + log.info("Successfully closed provider for " + appName); + + } + + private RpcResult buildResponse1( + String svcRequestId, + String topic, + String code, + String message, + String finalInd) { + + UploadartifactOutputBuilder responseBuilder = new UploadartifactOutputBuilder(); + ConfigDocumentResponseBuilder configResponseBuilder=new ConfigDocumentResponseBuilder(); + configResponseBuilder.setRequestId(svcRequestId); + configResponseBuilder.setStatus(code); + configResponseBuilder.setErrorReason(message); + RpcResult rpcResult = RpcResultBuilder. status(true) + .withResult(responseBuilder.build()).build(); + return rpcResult; + } + + @Override + public Future> uploadartifact(UploadartifactInput input) { + + if (input == null || input.getDocumentParameters() == null || input.getDocumentParameters().getArtifactContents() == null ) { + RpcResult rpcResult = + buildResponse1("N/A", "N/A", "INVALID_INPUT", "Invalid input, null or empty document information" , "Y"); + return Futures.immediateFuture(rpcResult); + } + UploadartifactInputBuilder inputBuilder = new UploadartifactInputBuilder(input); + ConfigDocumentResponseBuilder configResponseBuilder = new ConfigDocumentResponseBuilder(); + UploadartifactOutputBuilder responseBuilder = new UploadartifactOutputBuilder(); + log.info("Received input = " + input ); + ArtifactHandlerProviderUtil designUtil = new ArtifactHandlerProviderUtil(input); + configResponseBuilder.setRequestId(input.getRequestInformation().getRequestId()); + try{ + + if(input.getRequestInformation().getSource() !=null){ + if(input.getRequestInformation().getSource().equalsIgnoreCase(SdcArtifactHandlerConstants.DESIGN_TOOL)){ + designUtil.processTemplate(designUtil.createDummyRequestData()); + configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_OK.toString()); + } + else + { + designUtil.processTemplate(designUtil.createRequestData()); + configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_OK.toString()); + } + } + else + { + throw new Exception("No Tempalte data found"); + } + + + } + catch (Exception e) { + + configResponseBuilder.setErrorReason(e.getMessage()); + configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_ERROR.toString()); + log.error("Caught exception looking for Artifact Handler", e); + log.info("Caught exception looking for Artifact Handler: "); + } + + responseBuilder.setConfigDocumentResponse(configResponseBuilder.build()); + RpcResult rpcResult = RpcResultBuilder. status(true).withResult(responseBuilder.build()).build(); + return Futures.immediateFuture(rpcResult); + + } +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/SdcArtifactHandlerActivator.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/SdcArtifactHandlerActivator.java new file mode 100644 index 000000000..ebbbe4735 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/SdcArtifactHandlerActivator.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class SdcArtifactHandlerActivator implements BundleActivator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(SdcArtifactHandlerActivator.class); + private List registrations = new LinkedList(); + + @Override + public void start(BundleContext ctx) throws Exception { + ArtifactHandlerNode artifactHandlerNode = new ArtifactHandlerNode(); + log.info("Registering service-- " + artifactHandlerNode.getClass().getName()); + registrations.add(ctx.registerService(artifactHandlerNode.getClass().getName(), artifactHandlerNode, null)); + + } + + @Override + public void stop(BundleContext arg0) throws Exception { + for (ServiceRegistration registration : registrations) { + registration.unregister(); + registration = null; + } + } +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/dbservices/DBService.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/dbservices/DBService.java new file mode 100644 index 000000000..031d53e28 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/dbservices/DBService.java @@ -0,0 +1,531 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.dbservices; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; + +import java.sql.SQLException; +import java.util.HashMap; +import org.apache.commons.lang.StringUtils; + +public class DBService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DBService.class); + private SvcLogicResource serviceLogic; + private static DBService dgGeneralDBService = null; + + public static DBService initialise() { + if (dgGeneralDBService == null) { + dgGeneralDBService = new DBService(); + } + return dgGeneralDBService; + } + + private DBService() { + if (serviceLogic == null) { + serviceLogic = new SqlResource(); + } + } + + protected DBService(SqlResource svcLogic) { + if (serviceLogic == null) { + serviceLogic = svcLogic; + } + } + + public String getInternalVersionNumber(SvcLogicContext ctx, String artifactName, String prefix) + throws SvcLogicException { + String fn = "DBService.getInternalVersionNumber"; + QueryStatus status = null; + String artifactInternalVersion = null; + if (serviceLogic != null && ctx != null) { + String key = "select max(internal_version) as maximum from ASDC_ARTIFACTS WHERE ARTIFACT_NAME = '" + + artifactName + "'"; + log.info("Getting internal Versoin :" + key); + status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - getting internal Artifact Number"); + artifactInternalVersion = ctx.getAttribute("maximum"); + log.info("Internal Version received as : " + artifactInternalVersion); + log.info("Internal Version received as1 : " + ctx.getAttribute("max(internal_version)")); + log.info("Internal Version received as1 : " + ctx.getAttribute("max")); + log.info("Internal Version received as1 : " + ctx.getAttribute("internal_version")); + log.info("Internal Version received as1 : " + ctx.getAttributeKeySet().toString()); + } + return artifactInternalVersion; + } + + public String getArtifactID(SvcLogicContext ctx, String artifactName) throws SvcLogicException { + String fn = "DBService.getArtifactID"; + QueryStatus status = null; + String artifactID = null; + if (serviceLogic != null && ctx != null) { + String key = "select max(ASDC_ARTIFACTS_ID) as id from ASDC_ARTIFACTS WHERE ARTIFACT_NAME = '" + + artifactName + "'"; + log.info("Getting Artifact ID String :" + key); + status = serviceLogic.query("SQL", false, null, key, null, null, ctx); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error - getting Artifact ID from database"); + artifactID = ctx.getAttribute("id"); + log.info("SDC_ARTIFACTS_ID received as : " + ctx.getAttribute("id")); + } + return artifactID; + } + + public QueryStatus saveArtifacts(SvcLogicContext ctx, int intversion) throws SvcLogicException { + String fn = "DBService.saveArtifacts"; + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "INSERT INTO ASDC_ARTIFACTS " + "SET SERVICE_UUID = $service-uuid , " + + " DISTRIBUTION_ID = $distribution-id ," + " SERVICE_NAME = $service-name ," + + " SERVICE_DESCRIPTION = $service-description ," + " RESOURCE_UUID = $resource-uuid ," + + " RESOURCE_INSTANCE_NAME = $resource-instance-name ," + " RESOURCE_NAME = $resource-name ," + + " RESOURCE_VERSION = $resource-version ," + " RESOURCE_TYPE = $resource-type ," + + " ARTIFACT_UUID = $artifact-uuid ," + " ARTIFACT_TYPE = $artifact-type ," + + " ARTIFACT_VERSION = $artifact-version ," + " ARTIFACT_DESCRIPTION = $artifact-description ," + + " INTERNAL_VERSION = " + intversion + "," + " ARTIFACT_NAME = $artifact-name ," + + " ARTIFACT_CONTENT = $artifact-contents "; + + status = serviceLogic.save("SQL", false, false, key, null, null, ctx); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing storing Artifact: " + + ctx.getAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + } + return status; + + } + + public QueryStatus logData(SvcLogicContext ctx, String prefix) throws SvcLogicException { + String fn = "DBService.saveReferenceData"; + QueryStatus status = null; + if (serviceLogic != null && ctx != null) { + String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + " SET request_id = $request-id , " + + " message_type = $log-message-type , " + " message = $log-message ;"; + status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error while loging data"); + + } + return status; + } + + public void processConfigureActionDg(SvcLogicContext context, boolean isUpdate) { + String fn = "DBService.processConfigureActionDg"; + log.info("Update Parameter for SDC Reference " + isUpdate); + String key = ""; + QueryStatus status = null; + if (isUpdate) + ; + } + + public void processSdcReferences(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { + String fn = "DBService.processSdcReferences"; + String key = ""; + QueryStatus status = null; + + if (isUpdate && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY).equals(SdcArtifactHandlerConstants.CAPABILITY)) { + log.info("Updating capability artifact in ASDC_REFERENCE"); + key = "update " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set ARTIFACT_NAME = $" + + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where " + "FILE_CATEGORY = $" + + SdcArtifactHandlerConstants.FILE_CATEGORY + " and VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE ; + } else if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set ARTIFACT_NAME = $" + + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where VNFC_TYPE = $" + + SdcArtifactHandlerConstants.VNFC_TYPE + " and FILE_CATEGORY = $" + + SdcArtifactHandlerConstants.FILE_CATEGORY + " and ACTION = $" + + SdcArtifactHandlerConstants.ACTION + " and VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; + + else { + if (context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY).equals(SdcArtifactHandlerConstants.CAPABILITY)) { + key = "insert into " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = null " + + " , FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY + " , VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = null " + " , ARTIFACT_TYPE = null " + + " , ARTIFACT_NAME = $" + SdcArtifactHandlerConstants.ARTIFACT_NAME; + } else { + key = "insert into " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = $" + + SdcArtifactHandlerConstants.VNFC_TYPE + " , FILE_CATEGORY = $" + + SdcArtifactHandlerConstants.FILE_CATEGORY + " , VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = $" + SdcArtifactHandlerConstants.ACTION + + " , ARTIFACT_TYPE = $" + SdcArtifactHandlerConstants.ARTIFACT_TYPE + " , ARTIFACT_NAME = $" + + SdcArtifactHandlerConstants.ARTIFACT_NAME; + } + } + if (serviceLogic != null && context != null) { + log.info("Insert Key: " + key); + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing sdc_reference table "); + } + } + + public boolean isArtifactUpdateRequired(SvcLogicContext context, String db) throws SvcLogicException, SQLException { + String fn = "DBService.isArtifactUpdateRequired"; + log.info("Checking if Update required for this data"); + + log.info("db" + db); + log.info("ACTION=" + context.getAttribute(SdcArtifactHandlerConstants.ACTION)); + log.info("VNFC_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_TYPE)); + log.info("VNFC_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); + log.info("VM_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); + log.info("VNF_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE)); + String whereClause = ""; + + QueryStatus status = null; + whereClause = " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; + + if (db != null) { + if (db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE) + && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY) + .equals(SdcArtifactHandlerConstants.CAPABILITY) + && context.getAttribute(SdcArtifactHandlerConstants.ACTION) == null) { + whereClause = whereClause + " and FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY; + } + + else if (db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE)) { + whereClause = whereClause + " and VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE + + " and FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY + " and ACTION = $" + + SdcArtifactHandlerConstants.ACTION; + } + + else if (db.equals(SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE)) { + whereClause = " where PROTOCOL = $" + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; + } else if (db.equals(SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG)) { + whereClause = whereClause + " and ACTION = $" + SdcArtifactHandlerConstants.ACTION; + } else if (db.equals(SdcArtifactHandlerConstants.DB_VNFC_REFERENCE)) { + int vm_instance = -1; + if (context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE) != null) + vm_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); + int vnfc_instance = -1; + if (context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE) != null) + vnfc_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); + whereClause = whereClause + " and ACTION = $" + SdcArtifactHandlerConstants.ACTION + " and VNFC_TYPE = $" + + SdcArtifactHandlerConstants.VNFC_TYPE + " and VNFC_INSTANCE = $" + + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $" + + SdcArtifactHandlerConstants.VM_INSTANCE; + + } + } + + if (serviceLogic != null && context != null) { + String key = "select COUNT(*) from " + db + whereClause; + log.info("SELECT String : " + key); + status = serviceLogic.query("SQL", false, null, key, null, null, context); + if (status.toString().equals("FAILURE")) { + throw new SvcLogicException("Error while reading data from " + db); + } + String count = context.getAttribute("COUNT(*)"); + log.info("Number of row Returned : " + count + ": " + status + ":"); + if (count != null && Integer.parseInt(count) > 0) { + context.setAttribute(count, null); + return true; + } else + return false; + } + return false; + } + + public void processDeviceInterfaceProtocol(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { + String fn = "DBService.processDeviceInterfaceProtocol"; + log.info("Starting DB operation for Device Interface Protocol " + isUpdate); + String key = ""; + QueryStatus status = null; + if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set PROTOCOL = $" + + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' " + + " , MODULE = 'APPC' " + " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; + else + key = "insert into " + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE + " , PROTOCOL = $" + + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' " + + " , MODULE = 'APPC' "; + + if (serviceLogic != null && context != null) { + + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing DEVICE_INTERFACE_PROTOCOL table "); + } + + } + + public void processDeviceAuthentication(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { + String fn = "DBService.processDeviceAuthentication"; + log.info(fn + "Starting DB operation for Device Authentication " + isUpdate); + String key = ""; + QueryStatus status = null; + if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION + " set USER_NAME = $" + + SdcArtifactHandlerConstants.USER_NAME +/* " , PASSWORD = 'dummy' " +*/ " , PORT_NUMBER = $" + + SdcArtifactHandlerConstants.PORT_NUMBER + " where VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE; + else + key = "insert into " + SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION + " set VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE + " , USER_NAME = $" + SdcArtifactHandlerConstants.USER_NAME + +/* " , PASSWORD = 'dummy' " + */ " , PORT_NUMBER = $" + SdcArtifactHandlerConstants.PORT_NUMBER; + + if (serviceLogic != null && context != null) { + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing DEVICE_AUTHENTICATION table "); + } + } + + public void processVnfcReference(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { + String fn = "DBService.processVnfcReference"; + log.info(fn + "Starting DB operation for Vnfc Reference " + isUpdate); + String key = ""; + int vm_instance = -1; + if (context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE) != null) + vm_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); + int vnfc_instance = -1; + if (context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE) != null) + vnfc_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); + QueryStatus status = null; + if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set VM_INSTANCE = " + vm_instance + + " , VNFC_INSTANCE = " + vnfc_instance + " , VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE + + " , VNFC_FUNCTION_CODE = $" + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE + + " , GROUP_NOTATION_TYPE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE + + " , GROUP_NOTATION_VALUE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE + + " , IPADDRESS_V4_OAM_VIP = $" + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP + + " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE + " and ACTION = $" + + SdcArtifactHandlerConstants.ACTION + " and VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE + + " and VNFC_INSTANCE = $" + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $" + + SdcArtifactHandlerConstants.VM_INSTANCE; + else + key = "insert into " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = $" + SdcArtifactHandlerConstants.ACTION + + " , VM_INSTANCE = $" + SdcArtifactHandlerConstants.VM_INSTANCE + " , VNFC_INSTANCE = $" + + SdcArtifactHandlerConstants.VNFC_INSTANCE + " , VNFC_TYPE = $" + + SdcArtifactHandlerConstants.VNFC_TYPE + " , VNFC_FUNCTION_CODE = $" + + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE + " , GROUP_NOTATION_TYPE = $" + + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE + " , IPADDRESS_V4_OAM_VIP = $" + + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP + " , GROUP_NOTATION_VALUE = $" + + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE; + + if (serviceLogic != null && context != null) { + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing VNFC_REFERENCE table "); + } + } + + public void processDownloadDgReference(SvcLogicContext context, boolean isUpdate) + throws SvcLogicException, SQLException { + String fn = "DBService.processDownloadDgReference"; + log.info(fn + "Starting DB operation for Download DG Reference " + isUpdate); + String key = ""; + QueryStatus status = null; + + if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + " set DOWNLOAD_CONFIG_DG = $" + + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where PROTOCOL = $" + + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; + else + key = "insert into " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + " set DOWNLOAD_CONFIG_DG = $" + + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " , PROTOCOL = $" + + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; + + if (serviceLogic != null && context != null) + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if ((status == null) || status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing DOWNLOAD_DG_REFERENCE table "); + } + + public void processConfigActionDg(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { + String fn = "DBService.processConfigActionDg"; + log.info(fn + "Starting DB operation for Config DG Action " + isUpdate); + String key = ""; + QueryStatus status = null; + + if (context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE) != null + && context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE).length() > 0) { + if (isUpdate) + key = "update " + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG + " set DOWNLOAD_CONFIG_DG = $" + + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where ACTION = $" + + SdcArtifactHandlerConstants.ACTION + " and VNF_TYPE = $" + + SdcArtifactHandlerConstants.VNF_TYPE; + else + key = "insert into " + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG + " set DOWNLOAD_CONFIG_DG = $" + + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " , ACTION = $" + + SdcArtifactHandlerConstants.ACTION + " , VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; + + if (serviceLogic != null && context != null) + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if ((status == null) || status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing Configure DG Action table "); + } else + log.info("No Update required for Config DG Action"); + + } + + public String getModelDataInformationbyArtifactName(String artifact_name) throws SvcLogicException { + String fn = "DBService.getVnfData"; + String key = ""; + SvcLogicContext con = new SvcLogicContext(); + HashMap modelData = new HashMap(); + QueryStatus status = null; + key = "select VNF_TYPE, VNFC_TYPE, ACTION, FILE_CATEGORY, ARTIFACT_TYPE from ASDC_REFERENCE where ARTIFACT_NAME = " + + artifact_name; + + if (serviceLogic != null && con != null) { + log.info(fn + "select Key: " + key); + status = serviceLogic.query("SQL", false, null, key, null, null, con); + if (status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing is ArtifactUpdateRequiredforPD table "); + + } + + log.info(fn + "Vnf_received :" + con.getAttribute("VNF_TYPE")); + + return con.getAttribute("VNF_TYPE"); + + } + + public void updateYangContents(SvcLogicContext context, String artifactId, String yangContents) + throws SvcLogicException { + String fn = "DBService.updateYangContents"; + log.info(fn + "Starting DB operation for updateYangContents"); + String key = ""; + QueryStatus status = null; + + key = "update ASDC_ARTIFACTS " + " set ARTIFACT_CONTENT = '" + yangContents + "'" + + " where ASDC_ARTIFACTS_ID = " + artifactId; + + if (serviceLogic != null && context != null) + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if ((status == null) || status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing Configure DG Action table "); + + } + + + public void insertProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action, + String action_level, String template) throws SvcLogicException { + String fn = "DBService.insertProtocolReference"; + log.info(fn + "Starting DB operation for insertProtocolReference"); + String key = ""; + QueryStatus status = null; + + key = "insert into PROTOCOL_REFERENCE (ACTION, VNF_TYPE, PROTOCOL, UPDATED_DATE, TEMPLATE, ACTION_LEVEL)" + + " values (" + "'" + action + "', '" + vnfType + "', '" + protocol + "', now(),'" + template + "', '" + + action_level + "')"; + + if (serviceLogic != null && context != null) + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if ((status == null) || status.toString().equals("FAILURE")) + throw new SvcLogicException("Error While processing insertProtocolReference "); + + } + + public boolean isProtocolReferenceUpdateRequired(SvcLogicContext context, String vnfType, String protocol, + String action, String action_level, String template) throws SvcLogicException { + SvcLogicContext localContext = new SvcLogicContext(); + String fn = "DBService.isProtocolReferenceUpdateRequired"; + log.info(fn + "Starting DB operation for isProtocolReferenceUpdateRequired"); + String key = ""; + QueryStatus status = null; + + key = "select COUNT(*) from PROTOCOL_REFERENCE where ACTION='" + action + "' and ACTION_LEVEL='" + action_level + + "' and VNF_TYPE='" + vnfType + "'"; + status = serviceLogic.query("SQL", false, null, key, null, null, localContext); + String countStr = localContext.getAttribute("COUNT(*)"); + int count = Integer.parseInt(countStr); + if (count > 0) + return true; + else + return false; + } + + public void updateProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action, + String action_level, String template) throws SvcLogicException { + + String fn = "DBService.isProtocolReferenceUpdateRequired"; + log.info(fn + "Starting DB operation for isProtocolReferenceUpdateRequired"); + String key = ""; + QueryStatus status = null; + + key = "update PROTOCOL_REFERENCE set UPDATED_DATE=now(), template='" + template + "' where ACTION='" + action + + "' and ACTION_LEVEL='" + action_level + "' and VNF_TYPE='" + vnfType + "'"; + status = serviceLogic.save("SQL", false, false, key, null, null, context); + if (status == QueryStatus.FAILURE) { + log.info("updateProtocolReference:: Error updating protocol reference"); + throw new SvcLogicException("Error - updating PROTOCOL_REFERENCE_TABLE in updateProtocolReference"); + } + return; + } + + public String getDownLoadDGReference(SvcLogicContext context) throws Exception { + String fn = "DBService.setDownLoadDGReference"; + String downloadConfigDg = null; + log.info(fn + "Setting Download DG Reference from DB"); + String key = ""; + QueryStatus status = null; + String protocol = context.getAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL); + if (StringUtils.isBlank(protocol)) { + log.info(fn + " :: Protocol is Blank!! Returning without querying DB"); + throw new Exception(fn+":: Protocol is Blank!! Returning without querying DB"); + } + key = "select download_config_dg from " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + + " where protocol = '" + protocol + "'"; + SvcLogicContext localContext = new SvcLogicContext(); + status = serviceLogic.query("SQL", false, null, key, null, null, localContext); + if (status == QueryStatus.FAILURE) { + log.info(fn + ":: Error retrieving download_config_dg"); + throw new SvcLogicException("Error retrieving download_config_dg"); + } + if (status == QueryStatus.NOT_FOUND) { + log.info(fn + ":: NOT_FOUND! No data found for download_config_dg!!"); + throw new Exception(fn + ":: NOT_FOUND! No data found for download_config_dg!"); + } + downloadConfigDg = localContext.getAttribute("download-config-dg"); + log.info(fn + "download_config_dg::" + downloadConfigDg); + return downloadConfigDg; + } + + public void cleanUpVnfcReferencesForVnf(SvcLogicContext context) throws SvcLogicException { + String key1 = "delete from " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + + " where action = 'Configure' and vnf_type = $" + SdcArtifactHandlerConstants.VNF_TYPE; + QueryStatus status = null; + log.info("cleanUpVnfcReferencesForVnf()::Query:" + key1); + if (serviceLogic != null && context != null) { + status = serviceLogic.save("SQL", false, false, key1, null, null, context); + if (status.toString().equals("FAILURE")) { + log.debug("Error deleting from VNFC_REFERENCE table"); + throw new SvcLogicException("Error While processing VNFC_REFERENCE table "); + } + } + } + + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNode.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNode.java new file mode 100644 index 000000000..f56581977 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNode.java @@ -0,0 +1,533 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.node; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.appc.artifact.handler.dbservices.DBService; +import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; +import org.onap.appc.yang.YANGGenerator; +import org.onap.appc.yang.impl.YANGGeneratorFactory; +import org.openecomp.sdnc.config.params.transformer.tosca.ArtifactProcessorImpl; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + + +public class ArtifactHandlerNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerNode.class); + + public void processArtifact(Map inParams, SvcLogicContext ctx) throws Exception { + String responsePrefix = inParams.get("response_prefix"); + try { + if (inParams != null && !inParams.isEmpty() && inParams.get("postData") != null) { + log.info("Received request for process Artifact with params: " + inParams.toString()); + String postData = inParams.get("postData"); + JSONObject input = new JSONObject(postData).getJSONObject("input"); + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; + storeUpdateSdcArtifacts(input); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + private boolean storeUpdateSdcArtifacts(JSONObject postDataJson) throws Exception { + log.info("Starting processing of SDC Artifacs into Handler with Data : " + postDataJson.toString()); + try { + JSONObject request_information = + (JSONObject) postDataJson.get(SdcArtifactHandlerConstants.REQUEST_INFORMATION); + JSONObject document_information = + (JSONObject) postDataJson.get(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS); + String artifact_name = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME); + if (artifact_name != null) { + updateStoreArtifacts(request_information, document_information); + if (artifact_name.toLowerCase().startsWith(SdcArtifactHandlerConstants.REFERENCE)) + return storeReferenceData(request_information, document_information); + else if (artifact_name.toLowerCase().startsWith(SdcArtifactHandlerConstants.PD)) + return createDataForPD(request_information, document_information); + + } else + throw new Exception("Missing Artifact Name for Request : " + + request_information.getString(SdcArtifactHandlerConstants.REQUETS_ID)); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Error while processing Request ID : " + + ((JSONObject) postDataJson.get(SdcArtifactHandlerConstants.REQUEST_INFORMATION)) + .getString(SdcArtifactHandlerConstants.REQUETS_ID) + + e.getMessage()); + } + return false; + + } + + private boolean createDataForPD(JSONObject request_information, JSONObject document_information) throws Exception { + + String fn = "ArtifactHandlerNode.createReferenceDataForPD"; + String artifact_name = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME); + log.info(fn + "Received PD File Name: " + artifact_name + " and suffix lenght " + + SdcArtifactHandlerConstants.PD.length()); + try { + + String suffix = artifact_name.substring(SdcArtifactHandlerConstants.PD.length()); + createArtifactRecords(request_information, document_information, suffix); + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Error while createing PD data records " + e.getMessage()); + } + return true; + } + + private void createArtifactRecords(JSONObject request_information, JSONObject document_information, String suffix) + throws Exception { + + log.info("Creating Tosca Records and storing into SDC Artifacs"); + String[] docs = {"Tosca", "Yang"}; + ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); + String PDFileContents = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS); + + // Tosca generation + OutputStream toscaStream = new ByteArrayOutputStream(); + String toscaContents = null; + ArtifactProcessorImpl toscaGenerator = new ArtifactProcessorImpl(); + toscaGenerator.generateArtifact(PDFileContents, toscaStream); + if (toscaStream != null) + toscaContents = toscaStream.toString(); + log.info("Generated Tosca File : " + toscaContents); + + String yangContents = "YANG generation is in Progress"; + String yangName = null; + + for (String doc : docs) { + document_information.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, doc.concat("Type")); + document_information.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, doc.concat("Model")); + if (doc.equals("Tosca")) + document_information.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, + ahpUtil.escapeSql(toscaContents)); + else if (doc.equals("Yang")) + document_information.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, + ahpUtil.escapeSql(yangContents)); + document_information.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, doc.concat(suffix)); + yangName = doc.concat(suffix); + updateStoreArtifacts(request_information, document_information); + } + + String artifactId = getArtifactID(yangName); + OutputStream yangStream = new ByteArrayOutputStream(); + YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator(); + yangGenerator.generateYANG(artifactId, toscaContents, yangStream); + if (yangStream != null) + yangContents = yangStream.toString(); + + if (yangContents != null) { + updateYangContents(artifactId, ahpUtil.escapeSql(yangContents)); + } + + } + + private void updateYangContents(String artifactId, String yangContents) throws SvcLogicException { + SvcLogicContext context = new SvcLogicContext(); + DBService dbservice = DBService.initialise(); + dbservice.updateYangContents(context, artifactId, yangContents); + } + + private String getArtifactID(String yangName) throws SvcLogicException { + SvcLogicContext context = new SvcLogicContext(); + DBService dbservice = DBService.initialise(); + return dbservice.getArtifactID(context, yangName); + } + + protected boolean updateStoreArtifacts(JSONObject request_information, JSONObject document_information) + throws Exception { + log.info("UpdateStoreArtifactsStarted storing of SDC Artifacs "); + + SvcLogicContext context = new SvcLogicContext(); + DBService dbservice = DBService.initialise(); + ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); + int intversion = 0; + context.setAttribute("artifact_name", + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + String internal_version = dbservice.getInternalVersionNumber(context, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); + log.info("Internal Version number received from Database : " + internal_version); + if (internal_version != null) { + intversion = Integer.parseInt(internal_version); + intversion++; + } + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_UUID, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.DISTRIBUTION_ID, + document_information.getString(SdcArtifactHandlerConstants.DISTRIBUTION_ID)); + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_NAME, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_NAME)); + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_UUID, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_VERSOIN)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_TYPE, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_TYPE)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_UUID, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, + ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS))); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + dbservice.saveArtifacts(context, intversion); + return true; + + } + + public boolean storeReferenceData(JSONObject request_information, JSONObject document_information) + throws Exception { + log.info("Started storing of SDC Artifacs into Handler"); + try { + boolean updateRequired = false; + boolean pdFile = false; + String suffix = null; + String categorySuffix = null; + DBService dbservice = DBService.initialise(); + ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); + String contentString = + ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS)); + String artifactName = + ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + String capabilityArtifactName = + StringUtils.replace(artifactName, SdcArtifactHandlerConstants.ARTIFACT_NAME_REFERENCE, + SdcArtifactHandlerConstants.ARTIFACT_NAME_CAPABILITY); + JSONObject capabilities = new JSONObject(); + JSONArray vnfActionList = new JSONArray(); + JSONArray vfModuleActionList = new JSONArray(); + JSONArray vnfcActionList = new JSONArray(); + JSONArray vmActionList = new JSONArray(); + String vnfType = null; + JSONObject contentObject = new JSONObject(contentString); + JSONArray contentArray = contentObject.getJSONArray("reference_data"); + boolean storeCapabilityArtifact=true; + for (int a = 0; a < contentArray.length(); a++) { + + JSONObject content = (JSONObject) contentArray.get(a); + log.info("contentString =" + content.toString()); + JSONObject scope = content.getJSONObject("scope"); + log.info("scope :" + scope); + SvcLogicContext context = new SvcLogicContext(); + vnfType = scope.getString(SdcArtifactHandlerConstants.VNF_TYPE); + context.setAttribute(SdcArtifactHandlerConstants.VNF_TYPE, + scope.getString(SdcArtifactHandlerConstants.VNF_TYPE)); + context.setAttribute(SdcArtifactHandlerConstants.ACTION, + content.getString(SdcArtifactHandlerConstants.ACTION)); + String actionLevel = content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL); + context.setAttribute(SdcArtifactHandlerConstants.ACTION_LEVEL, + content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL)); + if ((null != actionLevel) + && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VNFC)) { + vnfcActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); + } + if (null != actionLevel + && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VF_MODULE)) { + vfModuleActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); + } + if (null != actionLevel && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VNF)) { + vnfActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); + } + if (null != actionLevel && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VM)) { + vmActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); + } + if (scope.has(SdcArtifactHandlerConstants.VNFC_TYPE) + && !scope.isNull(SdcArtifactHandlerConstants.VNFC_TYPE)) { + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, + scope.getString(SdcArtifactHandlerConstants.VNFC_TYPE)); + String vnfcTypeScope = scope.getString(SdcArtifactHandlerConstants.VNFC_TYPE); + if (StringUtils.isNotBlank(vnfcTypeScope)) { + storeCapabilityArtifact = false; + log.info("No capability Artifact for this reference data as it is at VNFC level!!"); + } + } + else + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); + if (content.has(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)) + context.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL, + content.getString(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)); + if (content.has(SdcArtifactHandlerConstants.USER_NAME)) + context.setAttribute(SdcArtifactHandlerConstants.USER_NAME, + content.getString(SdcArtifactHandlerConstants.USER_NAME)); + if (content.has(SdcArtifactHandlerConstants.PORT_NUMBER)) + context.setAttribute(SdcArtifactHandlerConstants.PORT_NUMBER, + content.getString(SdcArtifactHandlerConstants.PORT_NUMBER)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, ""); + if (content.has("artifact-list") && content.get("artifact-list") instanceof JSONArray) { + JSONArray artifactLists = (JSONArray) content.get("artifact-list"); + for (int i = 0; i < artifactLists.length(); i++) { + JSONObject artifact = (JSONObject) artifactLists.get(i); + log.info("artifact is " + artifact); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, + artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, + artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE)); + + if (artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME) != null + && artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME).toLowerCase() + .startsWith(SdcArtifactHandlerConstants.PD)) { + suffix = artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME) + .substring(SdcArtifactHandlerConstants.PD.length()); + categorySuffix = artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE) + .substring(SdcArtifactHandlerConstants.PD.length()); + pdFile = true; + } + + dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); + + cleanArtifactInstanceData(context); + } + + if (pdFile) { + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, "Tosca".concat(suffix)); + context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, + SdcArtifactHandlerConstants.TOSCA_MODEL); + dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, "Yang".concat(suffix)); + context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, + SdcArtifactHandlerConstants.PARAMETER_YANG); + dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); + } + } + if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure") + || content.getString(SdcArtifactHandlerConstants.ACTION).equals("ConfigModify")) { + if (content.has(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE) + && content.getString(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE).length() > 0) { + context.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, + content.getString(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE)); + dbservice.processDownloadDgReference(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE)); + } + if (StringUtils.isBlank(context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE))) + context.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, + dbservice.getDownLoadDGReference(context)); + dbservice.processConfigActionDg(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG)); + if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure")) { + dbservice.processDeviceInterfaceProtocol(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL)); + dbservice.processDeviceAuthentication(context, dbservice.isArtifactUpdateRequired(context, + SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION)); + } + + } + + + populateProtocolReference(dbservice, content); + + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); + + if (content.has(SdcArtifactHandlerConstants.VM) + && content.get(SdcArtifactHandlerConstants.VM) instanceof JSONArray) { + JSONArray vmList = (JSONArray) content.get(SdcArtifactHandlerConstants.VM); + dbservice.cleanUpVnfcReferencesForVnf(context); + for (int i = 0; i < vmList.length(); i++) { + JSONObject vmInstance = (JSONObject) vmList.get(i); + context.setAttribute(SdcArtifactHandlerConstants.VM_INSTANCE, + String.valueOf(vmInstance.getInt(SdcArtifactHandlerConstants.VM_INSTANCE))); + log.info("VALUE = " + context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); + if (vmInstance.get(SdcArtifactHandlerConstants.VNFC) instanceof JSONArray) { + JSONArray vnfcInstanceList = (JSONArray) vmInstance.get(SdcArtifactHandlerConstants.VNFC); + for (int k = 0; k < vnfcInstanceList.length(); k++) { + JSONObject vnfcInstance = (JSONObject) vnfcInstanceList.get(k); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE, + String.valueOf(vnfcInstance.getInt(SdcArtifactHandlerConstants.VNFC_INSTANCE))); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, + vnfcInstance.getString(SdcArtifactHandlerConstants.VNFC_TYPE)); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE, + vnfcInstance.getString(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE)); + if (vnfcInstance.has(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP)) + context.setAttribute(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP, + vnfcInstance.getString(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP)); + if (vnfcInstance.has(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE)) + context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE, + vnfcInstance.getString(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE)); + if (vnfcInstance.has(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE)) + context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE, + vnfcInstance.getString(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE)); + if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure")) { + dbservice.processVnfcReference(context,false); + } + cleanVnfcInstance(context); + } + context.setAttribute(SdcArtifactHandlerConstants.VM_INSTANCE, null); + } + } + } + + + } + if (storeCapabilityArtifact) { + capabilities.put("vnf", vnfActionList); + capabilities.put("vf-module", vfModuleActionList); + capabilities.put("vnfc", vnfcActionList); + capabilities.put("vm", vmActionList); + processAndStoreCapablitiesArtifact(dbservice, document_information, capabilities, capabilityArtifactName, + vnfType); + } + + } catch (Exception e) { + e.printStackTrace(); + throw new Exception("Error While Storing : " + e.getMessage()); + } + + return true; + } + + private void cleanArtifactInstanceData(SvcLogicContext context) { + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, null); + context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, null); + } + + private void cleanVnfcInstance(SvcLogicContext context) { + + context.setAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE, null); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE, null); + context.setAttribute(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP, null); + context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE, null); + context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE, null); + + } + + private void processAndStoreCapablitiesArtifact(DBService dbservice, JSONObject document_information, + JSONObject capabilities, String capabilityArtifactName, String vnfType) throws Exception { + log.info("Begin-->processAndStoreCapablitiesArtifact "); + + try { + + JSONObject newCapabilitiesObject = new JSONObject(); + newCapabilitiesObject.put("capabilities", capabilities); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, capabilityArtifactName); + context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, SdcArtifactHandlerConstants.CAPABILITY); + context.setAttribute(SdcArtifactHandlerConstants.ACTION, null); + context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, null); + context.setAttribute(SdcArtifactHandlerConstants.VNF_TYPE, vnfType); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, newCapabilitiesObject.toString()); + dbservice.processSdcReferences(context, + dbservice.isArtifactUpdateRequired(context, SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); + int intversion = 0; + + String internal_version = dbservice.getInternalVersionNumber(context, + context.getAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); + log.info("Internal Version number received from Database : " + internal_version); + if (internal_version != null) { + intversion = Integer.parseInt(internal_version); + intversion++; + } + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_UUID, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.DISTRIBUTION_ID, + document_information.getString(SdcArtifactHandlerConstants.DISTRIBUTION_ID)); + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_NAME, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_NAME)); + context.setAttribute(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, + document_information.getString(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_UUID, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_VERSOIN)); + context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_TYPE, + document_information.getString(SdcArtifactHandlerConstants.RESOURCE_TYPE)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_UUID, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_UUID)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN)); + context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION)); + + + dbservice.saveArtifacts(context, intversion); + return; + } catch (Exception e) { + log.error("Error saving capabilities artifact to DB: " + e.toString()); + throw e; + } finally { + log.info("End-->processAndStoreCapablitiesArtifact "); + } + + } + + private void populateProtocolReference(DBService dbservice, JSONObject content) throws Exception { + log.info("Begin-->populateProtocolReference "); + try { + SvcLogicContext context = new SvcLogicContext(); + JSONObject scope = content.getJSONObject("scope"); + String vnfType = null, protocol = null, action = null, actionLevel = null, template = null; + if (scope.has(SdcArtifactHandlerConstants.VNF_TYPE) && !scope.isNull(SdcArtifactHandlerConstants.VNF_TYPE)) + vnfType = scope.getString(SdcArtifactHandlerConstants.VNF_TYPE); + if (content.has(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)) + protocol = content.getString(SdcArtifactHandlerConstants.DEVICE_PROTOCOL); + if (content.has(SdcArtifactHandlerConstants.ACTION)) + action = content.getString(SdcArtifactHandlerConstants.ACTION); + if (content.has(SdcArtifactHandlerConstants.ACTION_LEVEL)) + actionLevel = content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL); + if (content.has(SdcArtifactHandlerConstants.TEMPLATE) + && !content.isNull(SdcArtifactHandlerConstants.TEMPLATE)) + template = content.getString(SdcArtifactHandlerConstants.TEMPLATE); + boolean isUpdateNeeded=dbservice.isProtocolReferenceUpdateRequired(context, vnfType, protocol, action, actionLevel, template); + if (isUpdateNeeded) + dbservice.updateProtocolReference(context, vnfType, protocol, action, actionLevel, template); + else + dbservice.insertProtocolReference(context, vnfType,protocol,action,actionLevel,template); + } catch (Exception e) { + log.error("Error inserting record into protocolReference: " + e.toString()); + throw e; + } finally { + log.info("End-->populateProtocolReference "); + } + } + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java new file mode 100644 index 000000000..15859178a --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.utils; + +import java.io.IOException; +import java.security.SecureRandom; +import java.util.HashMap; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInput; +import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ArtifactHandlerProviderUtil { + + public UploadartifactInput templateData ; + SvcLogicContext context = null; + private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerProviderUtil.class); + public static void loadProperties() { + // TODO Auto-generated method stub + + } + public enum DistributionStatusEnum { + DOWNLOAD_OK, + DOWNLOAD_ERROR, + ALREADY_DOWNLOADED, + DEPLOY_OK, + DEPLOY_ERROR, + ALREADY_DEPLOYED; + } + + public ArtifactHandlerProviderUtil(){}; + + public ArtifactHandlerProviderUtil(UploadartifactInput input) { + this.templateData = input; + log.info("templateData " + this.templateData); + } + + public void processTemplate(String requestInfo) throws Exception { + if(context == null) + context = new SvcLogicContext(); + + ArtifactHandlerNode node = new ArtifactHandlerNode(); + try { + + HashMap processdata = new HashMap(); + processdata.put("postData", requestInfo); + log.info("Post data = " + requestInfo); + node.processArtifact(processdata, context); + } catch (Exception e) { + // TODO Auto-generated catch block + log.error("Error: " + e.getMessage()); + e.printStackTrace(); + throw e; + } + + } + public String createDummyRequestData() throws JSONException, IOException{ + + + JSONObject info = new JSONObject(this.templateData); + log.info("INFO = " + info); + String artifact_name = templateData.getDocumentParameters().getArtifactName(); + String artifact_version = templateData.getDocumentParameters().getArtifactVersion(); + + JSONObject json = new JSONObject(); + JSONObject requestInfo = new JSONObject(); + String random = getRandom(); + + requestInfo.put(SdcArtifactHandlerConstants.REQUETS_ID, "TLRID-" + random); + requestInfo.put(SdcArtifactHandlerConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); + requestInfo.put(SdcArtifactHandlerConstants.SOURCE, "TemplateLoader"); + + JSONObject docParams = new JSONObject(); + docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID, "TLSUUID" + templateData.getRequestInformation().getRequestId()); + docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "TLDID" + random); + docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, "TLServiceName"); + docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "Template Loader Test"); + docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS, "[]"); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "TLRUID" + random); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "TLRIName"); + docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, "TLResourceName"); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, "TLResourceVersion"); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "TLResourceType"); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "TLAUUID" + random); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, "APPC-CONFIG"); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, templateData.getDocumentParameters().getArtifactVersion()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "SdcTestDescription"); + // String data = IOUtils.toString(TestartifactHandlerNode.class.getClassLoader().getResourceAsStream("template_msrp_msc_a_template.json"), "utf-8"); + // String data = IOUtils.toString(TemplateProcessor.class.getClassLoader().getResourceAsStream("referenceData.json"), "utf-8"); + + // this.templateData = this.templateData.substring(this.templateData.indexOf("}") + 1); + docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents()); + + json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); + json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams); + System.out.println("Final data =" + this.templateData); + return String.format("{\"input\": %s}", json.toString()); + } + + private String getRandom() { + SecureRandom random = new SecureRandom(); + int num = random.nextInt(100000); + String formatted = String.format("%05d", num); + return formatted; + } + + public String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\"}; + String replacementList[] = new String[]{ "''","\\\\"}; + return StringUtils.replaceEach(str,searchList, replacementList); + } + public String createRequestData() throws JSONException, IOException{ + + + JSONObject info = new JSONObject(this.templateData); + log.info("INFO = " + info); + + JSONObject json = new JSONObject(); + JSONObject requestInfo = new JSONObject(); + String random = getRandom(); + + requestInfo.put(SdcArtifactHandlerConstants.REQUETS_ID, templateData.getRequestInformation().getRequestId()); + requestInfo.put(SdcArtifactHandlerConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); + requestInfo.put(SdcArtifactHandlerConstants.SOURCE, templateData.getRequestInformation().getSource()); + + String serviceDescription = serviceDescriptionData(templateData.getDocumentParameters().getServiceDescription()); + + JSONObject docParams = new JSONObject(); + docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID, templateData.getDocumentParameters().getResourceUuid()); + docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, templateData.getDocumentParameters().getDistributionId()); + docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, templateData.getDocumentParameters().getServiceName()); + docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION,serviceDescription); + docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS, templateData.getDocumentParameters().getServiceArtifacts()); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_UUID, templateData.getDocumentParameters().getResourceUuid()); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, templateData.getDocumentParameters().getResourceInstanceName()); + docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, templateData.getDocumentParameters().getResourceName()); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, templateData.getDocumentParameters().getResourceVersion()); + docParams.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, templateData.getDocumentParameters().getResourceType()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, templateData.getDocumentParameters().getArtifactUuid()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, templateData.getDocumentParameters().getArtifactType()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, templateData.getDocumentParameters().getArtifactVersion()); + docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, templateData.getDocumentParameters().getArtifactDescription()); + + docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents()); + + json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); + json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams); + System.out.println("Final data =" + this.templateData); + return String.format("{\"input\": %s}", json.toString()); + } + + private String serviceDescriptionData(String serviceDescription){ + if(!StringUtils.isBlank(serviceDescription)&&serviceDescription.length()>255){ + serviceDescription = serviceDescription.substring(0, 255); + } + return serviceDescription; + } +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/EscapeUtils.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/EscapeUtils.java new file mode 100644 index 000000000..ece5cdb24 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/EscapeUtils.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.utils; + +import org.apache.commons.lang3.StringUtils; + +public class EscapeUtils { + + public EscapeUtils() { + // TODO Auto-generated constructor stub + } + + public static String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\"}; + String replacementList[] = new String[]{ "''","\\\\"}; + return StringUtils.replaceEach(str,searchList, replacementList); + } +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java new file mode 100644 index 000000000..c045ee7d4 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/onap/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.utils; + +public class SdcArtifactHandlerConstants { + + public static final String DOCUMENT_PARAMETERS = "document-parameters"; + public static final String SERVICE_UUID = "service-uuid"; + public static final String DISTRIBUTION_ID = "distribution-id"; + public static final String REQUETS_ID = "request-id"; + public static final String REQUEST_ACTION = "request-action"; + public static final String SOURCE = "source"; + public static final String SERVICE_NAME = "service-name"; + public static final String SERVICE_DESCRIPTION ="service-description"; + public static final String SERVICE_ARTIFACTS = "service-artifacts"; + public static final String RESOURCE_UUID ="resource-uuid"; + public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name"; + public static final String REOURCE_NAME = "resource-name"; + public static final String RESOURCE_VERSOIN ="resource-version"; + public static final String RESOURCE_TYPE= "resource-type"; + public static final String ARTIFACT_UUID ="artifact-uuid"; + public static final String ARTIFACT_NAME = "artifact-name"; + public static final String ARTIFACT_TYPE = "artifact-type"; + public static final String ARTIFACT_VERSOIN = "artifact-version"; + public static final String ARTIFACT_DESRIPTION = "artifact-description"; + public static final String ARTIFACT_CONTENTS = "artifact-contents"; + public static final String REQUEST_INFORMATION = "request-information"; + public static final String INTERNAL_VERSION = "internal-versoin"; + public static final String FILE_CATEGORY = "file-category"; + public static final String VNF_TYPE = "vnf-type"; + public static final String ACTION = "action"; + public static final String ACTION_LEVEL = "action-level"; + public static final String VNFC_TYPE = "vnfc-type"; + public static final String VM_INSTANCE = "vm-instance"; + public static final String VM = "vm"; + public static final String VNFC = "vnfc"; + public static final String VNFC_FUNCTION_CODE = "vnfc-function-code"; + public static final String GROUP_NOTATION = "group-notation"; + public static final String IPADDRESS_V4_OAM_VIP = "ipaddress-v4-oam-vip"; + public static final String GROUP_NOTATION_TYPE = "group-notation-type"; + public static final String GROUP_NOTATION_VALUE = "group-notation-value"; + public static final String REFERENCE = "reference"; + public static final String VNFC_INSTANCE = "vnfc-instance"; + public static final String DEVICE_PROTOCOL = "device-protocol"; + public static final String DG_RPC = "dg-rpc"; + public static final String MODULE = "module"; + public static final String USER_NAME = "user-name"; + public static final String PORT_NUMBER = "port-number"; + public static final String DOWNLOAD_DG_REFERENCE = "download-dg-reference"; + + + public static final String DB_DOWNLOAD_DG_REFERENCE = "DOWNLOAD_DG_REFERENCE"; + public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; + public static final String DB_DEVICE_INTERFACE_PROTOCOL = "DEVICE_INTERFACE_PROTOCOL"; + public static final String DB_DEVICE_AUTHENTICATION = "DEVICE_AUTHENTICATION"; + public static final String DB_VNFC_REFERENCE = "VNFC_REFERENCE"; + public static final String DB_CONFIG_ACTION_DG = "CONFIGURE_ACTION_DG"; + public static final String PD = "pd"; + public static final String PARAMETER_YANG = "parameter_yang"; + public static final String TOSCA_MODEL = "tosca_model"; + public static final String DESIGN_TOOL = "Design-tool"; + public static final String ACTION_LEVEL_VNFC = "VNFC"; + public static final String ACTION_LEVEL_VF_MODULE ="VF-MODULE"; + public static final String ACTION_LEVEL_VNF = "VNF"; + public static final String ACTION_LEVEL_VM = "VM"; + public static final String CAPABILITY = "capability"; + public static final String TEMPLATE = "template"; + public static final String ARTIFACT_NAME_REFERENCE = "reference"; + public static final String ARTIFACT_NAME_CAPABILITY = "capability"; +} + diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java new file mode 100644 index 000000000..67bb19941 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321; + +import org.onap.appc.artifact.handler.ArtifactHandlerProvider; + +public class ArtifactHandlerProviderModule extends org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.AbstractArtifactHandlerProviderModule { + public ArtifactHandlerProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public ArtifactHandlerProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.ArtifactHandlerProviderModule oldModule, java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void customValidation() { + // add custom validation form module attributes here. + } + + @Override + public java.lang.AutoCloseable createInstance() { + final ArtifactHandlerProvider provider = new ArtifactHandlerProvider(getDataBrokerDependency() + , getNotificationServiceDependency() + , getRpcRegistryDependency()); + + return new AutoCloseable() { + + @Override + public void close() throws Exception { + provider.close(); + } + }; + } + + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java new file mode 100644 index 000000000..7190da5b9 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/* +* Generated file +* +* Generated from: yang module name: artifact-handler-provider-impl yang module local name: artifact-handler-provider-impl +* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator +* Generated at: Wed Aug 09 09:36:59 EDT 2017 +* +* Do not modify this file unless it is present under src/main directory +*/ +package org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321; +public class ArtifactHandlerProviderModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.AbstractArtifactHandlerProviderModuleFactory { + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java deleted file mode 100644 index 67bb19941..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModule.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321; - -import org.onap.appc.artifact.handler.ArtifactHandlerProvider; - -public class ArtifactHandlerProviderModule extends org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.AbstractArtifactHandlerProviderModule { - public ArtifactHandlerProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public ArtifactHandlerProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.ArtifactHandlerProviderModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - final ArtifactHandlerProvider provider = new ArtifactHandlerProvider(getDataBrokerDependency() - , getNotificationServiceDependency() - , getRpcRegistryDependency()); - - return new AutoCloseable() { - - @Override - public void close() throws Exception { - provider.close(); - } - }; - } - - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java deleted file mode 100644 index 7190da5b9..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/artifact/handler/provider/impl/rev170321/ArtifactHandlerProviderModuleFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/* -* Generated file -* -* Generated from: yang module name: artifact-handler-provider-impl yang module local name: artifact-handler-provider-impl -* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator -* Generated at: Wed Aug 09 09:36:59 EDT 2017 -* -* Do not modify this file unless it is present under src/main directory -*/ -package org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321; -public class ArtifactHandlerProviderModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.artifact.handler.provider.impl.rev170321.AbstractArtifactHandlerProviderModuleFactory { - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/ArtifactHandlerProvider.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/ArtifactHandlerProvider.java deleted file mode 100644 index d5ccd45b0..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/ArtifactHandlerProvider.java +++ /dev/null @@ -1,213 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler; - -import java.util.HashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.DataChangeListener; -import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.ArtifactHandlerService; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.uploadartifact.output.ConfigDocumentResponseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Services; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.ServicesBuilder; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; -import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.Futures; - - - -public class ArtifactHandlerProvider implements AutoCloseable, ArtifactHandlerService, DataChangeListener { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerProvider.class); - private final String appName = "ArtifactsHandler"; - private final ExecutorService executor; - protected DataBroker dataBroker; - protected NotificationProviderService notificationService; - protected RpcProviderRegistry rpcRegistry; - private ListenerRegistration dclServices; - - protected BindingAwareBroker.RpcRegistration rpcRegistration; - - public ArtifactHandlerProvider(DataBroker dataBroker2, - NotificationProviderService notificationProviderService, - RpcProviderRegistry rpcProviderRegistry) { - this.log.info("Creating provider for " + appName); - executor = Executors.newFixedThreadPool(10); - dataBroker = dataBroker2; - notificationService = notificationProviderService; - rpcRegistry = rpcProviderRegistry; - initialize(); - - } - - public void initialize() { - log.info("Initializing provider for " + appName); - // Create the top level containers - createContainers(); - try { - ArtifactHandlerProviderUtil.loadProperties(); - } catch (Exception e) { - log.error("Caught Exception while trying to load properties file"); - } - // Listener for changes to Services tree - - rpcRegistration = rpcRegistry.addRpcImplementation( - ArtifactHandlerService.class, this); - - log.info("Initialization complete for " + appName); - } - private void createContainers() { - final WriteTransaction t = dataBroker.newReadWriteTransaction(); - // Create the Services container - t.merge(LogicalDatastoreType.CONFIGURATION,InstanceIdentifier.create(Services.class),new ServicesBuilder().build()); - t.merge(LogicalDatastoreType.OPERATIONAL,InstanceIdentifier.create(Services.class),new ServicesBuilder().build()); - - try { - CheckedFuture checkedFuture = t.submit(); - checkedFuture.get(); - log.info("Create Containers succeeded!: "); - - } catch (InterruptedException | ExecutionException e) { - log.error("Create Containers Failed: " + e); - e.printStackTrace(); - } - } - - - @Override - public void onDataChanged(AsyncDataChangeEvent, DataObject> arg0) { - // TODO Auto-generated method stub - - } - - - - @Override - public void close() throws Exception { - - log.info("Closing provider for " + appName); - if(this.executor != null){ - executor.shutdown(); - } - if(this.rpcRegistration != null){ - rpcRegistration.close(); - } - log.info("Successfully closed provider for " + appName); - - } - - private RpcResult buildResponse1( - String svcRequestId, - String topic, - String code, - String message, - String finalInd) { - - UploadartifactOutputBuilder responseBuilder = new UploadartifactOutputBuilder(); - ConfigDocumentResponseBuilder configResponseBuilder=new ConfigDocumentResponseBuilder(); - configResponseBuilder.setRequestId(svcRequestId); - configResponseBuilder.setStatus(code); - configResponseBuilder.setErrorReason(message); - RpcResult rpcResult = RpcResultBuilder. status(true) - .withResult(responseBuilder.build()).build(); - return rpcResult; - } - - @Override - public Future> uploadartifact(UploadartifactInput input) { - - if (input == null || input.getDocumentParameters() == null || input.getDocumentParameters().getArtifactContents() == null ) { - RpcResult rpcResult = - buildResponse1("N/A", "N/A", "INVALID_INPUT", "Invalid input, null or empty document information" , "Y"); - return Futures.immediateFuture(rpcResult); - } - UploadartifactInputBuilder inputBuilder = new UploadartifactInputBuilder(input); - ConfigDocumentResponseBuilder configResponseBuilder = new ConfigDocumentResponseBuilder(); - UploadartifactOutputBuilder responseBuilder = new UploadartifactOutputBuilder(); - log.info("Received input = " + input ); - ArtifactHandlerProviderUtil designUtil = new ArtifactHandlerProviderUtil(input); - configResponseBuilder.setRequestId(input.getRequestInformation().getRequestId()); - try{ - - if(input.getRequestInformation().getSource() !=null){ - if(input.getRequestInformation().getSource().equalsIgnoreCase(SdcArtifactHandlerConstants.DESIGN_TOOL)){ - designUtil.processTemplate(designUtil.createDummyRequestData()); - configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_OK.toString()); - } - else - { - designUtil.processTemplate(designUtil.createRequestData()); - configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_OK.toString()); - } - } - else - { - throw new Exception("No Tempalte data found"); - } - - - } - catch (Exception e) { - - configResponseBuilder.setErrorReason(e.getMessage()); - configResponseBuilder.setStatus(ArtifactHandlerProviderUtil.DistributionStatusEnum.DEPLOY_ERROR.toString()); - log.error("Caught exception looking for Artifact Handler", e); - log.info("Caught exception looking for Artifact Handler: "); - } - - responseBuilder.setConfigDocumentResponse(configResponseBuilder.build()); - RpcResult rpcResult = RpcResultBuilder. status(true).withResult(responseBuilder.build()).build(); - return Futures.immediateFuture(rpcResult); - - } -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/SdcArtifactHandlerActivator.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/SdcArtifactHandlerActivator.java deleted file mode 100644 index ebbbe4735..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/SdcArtifactHandlerActivator.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler; - -import java.util.LinkedList; -import java.util.List; - -import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class SdcArtifactHandlerActivator implements BundleActivator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(SdcArtifactHandlerActivator.class); - private List registrations = new LinkedList(); - - @Override - public void start(BundleContext ctx) throws Exception { - ArtifactHandlerNode artifactHandlerNode = new ArtifactHandlerNode(); - log.info("Registering service-- " + artifactHandlerNode.getClass().getName()); - registrations.add(ctx.registerService(artifactHandlerNode.getClass().getName(), artifactHandlerNode, null)); - - } - - @Override - public void stop(BundleContext arg0) throws Exception { - for (ServiceRegistration registration : registrations) { - registration.unregister(); - registration = null; - } - } -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/dbservices/DBService.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/dbservices/DBService.java deleted file mode 100644 index 031d53e28..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/dbservices/DBService.java +++ /dev/null @@ -1,531 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.dbservices; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; - -import java.sql.SQLException; -import java.util.HashMap; -import org.apache.commons.lang.StringUtils; - -public class DBService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DBService.class); - private SvcLogicResource serviceLogic; - private static DBService dgGeneralDBService = null; - - public static DBService initialise() { - if (dgGeneralDBService == null) { - dgGeneralDBService = new DBService(); - } - return dgGeneralDBService; - } - - private DBService() { - if (serviceLogic == null) { - serviceLogic = new SqlResource(); - } - } - - protected DBService(SqlResource svcLogic) { - if (serviceLogic == null) { - serviceLogic = svcLogic; - } - } - - public String getInternalVersionNumber(SvcLogicContext ctx, String artifactName, String prefix) - throws SvcLogicException { - String fn = "DBService.getInternalVersionNumber"; - QueryStatus status = null; - String artifactInternalVersion = null; - if (serviceLogic != null && ctx != null) { - String key = "select max(internal_version) as maximum from ASDC_ARTIFACTS WHERE ARTIFACT_NAME = '" - + artifactName + "'"; - log.info("Getting internal Versoin :" + key); - status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - getting internal Artifact Number"); - artifactInternalVersion = ctx.getAttribute("maximum"); - log.info("Internal Version received as : " + artifactInternalVersion); - log.info("Internal Version received as1 : " + ctx.getAttribute("max(internal_version)")); - log.info("Internal Version received as1 : " + ctx.getAttribute("max")); - log.info("Internal Version received as1 : " + ctx.getAttribute("internal_version")); - log.info("Internal Version received as1 : " + ctx.getAttributeKeySet().toString()); - } - return artifactInternalVersion; - } - - public String getArtifactID(SvcLogicContext ctx, String artifactName) throws SvcLogicException { - String fn = "DBService.getArtifactID"; - QueryStatus status = null; - String artifactID = null; - if (serviceLogic != null && ctx != null) { - String key = "select max(ASDC_ARTIFACTS_ID) as id from ASDC_ARTIFACTS WHERE ARTIFACT_NAME = '" - + artifactName + "'"; - log.info("Getting Artifact ID String :" + key); - status = serviceLogic.query("SQL", false, null, key, null, null, ctx); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error - getting Artifact ID from database"); - artifactID = ctx.getAttribute("id"); - log.info("SDC_ARTIFACTS_ID received as : " + ctx.getAttribute("id")); - } - return artifactID; - } - - public QueryStatus saveArtifacts(SvcLogicContext ctx, int intversion) throws SvcLogicException { - String fn = "DBService.saveArtifacts"; - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "INSERT INTO ASDC_ARTIFACTS " + "SET SERVICE_UUID = $service-uuid , " - + " DISTRIBUTION_ID = $distribution-id ," + " SERVICE_NAME = $service-name ," - + " SERVICE_DESCRIPTION = $service-description ," + " RESOURCE_UUID = $resource-uuid ," - + " RESOURCE_INSTANCE_NAME = $resource-instance-name ," + " RESOURCE_NAME = $resource-name ," - + " RESOURCE_VERSION = $resource-version ," + " RESOURCE_TYPE = $resource-type ," - + " ARTIFACT_UUID = $artifact-uuid ," + " ARTIFACT_TYPE = $artifact-type ," - + " ARTIFACT_VERSION = $artifact-version ," + " ARTIFACT_DESCRIPTION = $artifact-description ," - + " INTERNAL_VERSION = " + intversion + "," + " ARTIFACT_NAME = $artifact-name ," - + " ARTIFACT_CONTENT = $artifact-contents "; - - status = serviceLogic.save("SQL", false, false, key, null, null, ctx); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing storing Artifact: " - + ctx.getAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - } - return status; - - } - - public QueryStatus logData(SvcLogicContext ctx, String prefix) throws SvcLogicException { - String fn = "DBService.saveReferenceData"; - QueryStatus status = null; - if (serviceLogic != null && ctx != null) { - String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + " SET request_id = $request-id , " - + " message_type = $log-message-type , " + " message = $log-message ;"; - status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error while loging data"); - - } - return status; - } - - public void processConfigureActionDg(SvcLogicContext context, boolean isUpdate) { - String fn = "DBService.processConfigureActionDg"; - log.info("Update Parameter for SDC Reference " + isUpdate); - String key = ""; - QueryStatus status = null; - if (isUpdate) - ; - } - - public void processSdcReferences(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { - String fn = "DBService.processSdcReferences"; - String key = ""; - QueryStatus status = null; - - if (isUpdate && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY).equals(SdcArtifactHandlerConstants.CAPABILITY)) { - log.info("Updating capability artifact in ASDC_REFERENCE"); - key = "update " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set ARTIFACT_NAME = $" - + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where " + "FILE_CATEGORY = $" - + SdcArtifactHandlerConstants.FILE_CATEGORY + " and VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE ; - } else if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set ARTIFACT_NAME = $" - + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where VNFC_TYPE = $" - + SdcArtifactHandlerConstants.VNFC_TYPE + " and FILE_CATEGORY = $" - + SdcArtifactHandlerConstants.FILE_CATEGORY + " and ACTION = $" - + SdcArtifactHandlerConstants.ACTION + " and VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; - - else { - if (context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY).equals(SdcArtifactHandlerConstants.CAPABILITY)) { - key = "insert into " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = null " - + " , FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY + " , VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = null " + " , ARTIFACT_TYPE = null " - + " , ARTIFACT_NAME = $" + SdcArtifactHandlerConstants.ARTIFACT_NAME; - } else { - key = "insert into " + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = $" - + SdcArtifactHandlerConstants.VNFC_TYPE + " , FILE_CATEGORY = $" - + SdcArtifactHandlerConstants.FILE_CATEGORY + " , VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = $" + SdcArtifactHandlerConstants.ACTION - + " , ARTIFACT_TYPE = $" + SdcArtifactHandlerConstants.ARTIFACT_TYPE + " , ARTIFACT_NAME = $" - + SdcArtifactHandlerConstants.ARTIFACT_NAME; - } - } - if (serviceLogic != null && context != null) { - log.info("Insert Key: " + key); - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing sdc_reference table "); - } - } - - public boolean isArtifactUpdateRequired(SvcLogicContext context, String db) throws SvcLogicException, SQLException { - String fn = "DBService.isArtifactUpdateRequired"; - log.info("Checking if Update required for this data"); - - log.info("db" + db); - log.info("ACTION=" + context.getAttribute(SdcArtifactHandlerConstants.ACTION)); - log.info("VNFC_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_TYPE)); - log.info("VNFC_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); - log.info("VM_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); - log.info("VNF_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE)); - String whereClause = ""; - - QueryStatus status = null; - whereClause = " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; - - if (db != null) { - if (db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE) - && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY) - .equals(SdcArtifactHandlerConstants.CAPABILITY) - && context.getAttribute(SdcArtifactHandlerConstants.ACTION) == null) { - whereClause = whereClause + " and FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY; - } - - else if (db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE)) { - whereClause = whereClause + " and VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE - + " and FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY + " and ACTION = $" - + SdcArtifactHandlerConstants.ACTION; - } - - else if (db.equals(SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE)) { - whereClause = " where PROTOCOL = $" + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; - } else if (db.equals(SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG)) { - whereClause = whereClause + " and ACTION = $" + SdcArtifactHandlerConstants.ACTION; - } else if (db.equals(SdcArtifactHandlerConstants.DB_VNFC_REFERENCE)) { - int vm_instance = -1; - if (context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE) != null) - vm_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); - int vnfc_instance = -1; - if (context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE) != null) - vnfc_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); - whereClause = whereClause + " and ACTION = $" + SdcArtifactHandlerConstants.ACTION + " and VNFC_TYPE = $" - + SdcArtifactHandlerConstants.VNFC_TYPE + " and VNFC_INSTANCE = $" - + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $" - + SdcArtifactHandlerConstants.VM_INSTANCE; - - } - } - - if (serviceLogic != null && context != null) { - String key = "select COUNT(*) from " + db + whereClause; - log.info("SELECT String : " + key); - status = serviceLogic.query("SQL", false, null, key, null, null, context); - if (status.toString().equals("FAILURE")) { - throw new SvcLogicException("Error while reading data from " + db); - } - String count = context.getAttribute("COUNT(*)"); - log.info("Number of row Returned : " + count + ": " + status + ":"); - if (count != null && Integer.parseInt(count) > 0) { - context.setAttribute(count, null); - return true; - } else - return false; - } - return false; - } - - public void processDeviceInterfaceProtocol(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { - String fn = "DBService.processDeviceInterfaceProtocol"; - log.info("Starting DB operation for Device Interface Protocol " + isUpdate); - String key = ""; - QueryStatus status = null; - if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set PROTOCOL = $" - + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' " - + " , MODULE = 'APPC' " + " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; - else - key = "insert into " + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE + " , PROTOCOL = $" - + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' " - + " , MODULE = 'APPC' "; - - if (serviceLogic != null && context != null) { - - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing DEVICE_INTERFACE_PROTOCOL table "); - } - - } - - public void processDeviceAuthentication(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { - String fn = "DBService.processDeviceAuthentication"; - log.info(fn + "Starting DB operation for Device Authentication " + isUpdate); - String key = ""; - QueryStatus status = null; - if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION + " set USER_NAME = $" - + SdcArtifactHandlerConstants.USER_NAME +/* " , PASSWORD = 'dummy' " +*/ " , PORT_NUMBER = $" - + SdcArtifactHandlerConstants.PORT_NUMBER + " where VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE; - else - key = "insert into " + SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION + " set VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE + " , USER_NAME = $" + SdcArtifactHandlerConstants.USER_NAME - +/* " , PASSWORD = 'dummy' " + */ " , PORT_NUMBER = $" + SdcArtifactHandlerConstants.PORT_NUMBER; - - if (serviceLogic != null && context != null) { - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing DEVICE_AUTHENTICATION table "); - } - } - - public void processVnfcReference(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { - String fn = "DBService.processVnfcReference"; - log.info(fn + "Starting DB operation for Vnfc Reference " + isUpdate); - String key = ""; - int vm_instance = -1; - if (context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE) != null) - vm_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); - int vnfc_instance = -1; - if (context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE) != null) - vnfc_instance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE)); - QueryStatus status = null; - if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set VM_INSTANCE = " + vm_instance - + " , VNFC_INSTANCE = " + vnfc_instance + " , VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE - + " , VNFC_FUNCTION_CODE = $" + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE - + " , GROUP_NOTATION_TYPE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE - + " , GROUP_NOTATION_VALUE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE - + " , IPADDRESS_V4_OAM_VIP = $" + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP - + " where VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE + " and ACTION = $" - + SdcArtifactHandlerConstants.ACTION + " and VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE - + " and VNFC_INSTANCE = $" + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $" - + SdcArtifactHandlerConstants.VM_INSTANCE; - else - key = "insert into " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = $" + SdcArtifactHandlerConstants.ACTION - + " , VM_INSTANCE = $" + SdcArtifactHandlerConstants.VM_INSTANCE + " , VNFC_INSTANCE = $" - + SdcArtifactHandlerConstants.VNFC_INSTANCE + " , VNFC_TYPE = $" - + SdcArtifactHandlerConstants.VNFC_TYPE + " , VNFC_FUNCTION_CODE = $" - + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE + " , GROUP_NOTATION_TYPE = $" - + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE + " , IPADDRESS_V4_OAM_VIP = $" - + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP + " , GROUP_NOTATION_VALUE = $" - + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE; - - if (serviceLogic != null && context != null) { - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing VNFC_REFERENCE table "); - } - } - - public void processDownloadDgReference(SvcLogicContext context, boolean isUpdate) - throws SvcLogicException, SQLException { - String fn = "DBService.processDownloadDgReference"; - log.info(fn + "Starting DB operation for Download DG Reference " + isUpdate); - String key = ""; - QueryStatus status = null; - - if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + " set DOWNLOAD_CONFIG_DG = $" - + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where PROTOCOL = $" - + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; - else - key = "insert into " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + " set DOWNLOAD_CONFIG_DG = $" - + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " , PROTOCOL = $" - + SdcArtifactHandlerConstants.DEVICE_PROTOCOL; - - if (serviceLogic != null && context != null) - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if ((status == null) || status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing DOWNLOAD_DG_REFERENCE table "); - } - - public void processConfigActionDg(SvcLogicContext context, boolean isUpdate) throws SvcLogicException { - String fn = "DBService.processConfigActionDg"; - log.info(fn + "Starting DB operation for Config DG Action " + isUpdate); - String key = ""; - QueryStatus status = null; - - if (context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE) != null - && context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE).length() > 0) { - if (isUpdate) - key = "update " + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG + " set DOWNLOAD_CONFIG_DG = $" - + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where ACTION = $" - + SdcArtifactHandlerConstants.ACTION + " and VNF_TYPE = $" - + SdcArtifactHandlerConstants.VNF_TYPE; - else - key = "insert into " + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG + " set DOWNLOAD_CONFIG_DG = $" - + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " , ACTION = $" - + SdcArtifactHandlerConstants.ACTION + " , VNF_TYPE = $" + SdcArtifactHandlerConstants.VNF_TYPE; - - if (serviceLogic != null && context != null) - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if ((status == null) || status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing Configure DG Action table "); - } else - log.info("No Update required for Config DG Action"); - - } - - public String getModelDataInformationbyArtifactName(String artifact_name) throws SvcLogicException { - String fn = "DBService.getVnfData"; - String key = ""; - SvcLogicContext con = new SvcLogicContext(); - HashMap modelData = new HashMap(); - QueryStatus status = null; - key = "select VNF_TYPE, VNFC_TYPE, ACTION, FILE_CATEGORY, ARTIFACT_TYPE from ASDC_REFERENCE where ARTIFACT_NAME = " - + artifact_name; - - if (serviceLogic != null && con != null) { - log.info(fn + "select Key: " + key); - status = serviceLogic.query("SQL", false, null, key, null, null, con); - if (status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing is ArtifactUpdateRequiredforPD table "); - - } - - log.info(fn + "Vnf_received :" + con.getAttribute("VNF_TYPE")); - - return con.getAttribute("VNF_TYPE"); - - } - - public void updateYangContents(SvcLogicContext context, String artifactId, String yangContents) - throws SvcLogicException { - String fn = "DBService.updateYangContents"; - log.info(fn + "Starting DB operation for updateYangContents"); - String key = ""; - QueryStatus status = null; - - key = "update ASDC_ARTIFACTS " + " set ARTIFACT_CONTENT = '" + yangContents + "'" - + " where ASDC_ARTIFACTS_ID = " + artifactId; - - if (serviceLogic != null && context != null) - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if ((status == null) || status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing Configure DG Action table "); - - } - - - public void insertProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action, - String action_level, String template) throws SvcLogicException { - String fn = "DBService.insertProtocolReference"; - log.info(fn + "Starting DB operation for insertProtocolReference"); - String key = ""; - QueryStatus status = null; - - key = "insert into PROTOCOL_REFERENCE (ACTION, VNF_TYPE, PROTOCOL, UPDATED_DATE, TEMPLATE, ACTION_LEVEL)" - + " values (" + "'" + action + "', '" + vnfType + "', '" + protocol + "', now(),'" + template + "', '" - + action_level + "')"; - - if (serviceLogic != null && context != null) - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if ((status == null) || status.toString().equals("FAILURE")) - throw new SvcLogicException("Error While processing insertProtocolReference "); - - } - - public boolean isProtocolReferenceUpdateRequired(SvcLogicContext context, String vnfType, String protocol, - String action, String action_level, String template) throws SvcLogicException { - SvcLogicContext localContext = new SvcLogicContext(); - String fn = "DBService.isProtocolReferenceUpdateRequired"; - log.info(fn + "Starting DB operation for isProtocolReferenceUpdateRequired"); - String key = ""; - QueryStatus status = null; - - key = "select COUNT(*) from PROTOCOL_REFERENCE where ACTION='" + action + "' and ACTION_LEVEL='" + action_level - + "' and VNF_TYPE='" + vnfType + "'"; - status = serviceLogic.query("SQL", false, null, key, null, null, localContext); - String countStr = localContext.getAttribute("COUNT(*)"); - int count = Integer.parseInt(countStr); - if (count > 0) - return true; - else - return false; - } - - public void updateProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action, - String action_level, String template) throws SvcLogicException { - - String fn = "DBService.isProtocolReferenceUpdateRequired"; - log.info(fn + "Starting DB operation for isProtocolReferenceUpdateRequired"); - String key = ""; - QueryStatus status = null; - - key = "update PROTOCOL_REFERENCE set UPDATED_DATE=now(), template='" + template + "' where ACTION='" + action - + "' and ACTION_LEVEL='" + action_level + "' and VNF_TYPE='" + vnfType + "'"; - status = serviceLogic.save("SQL", false, false, key, null, null, context); - if (status == QueryStatus.FAILURE) { - log.info("updateProtocolReference:: Error updating protocol reference"); - throw new SvcLogicException("Error - updating PROTOCOL_REFERENCE_TABLE in updateProtocolReference"); - } - return; - } - - public String getDownLoadDGReference(SvcLogicContext context) throws Exception { - String fn = "DBService.setDownLoadDGReference"; - String downloadConfigDg = null; - log.info(fn + "Setting Download DG Reference from DB"); - String key = ""; - QueryStatus status = null; - String protocol = context.getAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL); - if (StringUtils.isBlank(protocol)) { - log.info(fn + " :: Protocol is Blank!! Returning without querying DB"); - throw new Exception(fn+":: Protocol is Blank!! Returning without querying DB"); - } - key = "select download_config_dg from " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE - + " where protocol = '" + protocol + "'"; - SvcLogicContext localContext = new SvcLogicContext(); - status = serviceLogic.query("SQL", false, null, key, null, null, localContext); - if (status == QueryStatus.FAILURE) { - log.info(fn + ":: Error retrieving download_config_dg"); - throw new SvcLogicException("Error retrieving download_config_dg"); - } - if (status == QueryStatus.NOT_FOUND) { - log.info(fn + ":: NOT_FOUND! No data found for download_config_dg!!"); - throw new Exception(fn + ":: NOT_FOUND! No data found for download_config_dg!"); - } - downloadConfigDg = localContext.getAttribute("download-config-dg"); - log.info(fn + "download_config_dg::" + downloadConfigDg); - return downloadConfigDg; - } - - public void cleanUpVnfcReferencesForVnf(SvcLogicContext context) throws SvcLogicException { - String key1 = "delete from " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE - + " where action = 'Configure' and vnf_type = $" + SdcArtifactHandlerConstants.VNF_TYPE; - QueryStatus status = null; - log.info("cleanUpVnfcReferencesForVnf()::Query:" + key1); - if (serviceLogic != null && context != null) { - status = serviceLogic.save("SQL", false, false, key1, null, null, context); - if (status.toString().equals("FAILURE")) { - log.debug("Error deleting from VNFC_REFERENCE table"); - throw new SvcLogicException("Error While processing VNFC_REFERENCE table "); - } - } - } - - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNode.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNode.java deleted file mode 100644 index f56581977..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNode.java +++ /dev/null @@ -1,533 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.node; - -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.appc.artifact.handler.dbservices.DBService; -import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; -import org.onap.appc.yang.YANGGenerator; -import org.onap.appc.yang.impl.YANGGeneratorFactory; -import org.openecomp.sdnc.config.params.transformer.tosca.ArtifactProcessorImpl; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - - -public class ArtifactHandlerNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerNode.class); - - public void processArtifact(Map inParams, SvcLogicContext ctx) throws Exception { - String responsePrefix = inParams.get("response_prefix"); - try { - if (inParams != null && !inParams.isEmpty() && inParams.get("postData") != null) { - log.info("Received request for process Artifact with params: " + inParams.toString()); - String postData = inParams.get("postData"); - JSONObject input = new JSONObject(postData).getJSONObject("input"); - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : ""; - storeUpdateSdcArtifacts(input); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private boolean storeUpdateSdcArtifacts(JSONObject postDataJson) throws Exception { - log.info("Starting processing of SDC Artifacs into Handler with Data : " + postDataJson.toString()); - try { - JSONObject request_information = - (JSONObject) postDataJson.get(SdcArtifactHandlerConstants.REQUEST_INFORMATION); - JSONObject document_information = - (JSONObject) postDataJson.get(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS); - String artifact_name = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME); - if (artifact_name != null) { - updateStoreArtifacts(request_information, document_information); - if (artifact_name.toLowerCase().startsWith(SdcArtifactHandlerConstants.REFERENCE)) - return storeReferenceData(request_information, document_information); - else if (artifact_name.toLowerCase().startsWith(SdcArtifactHandlerConstants.PD)) - return createDataForPD(request_information, document_information); - - } else - throw new Exception("Missing Artifact Name for Request : " - + request_information.getString(SdcArtifactHandlerConstants.REQUETS_ID)); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Error while processing Request ID : " - + ((JSONObject) postDataJson.get(SdcArtifactHandlerConstants.REQUEST_INFORMATION)) - .getString(SdcArtifactHandlerConstants.REQUETS_ID) - + e.getMessage()); - } - return false; - - } - - private boolean createDataForPD(JSONObject request_information, JSONObject document_information) throws Exception { - - String fn = "ArtifactHandlerNode.createReferenceDataForPD"; - String artifact_name = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME); - log.info(fn + "Received PD File Name: " + artifact_name + " and suffix lenght " - + SdcArtifactHandlerConstants.PD.length()); - try { - - String suffix = artifact_name.substring(SdcArtifactHandlerConstants.PD.length()); - createArtifactRecords(request_information, document_information, suffix); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Error while createing PD data records " + e.getMessage()); - } - return true; - } - - private void createArtifactRecords(JSONObject request_information, JSONObject document_information, String suffix) - throws Exception { - - log.info("Creating Tosca Records and storing into SDC Artifacs"); - String[] docs = {"Tosca", "Yang"}; - ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); - String PDFileContents = document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS); - - // Tosca generation - OutputStream toscaStream = new ByteArrayOutputStream(); - String toscaContents = null; - ArtifactProcessorImpl toscaGenerator = new ArtifactProcessorImpl(); - toscaGenerator.generateArtifact(PDFileContents, toscaStream); - if (toscaStream != null) - toscaContents = toscaStream.toString(); - log.info("Generated Tosca File : " + toscaContents); - - String yangContents = "YANG generation is in Progress"; - String yangName = null; - - for (String doc : docs) { - document_information.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, doc.concat("Type")); - document_information.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, doc.concat("Model")); - if (doc.equals("Tosca")) - document_information.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, - ahpUtil.escapeSql(toscaContents)); - else if (doc.equals("Yang")) - document_information.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, - ahpUtil.escapeSql(yangContents)); - document_information.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, doc.concat(suffix)); - yangName = doc.concat(suffix); - updateStoreArtifacts(request_information, document_information); - } - - String artifactId = getArtifactID(yangName); - OutputStream yangStream = new ByteArrayOutputStream(); - YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator(); - yangGenerator.generateYANG(artifactId, toscaContents, yangStream); - if (yangStream != null) - yangContents = yangStream.toString(); - - if (yangContents != null) { - updateYangContents(artifactId, ahpUtil.escapeSql(yangContents)); - } - - } - - private void updateYangContents(String artifactId, String yangContents) throws SvcLogicException { - SvcLogicContext context = new SvcLogicContext(); - DBService dbservice = DBService.initialise(); - dbservice.updateYangContents(context, artifactId, yangContents); - } - - private String getArtifactID(String yangName) throws SvcLogicException { - SvcLogicContext context = new SvcLogicContext(); - DBService dbservice = DBService.initialise(); - return dbservice.getArtifactID(context, yangName); - } - - protected boolean updateStoreArtifacts(JSONObject request_information, JSONObject document_information) - throws Exception { - log.info("UpdateStoreArtifactsStarted storing of SDC Artifacs "); - - SvcLogicContext context = new SvcLogicContext(); - DBService dbservice = DBService.initialise(); - ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); - int intversion = 0; - context.setAttribute("artifact_name", - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - String internal_version = dbservice.getInternalVersionNumber(context, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); - log.info("Internal Version number received from Database : " + internal_version); - if (internal_version != null) { - intversion = Integer.parseInt(internal_version); - intversion++; - } - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_UUID, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.DISTRIBUTION_ID, - document_information.getString(SdcArtifactHandlerConstants.DISTRIBUTION_ID)); - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_NAME, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_NAME)); - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_UUID, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_VERSOIN)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_TYPE, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_TYPE)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_UUID, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, - ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS))); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - dbservice.saveArtifacts(context, intversion); - return true; - - } - - public boolean storeReferenceData(JSONObject request_information, JSONObject document_information) - throws Exception { - log.info("Started storing of SDC Artifacs into Handler"); - try { - boolean updateRequired = false; - boolean pdFile = false; - String suffix = null; - String categorySuffix = null; - DBService dbservice = DBService.initialise(); - ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil(); - String contentString = - ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS)); - String artifactName = - ahpUtil.escapeSql(document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - String capabilityArtifactName = - StringUtils.replace(artifactName, SdcArtifactHandlerConstants.ARTIFACT_NAME_REFERENCE, - SdcArtifactHandlerConstants.ARTIFACT_NAME_CAPABILITY); - JSONObject capabilities = new JSONObject(); - JSONArray vnfActionList = new JSONArray(); - JSONArray vfModuleActionList = new JSONArray(); - JSONArray vnfcActionList = new JSONArray(); - JSONArray vmActionList = new JSONArray(); - String vnfType = null; - JSONObject contentObject = new JSONObject(contentString); - JSONArray contentArray = contentObject.getJSONArray("reference_data"); - boolean storeCapabilityArtifact=true; - for (int a = 0; a < contentArray.length(); a++) { - - JSONObject content = (JSONObject) contentArray.get(a); - log.info("contentString =" + content.toString()); - JSONObject scope = content.getJSONObject("scope"); - log.info("scope :" + scope); - SvcLogicContext context = new SvcLogicContext(); - vnfType = scope.getString(SdcArtifactHandlerConstants.VNF_TYPE); - context.setAttribute(SdcArtifactHandlerConstants.VNF_TYPE, - scope.getString(SdcArtifactHandlerConstants.VNF_TYPE)); - context.setAttribute(SdcArtifactHandlerConstants.ACTION, - content.getString(SdcArtifactHandlerConstants.ACTION)); - String actionLevel = content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL); - context.setAttribute(SdcArtifactHandlerConstants.ACTION_LEVEL, - content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL)); - if ((null != actionLevel) - && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VNFC)) { - vnfcActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); - } - if (null != actionLevel - && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VF_MODULE)) { - vfModuleActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); - } - if (null != actionLevel && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VNF)) { - vnfActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); - } - if (null != actionLevel && actionLevel.equalsIgnoreCase(SdcArtifactHandlerConstants.ACTION_LEVEL_VM)) { - vmActionList.put(content.getString(SdcArtifactHandlerConstants.ACTION)); - } - if (scope.has(SdcArtifactHandlerConstants.VNFC_TYPE) - && !scope.isNull(SdcArtifactHandlerConstants.VNFC_TYPE)) { - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, - scope.getString(SdcArtifactHandlerConstants.VNFC_TYPE)); - String vnfcTypeScope = scope.getString(SdcArtifactHandlerConstants.VNFC_TYPE); - if (StringUtils.isNotBlank(vnfcTypeScope)) { - storeCapabilityArtifact = false; - log.info("No capability Artifact for this reference data as it is at VNFC level!!"); - } - } - else - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); - if (content.has(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)) - context.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL, - content.getString(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)); - if (content.has(SdcArtifactHandlerConstants.USER_NAME)) - context.setAttribute(SdcArtifactHandlerConstants.USER_NAME, - content.getString(SdcArtifactHandlerConstants.USER_NAME)); - if (content.has(SdcArtifactHandlerConstants.PORT_NUMBER)) - context.setAttribute(SdcArtifactHandlerConstants.PORT_NUMBER, - content.getString(SdcArtifactHandlerConstants.PORT_NUMBER)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, ""); - if (content.has("artifact-list") && content.get("artifact-list") instanceof JSONArray) { - JSONArray artifactLists = (JSONArray) content.get("artifact-list"); - for (int i = 0; i < artifactLists.length(); i++) { - JSONObject artifact = (JSONObject) artifactLists.get(i); - log.info("artifact is " + artifact); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, - artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, - artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE)); - - if (artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME) != null - && artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME).toLowerCase() - .startsWith(SdcArtifactHandlerConstants.PD)) { - suffix = artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME) - .substring(SdcArtifactHandlerConstants.PD.length()); - categorySuffix = artifact.getString(SdcArtifactHandlerConstants.ARTIFACT_TYPE) - .substring(SdcArtifactHandlerConstants.PD.length()); - pdFile = true; - } - - dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); - - cleanArtifactInstanceData(context); - } - - if (pdFile) { - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, "Tosca".concat(suffix)); - context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, - SdcArtifactHandlerConstants.TOSCA_MODEL); - dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, "Yang".concat(suffix)); - context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, - SdcArtifactHandlerConstants.PARAMETER_YANG); - dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); - } - } - if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure") - || content.getString(SdcArtifactHandlerConstants.ACTION).equals("ConfigModify")) { - if (content.has(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE) - && content.getString(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE).length() > 0) { - context.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, - content.getString(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE)); - dbservice.processDownloadDgReference(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE)); - } - if (StringUtils.isBlank(context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE))) - context.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, - dbservice.getDownLoadDGReference(context)); - dbservice.processConfigActionDg(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG)); - if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure")) { - dbservice.processDeviceInterfaceProtocol(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL)); - dbservice.processDeviceAuthentication(context, dbservice.isArtifactUpdateRequired(context, - SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION)); - } - - } - - - populateProtocolReference(dbservice, content); - - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); - - if (content.has(SdcArtifactHandlerConstants.VM) - && content.get(SdcArtifactHandlerConstants.VM) instanceof JSONArray) { - JSONArray vmList = (JSONArray) content.get(SdcArtifactHandlerConstants.VM); - dbservice.cleanUpVnfcReferencesForVnf(context); - for (int i = 0; i < vmList.length(); i++) { - JSONObject vmInstance = (JSONObject) vmList.get(i); - context.setAttribute(SdcArtifactHandlerConstants.VM_INSTANCE, - String.valueOf(vmInstance.getInt(SdcArtifactHandlerConstants.VM_INSTANCE))); - log.info("VALUE = " + context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE)); - if (vmInstance.get(SdcArtifactHandlerConstants.VNFC) instanceof JSONArray) { - JSONArray vnfcInstanceList = (JSONArray) vmInstance.get(SdcArtifactHandlerConstants.VNFC); - for (int k = 0; k < vnfcInstanceList.length(); k++) { - JSONObject vnfcInstance = (JSONObject) vnfcInstanceList.get(k); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE, - String.valueOf(vnfcInstance.getInt(SdcArtifactHandlerConstants.VNFC_INSTANCE))); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, - vnfcInstance.getString(SdcArtifactHandlerConstants.VNFC_TYPE)); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE, - vnfcInstance.getString(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE)); - if (vnfcInstance.has(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP)) - context.setAttribute(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP, - vnfcInstance.getString(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP)); - if (vnfcInstance.has(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE)) - context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE, - vnfcInstance.getString(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE)); - if (vnfcInstance.has(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE)) - context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE, - vnfcInstance.getString(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE)); - if (content.getString(SdcArtifactHandlerConstants.ACTION).equals("Configure")) { - dbservice.processVnfcReference(context,false); - } - cleanVnfcInstance(context); - } - context.setAttribute(SdcArtifactHandlerConstants.VM_INSTANCE, null); - } - } - } - - - } - if (storeCapabilityArtifact) { - capabilities.put("vnf", vnfActionList); - capabilities.put("vf-module", vfModuleActionList); - capabilities.put("vnfc", vnfcActionList); - capabilities.put("vm", vmActionList); - processAndStoreCapablitiesArtifact(dbservice, document_information, capabilities, capabilityArtifactName, - vnfType); - } - - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Error While Storing : " + e.getMessage()); - } - - return true; - } - - private void cleanArtifactInstanceData(SvcLogicContext context) { - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, null); - context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, null); - } - - private void cleanVnfcInstance(SvcLogicContext context) { - - context.setAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE, null); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE, null); - context.setAttribute(SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP, null); - context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE, null); - context.setAttribute(SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE, null); - - } - - private void processAndStoreCapablitiesArtifact(DBService dbservice, JSONObject document_information, - JSONObject capabilities, String capabilityArtifactName, String vnfType) throws Exception { - log.info("Begin-->processAndStoreCapablitiesArtifact "); - - try { - - JSONObject newCapabilitiesObject = new JSONObject(); - newCapabilitiesObject.put("capabilities", capabilities); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME, capabilityArtifactName); - context.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, SdcArtifactHandlerConstants.CAPABILITY); - context.setAttribute(SdcArtifactHandlerConstants.ACTION, null); - context.setAttribute(SdcArtifactHandlerConstants.VNFC_TYPE, null); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_TYPE, null); - context.setAttribute(SdcArtifactHandlerConstants.VNF_TYPE, vnfType); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, newCapabilitiesObject.toString()); - dbservice.processSdcReferences(context, - dbservice.isArtifactUpdateRequired(context, SdcArtifactHandlerConstants.DB_SDC_REFERENCE)); - int intversion = 0; - - String internal_version = dbservice.getInternalVersionNumber(context, - context.getAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); - log.info("Internal Version number received from Database : " + internal_version); - if (internal_version != null) { - intversion = Integer.parseInt(internal_version); - intversion++; - } - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_UUID, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.DISTRIBUTION_ID, - document_information.getString(SdcArtifactHandlerConstants.DISTRIBUTION_ID)); - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_NAME, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_NAME)); - context.setAttribute(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, - document_information.getString(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_UUID, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_VERSOIN)); - context.setAttribute(SdcArtifactHandlerConstants.RESOURCE_TYPE, - document_information.getString(SdcArtifactHandlerConstants.RESOURCE_TYPE)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_UUID, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_UUID)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN)); - context.setAttribute(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION)); - - - dbservice.saveArtifacts(context, intversion); - return; - } catch (Exception e) { - log.error("Error saving capabilities artifact to DB: " + e.toString()); - throw e; - } finally { - log.info("End-->processAndStoreCapablitiesArtifact "); - } - - } - - private void populateProtocolReference(DBService dbservice, JSONObject content) throws Exception { - log.info("Begin-->populateProtocolReference "); - try { - SvcLogicContext context = new SvcLogicContext(); - JSONObject scope = content.getJSONObject("scope"); - String vnfType = null, protocol = null, action = null, actionLevel = null, template = null; - if (scope.has(SdcArtifactHandlerConstants.VNF_TYPE) && !scope.isNull(SdcArtifactHandlerConstants.VNF_TYPE)) - vnfType = scope.getString(SdcArtifactHandlerConstants.VNF_TYPE); - if (content.has(SdcArtifactHandlerConstants.DEVICE_PROTOCOL)) - protocol = content.getString(SdcArtifactHandlerConstants.DEVICE_PROTOCOL); - if (content.has(SdcArtifactHandlerConstants.ACTION)) - action = content.getString(SdcArtifactHandlerConstants.ACTION); - if (content.has(SdcArtifactHandlerConstants.ACTION_LEVEL)) - actionLevel = content.getString(SdcArtifactHandlerConstants.ACTION_LEVEL); - if (content.has(SdcArtifactHandlerConstants.TEMPLATE) - && !content.isNull(SdcArtifactHandlerConstants.TEMPLATE)) - template = content.getString(SdcArtifactHandlerConstants.TEMPLATE); - boolean isUpdateNeeded=dbservice.isProtocolReferenceUpdateRequired(context, vnfType, protocol, action, actionLevel, template); - if (isUpdateNeeded) - dbservice.updateProtocolReference(context, vnfType, protocol, action, actionLevel, template); - else - dbservice.insertProtocolReference(context, vnfType,protocol,action,actionLevel,template); - } catch (Exception e) { - log.error("Error inserting record into protocolReference: " + e.toString()); - throw e; - } finally { - log.info("End-->populateProtocolReference "); - } - } - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java deleted file mode 100644 index 15859178a..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtil.java +++ /dev/null @@ -1,191 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.utils; - -import java.io.IOException; -import java.security.SecureRandom; -import java.util.HashMap; - -import org.apache.commons.lang3.StringUtils; -import org.json.JSONException; -import org.json.JSONObject; -import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInput; -import org.onap.appc.artifact.handler.node.ArtifactHandlerNode; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ArtifactHandlerProviderUtil { - - public UploadartifactInput templateData ; - SvcLogicContext context = null; - private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerProviderUtil.class); - public static void loadProperties() { - // TODO Auto-generated method stub - - } - public enum DistributionStatusEnum { - DOWNLOAD_OK, - DOWNLOAD_ERROR, - ALREADY_DOWNLOADED, - DEPLOY_OK, - DEPLOY_ERROR, - ALREADY_DEPLOYED; - } - - public ArtifactHandlerProviderUtil(){}; - - public ArtifactHandlerProviderUtil(UploadartifactInput input) { - this.templateData = input; - log.info("templateData " + this.templateData); - } - - public void processTemplate(String requestInfo) throws Exception { - if(context == null) - context = new SvcLogicContext(); - - ArtifactHandlerNode node = new ArtifactHandlerNode(); - try { - - HashMap processdata = new HashMap(); - processdata.put("postData", requestInfo); - log.info("Post data = " + requestInfo); - node.processArtifact(processdata, context); - } catch (Exception e) { - // TODO Auto-generated catch block - log.error("Error: " + e.getMessage()); - e.printStackTrace(); - throw e; - } - - } - public String createDummyRequestData() throws JSONException, IOException{ - - - JSONObject info = new JSONObject(this.templateData); - log.info("INFO = " + info); - String artifact_name = templateData.getDocumentParameters().getArtifactName(); - String artifact_version = templateData.getDocumentParameters().getArtifactVersion(); - - JSONObject json = new JSONObject(); - JSONObject requestInfo = new JSONObject(); - String random = getRandom(); - - requestInfo.put(SdcArtifactHandlerConstants.REQUETS_ID, "TLRID-" + random); - requestInfo.put(SdcArtifactHandlerConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); - requestInfo.put(SdcArtifactHandlerConstants.SOURCE, "TemplateLoader"); - - JSONObject docParams = new JSONObject(); - docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID, "TLSUUID" + templateData.getRequestInformation().getRequestId()); - docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "TLDID" + random); - docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, "TLServiceName"); - docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "Template Loader Test"); - docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS, "[]"); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "TLRUID" + random); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "TLRIName"); - docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, "TLResourceName"); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, "TLResourceVersion"); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "TLResourceType"); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "TLAUUID" + random); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, "APPC-CONFIG"); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, templateData.getDocumentParameters().getArtifactVersion()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "SdcTestDescription"); - // String data = IOUtils.toString(TestartifactHandlerNode.class.getClassLoader().getResourceAsStream("template_msrp_msc_a_template.json"), "utf-8"); - // String data = IOUtils.toString(TemplateProcessor.class.getClassLoader().getResourceAsStream("referenceData.json"), "utf-8"); - - // this.templateData = this.templateData.substring(this.templateData.indexOf("}") + 1); - docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents()); - - json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); - json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams); - System.out.println("Final data =" + this.templateData); - return String.format("{\"input\": %s}", json.toString()); - } - - private String getRandom() { - SecureRandom random = new SecureRandom(); - int num = random.nextInt(100000); - String formatted = String.format("%05d", num); - return formatted; - } - - public String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\"}; - String replacementList[] = new String[]{ "''","\\\\"}; - return StringUtils.replaceEach(str,searchList, replacementList); - } - public String createRequestData() throws JSONException, IOException{ - - - JSONObject info = new JSONObject(this.templateData); - log.info("INFO = " + info); - - JSONObject json = new JSONObject(); - JSONObject requestInfo = new JSONObject(); - String random = getRandom(); - - requestInfo.put(SdcArtifactHandlerConstants.REQUETS_ID, templateData.getRequestInformation().getRequestId()); - requestInfo.put(SdcArtifactHandlerConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); - requestInfo.put(SdcArtifactHandlerConstants.SOURCE, templateData.getRequestInformation().getSource()); - - String serviceDescription = serviceDescriptionData(templateData.getDocumentParameters().getServiceDescription()); - - JSONObject docParams = new JSONObject(); - docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID, templateData.getDocumentParameters().getResourceUuid()); - docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, templateData.getDocumentParameters().getDistributionId()); - docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, templateData.getDocumentParameters().getServiceName()); - docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION,serviceDescription); - docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS, templateData.getDocumentParameters().getServiceArtifacts()); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_UUID, templateData.getDocumentParameters().getResourceUuid()); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, templateData.getDocumentParameters().getResourceInstanceName()); - docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, templateData.getDocumentParameters().getResourceName()); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, templateData.getDocumentParameters().getResourceVersion()); - docParams.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, templateData.getDocumentParameters().getResourceType()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, templateData.getDocumentParameters().getArtifactUuid()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, templateData.getDocumentParameters().getArtifactType()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, templateData.getDocumentParameters().getArtifactVersion()); - docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, templateData.getDocumentParameters().getArtifactDescription()); - - docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents()); - - json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); - json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams); - System.out.println("Final data =" + this.templateData); - return String.format("{\"input\": %s}", json.toString()); - } - - private String serviceDescriptionData(String serviceDescription){ - if(!StringUtils.isBlank(serviceDescription)&&serviceDescription.length()>255){ - serviceDescription = serviceDescription.substring(0, 255); - } - return serviceDescription; - } -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/EscapeUtils.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/EscapeUtils.java deleted file mode 100644 index ece5cdb24..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/EscapeUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.utils; - -import org.apache.commons.lang3.StringUtils; - -public class EscapeUtils { - - public EscapeUtils() { - // TODO Auto-generated constructor stub - } - - public static String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\"}; - String replacementList[] = new String[]{ "''","\\\\"}; - return StringUtils.replaceEach(str,searchList, replacementList); - } -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java b/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java deleted file mode 100644 index c045ee7d4..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/main/java/org/openecomp/appc/artifact/handler/utils/SdcArtifactHandlerConstants.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.utils; - -public class SdcArtifactHandlerConstants { - - public static final String DOCUMENT_PARAMETERS = "document-parameters"; - public static final String SERVICE_UUID = "service-uuid"; - public static final String DISTRIBUTION_ID = "distribution-id"; - public static final String REQUETS_ID = "request-id"; - public static final String REQUEST_ACTION = "request-action"; - public static final String SOURCE = "source"; - public static final String SERVICE_NAME = "service-name"; - public static final String SERVICE_DESCRIPTION ="service-description"; - public static final String SERVICE_ARTIFACTS = "service-artifacts"; - public static final String RESOURCE_UUID ="resource-uuid"; - public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name"; - public static final String REOURCE_NAME = "resource-name"; - public static final String RESOURCE_VERSOIN ="resource-version"; - public static final String RESOURCE_TYPE= "resource-type"; - public static final String ARTIFACT_UUID ="artifact-uuid"; - public static final String ARTIFACT_NAME = "artifact-name"; - public static final String ARTIFACT_TYPE = "artifact-type"; - public static final String ARTIFACT_VERSOIN = "artifact-version"; - public static final String ARTIFACT_DESRIPTION = "artifact-description"; - public static final String ARTIFACT_CONTENTS = "artifact-contents"; - public static final String REQUEST_INFORMATION = "request-information"; - public static final String INTERNAL_VERSION = "internal-versoin"; - public static final String FILE_CATEGORY = "file-category"; - public static final String VNF_TYPE = "vnf-type"; - public static final String ACTION = "action"; - public static final String ACTION_LEVEL = "action-level"; - public static final String VNFC_TYPE = "vnfc-type"; - public static final String VM_INSTANCE = "vm-instance"; - public static final String VM = "vm"; - public static final String VNFC = "vnfc"; - public static final String VNFC_FUNCTION_CODE = "vnfc-function-code"; - public static final String GROUP_NOTATION = "group-notation"; - public static final String IPADDRESS_V4_OAM_VIP = "ipaddress-v4-oam-vip"; - public static final String GROUP_NOTATION_TYPE = "group-notation-type"; - public static final String GROUP_NOTATION_VALUE = "group-notation-value"; - public static final String REFERENCE = "reference"; - public static final String VNFC_INSTANCE = "vnfc-instance"; - public static final String DEVICE_PROTOCOL = "device-protocol"; - public static final String DG_RPC = "dg-rpc"; - public static final String MODULE = "module"; - public static final String USER_NAME = "user-name"; - public static final String PORT_NUMBER = "port-number"; - public static final String DOWNLOAD_DG_REFERENCE = "download-dg-reference"; - - - public static final String DB_DOWNLOAD_DG_REFERENCE = "DOWNLOAD_DG_REFERENCE"; - public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; - public static final String DB_DEVICE_INTERFACE_PROTOCOL = "DEVICE_INTERFACE_PROTOCOL"; - public static final String DB_DEVICE_AUTHENTICATION = "DEVICE_AUTHENTICATION"; - public static final String DB_VNFC_REFERENCE = "VNFC_REFERENCE"; - public static final String DB_CONFIG_ACTION_DG = "CONFIGURE_ACTION_DG"; - public static final String PD = "pd"; - public static final String PARAMETER_YANG = "parameter_yang"; - public static final String TOSCA_MODEL = "tosca_model"; - public static final String DESIGN_TOOL = "Design-tool"; - public static final String ACTION_LEVEL_VNFC = "VNFC"; - public static final String ACTION_LEVEL_VF_MODULE ="VF-MODULE"; - public static final String ACTION_LEVEL_VNF = "VNF"; - public static final String ACTION_LEVEL_VM = "VM"; - public static final String CAPABILITY = "capability"; - public static final String TEMPLATE = "template"; - public static final String ARTIFACT_NAME_REFERENCE = "reference"; - public static final String ARTIFACT_NAME_CAPABILITY = "capability"; -} - diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/DBServiceTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/DBServiceTest.java new file mode 100644 index 000000000..d5e86a0fc --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/DBServiceTest.java @@ -0,0 +1,298 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.dbservices; + +import java.nio.charset.Charset; +import org.json.JSONObject; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.powermock.reflect.Whitebox; +import static org.junit.Assert.assertEquals; + +public class DBServiceTest { + + @Test + public void testSaveArtifacts() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + int internalVersion = 1; + dbService.saveArtifacts(ctx, internalVersion); + } + + @Test + public void testSaveArtifactsException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + int internalVersion = 1; + dbService.saveArtifacts(ctx, internalVersion); + } + + @Test + public void testLogData() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String prefix = "test"; + dbService.logData(ctx, prefix); + } + + + @Test + public void testLogDataException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String prefix = "test"; + dbService.logData(ctx, prefix); + } + + @Test + public void testProcessConfigActionDg() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + ctx.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, "Reference"); + dbService.processConfigActionDg(ctx, isUpdate); + } + + @Test + public void testProcessConfigActionDgException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + ctx.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, "Reference"); + dbService.processConfigActionDg(ctx, isUpdate); + } + + @Test + public void testGetModelDataInformationbyArtifactName() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String artifactName = "test"; + dbService.getModelDataInformationbyArtifactName(artifactName); + } + + @Test + public void testGetModelDataInformationbyArtifactNameException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String artifactName = "test"; + dbService.getModelDataInformationbyArtifactName(artifactName); + } + + @Test + public void testUpdateYangContents() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String artifactName = "test"; + String artifactId = "TestArtifact"; + String yangContents = "TestYangContents"; + dbService.updateYangContents(ctx, artifactId, yangContents); + } + + @Test + public void testUpdateYangContentsException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String artifactName = "test"; + String artifactId = "TestArtifact"; + String yangContents = "TestYangContents"; + dbService.updateYangContents(ctx, artifactId, yangContents); + } + + @Test + public void testInsertProtocolReference() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String vnfType = "testVnf"; + String protocol = "testProtocol"; + String action = "testAction"; + String actionLevel = "testActionLevel"; + String template = "testTemplateData"; + dbService.insertProtocolReference(ctx, vnfType, protocol, action, actionLevel, template); + } + + + @Test + public void testInsertProtocolReferenceException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String vnfType = "testVnf"; + String protocol = "testProtocol"; + String action = "testAction"; + String actionLevel = "testActionLevel"; + String template = "testTemplateData"; + dbService.insertProtocolReference(ctx, vnfType, protocol, action, actionLevel, template); + } + + @Test + public void testprocessDpwnloadDGReference() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDownloadDgReference(ctx, isUpdate); + } + + @Test + public void testprocessDpwnloadDGReferenceException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDownloadDgReference(ctx, isUpdate); + } + + @Test + public void testProcessVnfcReference() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processVnfcReference(ctx, isUpdate); + } + + @Test + public void testProcessVnfcReferenceException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processVnfcReference(ctx, isUpdate); + } + + @Test + public void testProcessDeviceAuthentication() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDeviceAuthentication(ctx, isUpdate); + } + + @Test + public void testProcessDeviceAuthenticationException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDeviceAuthentication(ctx, isUpdate); + } + + @Test + public void testProcessDeviceInterfaceProtocol() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDeviceInterfaceProtocol(ctx, isUpdate); + } + + @Test + public void testProcessDeviceInterfaceProtocolException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processDeviceInterfaceProtocol(ctx, isUpdate); + } + + @Test + public void testProcessSdcReferences() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ctx.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, "testCategory"); + boolean isUpdate = true; + dbService.processSdcReferences(ctx, isUpdate); + } + + @Ignore + public void testProcessSdcReferencesException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + boolean isUpdate = true; + dbService.processSdcReferences(ctx, isUpdate); + } + + @Test + public void testIsArtifactUpdateRequired() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String db = "db"; + dbService.isArtifactUpdateRequired(ctx, db); + } + + @Test + public void testIsArtifactUpdateRequiredExcetion() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String db = "db"; + dbService.isArtifactUpdateRequired(ctx, db); + } + + + @Test + public void testgetArtifactID() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String db = "db"; + dbService.getArtifactID(ctx, db); + } + + @Test + public void testgetArtifactIDException() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + String db = "db"; + dbService.getArtifactID(ctx, db); + } + @Test + public void testGetDownLoadDGReference() throws Exception { + MockDBService dbService = MockDBService.initialise(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + ctx.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL, "CLI"); + assertEquals("TestDG", dbService.getDownLoadDGReference(ctx)); + } +} + diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockDBService.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockDBService.java new file mode 100644 index 000000000..caec09172 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockDBService.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.dbservices; + +public class MockDBService extends DBService { + private static MockDBService mockDgGeneralDBService = null; + private static MockSvcLogicResource serviceLogic = new MockSvcLogicResource();; + + public MockDBService() { + super(serviceLogic); + if (mockDgGeneralDBService != null) { + mockDgGeneralDBService = new MockDBService(serviceLogic); + } + + } + + public MockDBService(MockSvcLogicResource serviceLogic2) { + super(serviceLogic); + } + + public static MockDBService initialise() { + if (mockDgGeneralDBService == null) { + mockDgGeneralDBService = new MockDBService(serviceLogic); + } + return mockDgGeneralDBService; + } + +} + diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockSvcLogicResource.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockSvcLogicResource.java new file mode 100644 index 000000000..c931ab0f4 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/dbservices/MockSvcLogicResource.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.dbservices; + +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; + +public class MockSvcLogicResource extends SqlResource { + + @Override + public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, + String orderBy, SvcLogicContext ctx) throws SvcLogicException { + QueryStatus status = QueryStatus.SUCCESS; + ctx.setAttribute("id", "testId"); + ctx.setAttribute("VNF_TYPE", "testvnf"); + ctx.setAttribute("maximum", "1"); + ctx.setAttribute("COUNT(*)", "1"); + ctx.setAttribute("download-config-dg", "TestDG"); + return status; + } + + + @Override + public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, + String prefix, SvcLogicContext ctx) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNodeTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNodeTest.java new file mode 100644 index 000000000..42d436e98 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/ArtifactHandlerNodeTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.node; + +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.Enumeration; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.powermock.reflect.Whitebox; +import static org.junit.Assert.assertTrue; +import org.onap.appc.artifact.handler.dbservices.DBService; +import org.onap.appc.artifact.handler.dbservices.MockDBService; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; +import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtilTest; + +import java.util.Map; +import java.util.HashMap; + +public class ArtifactHandlerNodeTest { + + @Test + public void testProcessArtifact() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("test", "test"); + MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); + Map inParams = new HashMap(); + JSONObject postData = new JSONObject(); + JSONObject input = new JSONObject(); + inParams.put("response_prefix", "prefix"); + JSONObject requestInfo = new JSONObject(); + JSONObject documentInfo = new JSONObject(); + String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() + .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); + requestInfo.put("RequestInfo", "testValue"); + input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo); + input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); + postData.put("input", input); + inParams.put("postData", postData.toString()); + ah.processArtifact(inParams, ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testStoreReferenceData() throws Exception { + MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); + JSONObject documentInfo = new JSONObject(); + String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() + .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); + JSONObject requestInfo = new JSONObject(); + requestInfo.put("RequestInfo", "testStoreReferenceData"); + ah.storeReferenceData(requestInfo, documentInfo); + } + + @Test + public void testPopulateProtocolReference() throws Exception { + ArtifactHandlerNode ah = new ArtifactHandlerNode(); + String contentStr = + "{\"action\": \"TestAction\",\"action-level\": \"vnf\",\"scope\": {\"vnf-type\": \"vDBE-I\",\"vnfc-type\": null},\"template\": \"N\",\"device-protocol\": \"REST\"}"; + JSONObject content = new JSONObject(contentStr); + MockDBService dbService = MockDBService.initialise(); + Whitebox.invokeMethod(ah, "populateProtocolReference", dbService, content); + } + + @Test + public void testProcessAndStoreCapablitiesArtifact() throws Exception { + ArtifactHandlerNode ah = new ArtifactHandlerNode(); + JSONObject capabilities = new JSONObject(); + JSONObject documentInfo = new JSONObject(); + MockDBService dbService = MockDBService.initialise(); + documentInfo.put(SdcArtifactHandlerConstants.SERVICE_UUID, "testuid"); + documentInfo.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "testDist"); + documentInfo.put(SdcArtifactHandlerConstants.SERVICE_NAME, "testName"); + documentInfo.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "testDesc"); + documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "testRes"); + documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "testResIns"); + documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, "testVers"); + documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "testResType"); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "testArtifactUuid"); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, "testArtifactVers"); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "testArtifactDesc"); + Whitebox.invokeMethod(ah, "processAndStoreCapablitiesArtifact", dbService, documentInfo, capabilities, + "artifactName", "someVnf"); + } + + @Test + public void testCleanVnfcInstance() throws Exception { + ArtifactHandlerNode ah = new ArtifactHandlerNode(); + SvcLogicContext ctx = new SvcLogicContext(); + Whitebox.invokeMethod(ah, "cleanVnfcInstance", ctx); + assertTrue(true); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testGetArtifactIDException() throws Exception { + ArtifactHandlerNode ah = new ArtifactHandlerNode(); + String yFileName = "yFileName"; + Whitebox.invokeMethod(ah, "getArtifactID", yFileName); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testStoreUpdateSdcArtifacts() throws Exception { + ArtifactHandlerNode ah = new ArtifactHandlerNode(); + String postDataStr = + "{\"request-information\":{},\"document-parameters\":{\"artifact-name\":\"testArtifact\",\"artifact-contents\":{\"content\":\"TestContent\"}}}"; + JSONObject postData = new JSONObject(postDataStr); + Whitebox.invokeMethod(ah, "storeUpdateSdcArtifacts", postData); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testUpdateStoreArtifacts() throws Exception { + MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); + JSONObject documentInfo = new JSONObject(); + String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() + .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); + documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); + JSONObject requestInfo = new JSONObject(); + requestInfo.put("RequestInfo", "testupdateStoreArtifacts"); + ah.updateStoreArtifacts(requestInfo, documentInfo); + } + + @Test + public void testCleanArtifactInstanceData() throws Exception { + MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); + SvcLogicContext ctx = new SvcLogicContext(); + Whitebox.invokeMethod(ah, "cleanArtifactInstanceData", ctx); + } + + @Ignore("Test is taking 60 seconds") + @Test(expected = Exception.class) + public void testUpdateYangContents() throws Exception { + MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); + String artifactId = "1"; + String yangContents = "SomeContent"; + Whitebox.invokeMethod(ah, "updateYangContents", artifactId, yangContents); + } + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/MockArtifactHandlerNode.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/MockArtifactHandlerNode.java new file mode 100644 index 000000000..39706a282 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/node/MockArtifactHandlerNode.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.node; + +import org.json.JSONObject; +import org.onap.appc.artifact.handler.dbservices.MockDBService; +import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class MockArtifactHandlerNode extends ArtifactHandlerNode { + + @Override + public boolean updateStoreArtifacts(JSONObject request_information, JSONObject document_information) + throws Exception { + if (request_information != null && request_information.get("RequestInfo").equals("testupdateStoreArtifacts")) { + super.updateStoreArtifacts(request_information, document_information); + } + SvcLogicContext context = new SvcLogicContext(); + MockDBService dbservice = MockDBService.initialise(); + int intversion = 0; + context.setAttribute("artifact_name", + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); + String internal_version = dbservice.getInternalVersionNumber(context, + document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); + if (internal_version != null) { + intversion = Integer.parseInt(internal_version); + intversion++; + } + + return true; + + } + + @Override + public boolean storeReferenceData(JSONObject request_information, JSONObject document_information) + throws Exception { + if (request_information != null && request_information.get("RequestInfo").equals("testStoreReferenceData")) { + super.storeReferenceData(request_information, document_information); + } + return true; + } + +} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java new file mode 100644 index 000000000..ef6ec6618 --- /dev/null +++ b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/onap/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.artifact.handler.utils; + +import static org.junit.Assert.assertTrue; +import java.nio.charset.Charset; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class ArtifactHandlerProviderUtilTest { + + @Test(expected = Exception.class) + public void testProcessTemplate() throws Exception { + String artifact_conetent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() + .getResourceAsStream("templates/reference_template.json"), Charset.defaultCharset()); + JSONObject obj = new JSONObject(); + obj.put("artifact-name", "reference_JunitTestArtifact"); + obj.put("artifact-version", "0.01"); + obj.put("artifact-contents", artifact_conetent); + ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); + ahprovider.processTemplate(obj.toString()); + } + + @Test(expected = Exception.class) + public void testcreateDummyRequestData() throws Exception { + String artifact_conetent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() + .getResourceAsStream("templates/reference_template.json"), Charset.defaultCharset()); + JSONObject obj = new JSONObject(); + obj.put("artifact-name", "reference_JunitTestArtifact"); + obj.put("artifact-version", "0.01"); + obj.put("artifact-contents", artifact_conetent); + ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); + String requestInfo = ahprovider.createDummyRequestData(); + } + + @Test + public void testEscapeSql() throws Exception { + String testStr = "Test String is 'test'"; + ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); + ahprovider.escapeSql(testStr); + assertTrue(true); + } + + @Test + public void testGetRandom() throws Exception { + ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); + Whitebox.invokeMethod(ahprovider, "getRandom"); + assertTrue(true); + } + + @Test + public void testEscapeUtils() throws Exception { + String str = "The Test string is 'test'"; + EscapeUtils.escapeSql(str); + assertTrue(true); + } +} + diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/DBServiceTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/DBServiceTest.java deleted file mode 100644 index d5e86a0fc..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/DBServiceTest.java +++ /dev/null @@ -1,298 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.dbservices; - -import java.nio.charset.Charset; -import org.json.JSONObject; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.powermock.reflect.Whitebox; -import static org.junit.Assert.assertEquals; - -public class DBServiceTest { - - @Test - public void testSaveArtifacts() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - int internalVersion = 1; - dbService.saveArtifacts(ctx, internalVersion); - } - - @Test - public void testSaveArtifactsException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - int internalVersion = 1; - dbService.saveArtifacts(ctx, internalVersion); - } - - @Test - public void testLogData() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String prefix = "test"; - dbService.logData(ctx, prefix); - } - - - @Test - public void testLogDataException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String prefix = "test"; - dbService.logData(ctx, prefix); - } - - @Test - public void testProcessConfigActionDg() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - ctx.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, "Reference"); - dbService.processConfigActionDg(ctx, isUpdate); - } - - @Test - public void testProcessConfigActionDgException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - ctx.setAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE, "Reference"); - dbService.processConfigActionDg(ctx, isUpdate); - } - - @Test - public void testGetModelDataInformationbyArtifactName() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String artifactName = "test"; - dbService.getModelDataInformationbyArtifactName(artifactName); - } - - @Test - public void testGetModelDataInformationbyArtifactNameException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String artifactName = "test"; - dbService.getModelDataInformationbyArtifactName(artifactName); - } - - @Test - public void testUpdateYangContents() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String artifactName = "test"; - String artifactId = "TestArtifact"; - String yangContents = "TestYangContents"; - dbService.updateYangContents(ctx, artifactId, yangContents); - } - - @Test - public void testUpdateYangContentsException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String artifactName = "test"; - String artifactId = "TestArtifact"; - String yangContents = "TestYangContents"; - dbService.updateYangContents(ctx, artifactId, yangContents); - } - - @Test - public void testInsertProtocolReference() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String vnfType = "testVnf"; - String protocol = "testProtocol"; - String action = "testAction"; - String actionLevel = "testActionLevel"; - String template = "testTemplateData"; - dbService.insertProtocolReference(ctx, vnfType, protocol, action, actionLevel, template); - } - - - @Test - public void testInsertProtocolReferenceException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String vnfType = "testVnf"; - String protocol = "testProtocol"; - String action = "testAction"; - String actionLevel = "testActionLevel"; - String template = "testTemplateData"; - dbService.insertProtocolReference(ctx, vnfType, protocol, action, actionLevel, template); - } - - @Test - public void testprocessDpwnloadDGReference() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDownloadDgReference(ctx, isUpdate); - } - - @Test - public void testprocessDpwnloadDGReferenceException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDownloadDgReference(ctx, isUpdate); - } - - @Test - public void testProcessVnfcReference() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processVnfcReference(ctx, isUpdate); - } - - @Test - public void testProcessVnfcReferenceException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processVnfcReference(ctx, isUpdate); - } - - @Test - public void testProcessDeviceAuthentication() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDeviceAuthentication(ctx, isUpdate); - } - - @Test - public void testProcessDeviceAuthenticationException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDeviceAuthentication(ctx, isUpdate); - } - - @Test - public void testProcessDeviceInterfaceProtocol() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDeviceInterfaceProtocol(ctx, isUpdate); - } - - @Test - public void testProcessDeviceInterfaceProtocolException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processDeviceInterfaceProtocol(ctx, isUpdate); - } - - @Test - public void testProcessSdcReferences() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ctx.setAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY, "testCategory"); - boolean isUpdate = true; - dbService.processSdcReferences(ctx, isUpdate); - } - - @Ignore - public void testProcessSdcReferencesException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - boolean isUpdate = true; - dbService.processSdcReferences(ctx, isUpdate); - } - - @Test - public void testIsArtifactUpdateRequired() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String db = "db"; - dbService.isArtifactUpdateRequired(ctx, db); - } - - @Test - public void testIsArtifactUpdateRequiredExcetion() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String db = "db"; - dbService.isArtifactUpdateRequired(ctx, db); - } - - - @Test - public void testgetArtifactID() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String db = "db"; - dbService.getArtifactID(ctx, db); - } - - @Test - public void testgetArtifactIDException() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - String db = "db"; - dbService.getArtifactID(ctx, db); - } - @Test - public void testGetDownLoadDGReference() throws Exception { - MockDBService dbService = MockDBService.initialise(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - ctx.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL, "CLI"); - assertEquals("TestDG", dbService.getDownLoadDGReference(ctx)); - } -} - diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockDBService.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockDBService.java deleted file mode 100644 index caec09172..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockDBService.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.dbservices; - -public class MockDBService extends DBService { - private static MockDBService mockDgGeneralDBService = null; - private static MockSvcLogicResource serviceLogic = new MockSvcLogicResource();; - - public MockDBService() { - super(serviceLogic); - if (mockDgGeneralDBService != null) { - mockDgGeneralDBService = new MockDBService(serviceLogic); - } - - } - - public MockDBService(MockSvcLogicResource serviceLogic2) { - super(serviceLogic); - } - - public static MockDBService initialise() { - if (mockDgGeneralDBService == null) { - mockDgGeneralDBService = new MockDBService(serviceLogic); - } - return mockDgGeneralDBService; - } - -} - diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockSvcLogicResource.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockSvcLogicResource.java deleted file mode 100644 index c931ab0f4..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/dbservices/MockSvcLogicResource.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.dbservices; - -import java.util.Map; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; - -public class MockSvcLogicResource extends SqlResource { - - @Override - public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, - String orderBy, SvcLogicContext ctx) throws SvcLogicException { - QueryStatus status = QueryStatus.SUCCESS; - ctx.setAttribute("id", "testId"); - ctx.setAttribute("VNF_TYPE", "testvnf"); - ctx.setAttribute("maximum", "1"); - ctx.setAttribute("COUNT(*)", "1"); - ctx.setAttribute("download-config-dg", "TestDG"); - return status; - } - - - @Override - public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, - String prefix, SvcLogicContext ctx) throws SvcLogicException { - return QueryStatus.SUCCESS; - } - - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNodeTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNodeTest.java deleted file mode 100644 index 42d436e98..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/ArtifactHandlerNodeTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.node; - -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.Enumeration; -import java.util.Properties; - -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.powermock.reflect.Whitebox; -import static org.junit.Assert.assertTrue; -import org.onap.appc.artifact.handler.dbservices.DBService; -import org.onap.appc.artifact.handler.dbservices.MockDBService; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; -import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtilTest; - -import java.util.Map; -import java.util.HashMap; - -public class ArtifactHandlerNodeTest { - - @Test - public void testProcessArtifact() throws Exception { - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("test", "test"); - MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); - Map inParams = new HashMap(); - JSONObject postData = new JSONObject(); - JSONObject input = new JSONObject(); - inParams.put("response_prefix", "prefix"); - JSONObject requestInfo = new JSONObject(); - JSONObject documentInfo = new JSONObject(); - String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() - .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); - requestInfo.put("RequestInfo", "testValue"); - input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo); - input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo); - postData.put("input", input); - inParams.put("postData", postData.toString()); - ah.processArtifact(inParams, ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testStoreReferenceData() throws Exception { - MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); - JSONObject documentInfo = new JSONObject(); - String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() - .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); - JSONObject requestInfo = new JSONObject(); - requestInfo.put("RequestInfo", "testStoreReferenceData"); - ah.storeReferenceData(requestInfo, documentInfo); - } - - @Test - public void testPopulateProtocolReference() throws Exception { - ArtifactHandlerNode ah = new ArtifactHandlerNode(); - String contentStr = - "{\"action\": \"TestAction\",\"action-level\": \"vnf\",\"scope\": {\"vnf-type\": \"vDBE-I\",\"vnfc-type\": null},\"template\": \"N\",\"device-protocol\": \"REST\"}"; - JSONObject content = new JSONObject(contentStr); - MockDBService dbService = MockDBService.initialise(); - Whitebox.invokeMethod(ah, "populateProtocolReference", dbService, content); - } - - @Test - public void testProcessAndStoreCapablitiesArtifact() throws Exception { - ArtifactHandlerNode ah = new ArtifactHandlerNode(); - JSONObject capabilities = new JSONObject(); - JSONObject documentInfo = new JSONObject(); - MockDBService dbService = MockDBService.initialise(); - documentInfo.put(SdcArtifactHandlerConstants.SERVICE_UUID, "testuid"); - documentInfo.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "testDist"); - documentInfo.put(SdcArtifactHandlerConstants.SERVICE_NAME, "testName"); - documentInfo.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "testDesc"); - documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "testRes"); - documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "testResIns"); - documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_VERSOIN, "testVers"); - documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "testResType"); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "testArtifactUuid"); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_VERSOIN, "testArtifactVers"); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "testArtifactDesc"); - Whitebox.invokeMethod(ah, "processAndStoreCapablitiesArtifact", dbService, documentInfo, capabilities, - "artifactName", "someVnf"); - } - - @Test - public void testCleanVnfcInstance() throws Exception { - ArtifactHandlerNode ah = new ArtifactHandlerNode(); - SvcLogicContext ctx = new SvcLogicContext(); - Whitebox.invokeMethod(ah, "cleanVnfcInstance", ctx); - assertTrue(true); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testGetArtifactIDException() throws Exception { - ArtifactHandlerNode ah = new ArtifactHandlerNode(); - String yFileName = "yFileName"; - Whitebox.invokeMethod(ah, "getArtifactID", yFileName); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testStoreUpdateSdcArtifacts() throws Exception { - ArtifactHandlerNode ah = new ArtifactHandlerNode(); - String postDataStr = - "{\"request-information\":{},\"document-parameters\":{\"artifact-name\":\"testArtifact\",\"artifact-contents\":{\"content\":\"TestContent\"}}}"; - JSONObject postData = new JSONObject(postDataStr); - Whitebox.invokeMethod(ah, "storeUpdateSdcArtifacts", postData); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testUpdateStoreArtifacts() throws Exception { - MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); - JSONObject documentInfo = new JSONObject(); - String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() - .getResourceAsStream("templates/reference_template"), Charset.defaultCharset()); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent); - documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json"); - JSONObject requestInfo = new JSONObject(); - requestInfo.put("RequestInfo", "testupdateStoreArtifacts"); - ah.updateStoreArtifacts(requestInfo, documentInfo); - } - - @Test - public void testCleanArtifactInstanceData() throws Exception { - MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); - SvcLogicContext ctx = new SvcLogicContext(); - Whitebox.invokeMethod(ah, "cleanArtifactInstanceData", ctx); - } - - @Ignore("Test is taking 60 seconds") - @Test(expected = Exception.class) - public void testUpdateYangContents() throws Exception { - MockArtifactHandlerNode ah = new MockArtifactHandlerNode(); - String artifactId = "1"; - String yangContents = "SomeContent"; - Whitebox.invokeMethod(ah, "updateYangContents", artifactId, yangContents); - } - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/MockArtifactHandlerNode.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/MockArtifactHandlerNode.java deleted file mode 100644 index 39706a282..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/node/MockArtifactHandlerNode.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.node; - -import org.json.JSONObject; -import org.onap.appc.artifact.handler.dbservices.MockDBService; -import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class MockArtifactHandlerNode extends ArtifactHandlerNode { - - @Override - public boolean updateStoreArtifacts(JSONObject request_information, JSONObject document_information) - throws Exception { - if (request_information != null && request_information.get("RequestInfo").equals("testupdateStoreArtifacts")) { - super.updateStoreArtifacts(request_information, document_information); - } - SvcLogicContext context = new SvcLogicContext(); - MockDBService dbservice = MockDBService.initialise(); - int intversion = 0; - context.setAttribute("artifact_name", - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME)); - String internal_version = dbservice.getInternalVersionNumber(context, - document_information.getString(SdcArtifactHandlerConstants.ARTIFACT_NAME), null); - if (internal_version != null) { - intversion = Integer.parseInt(internal_version); - intversion++; - } - - return true; - - } - - @Override - public boolean storeReferenceData(JSONObject request_information, JSONObject document_information) - throws Exception { - if (request_information != null && request_information.get("RequestInfo").equals("testStoreReferenceData")) { - super.storeReferenceData(request_information, document_information); - } - return true; - } - -} diff --git a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java b/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java deleted file mode 100644 index ef6ec6618..000000000 --- a/appc-inbound/appc-artifact-handler/provider/src/test/java/org/openecomp/appc/artifact/handler/utils/ArtifactHandlerProviderUtilTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.artifact.handler.utils; - -import static org.junit.Assert.assertTrue; -import java.nio.charset.Charset; -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -public class ArtifactHandlerProviderUtilTest { - - @Test(expected = Exception.class) - public void testProcessTemplate() throws Exception { - String artifact_conetent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() - .getResourceAsStream("templates/reference_template.json"), Charset.defaultCharset()); - JSONObject obj = new JSONObject(); - obj.put("artifact-name", "reference_JunitTestArtifact"); - obj.put("artifact-version", "0.01"); - obj.put("artifact-contents", artifact_conetent); - ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); - ahprovider.processTemplate(obj.toString()); - } - - @Test(expected = Exception.class) - public void testcreateDummyRequestData() throws Exception { - String artifact_conetent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader() - .getResourceAsStream("templates/reference_template.json"), Charset.defaultCharset()); - JSONObject obj = new JSONObject(); - obj.put("artifact-name", "reference_JunitTestArtifact"); - obj.put("artifact-version", "0.01"); - obj.put("artifact-contents", artifact_conetent); - ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); - String requestInfo = ahprovider.createDummyRequestData(); - } - - @Test - public void testEscapeSql() throws Exception { - String testStr = "Test String is 'test'"; - ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); - ahprovider.escapeSql(testStr); - assertTrue(true); - } - - @Test - public void testGetRandom() throws Exception { - ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil(); - Whitebox.invokeMethod(ahprovider, "getRandom"); - assertTrue(true); - } - - @Test - public void testEscapeUtils() throws Exception { - String str = "The Test string is 'test'"; - EscapeUtils.escapeSql(str); - assertTrue(true); - } -} - diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/ArtifactInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/ArtifactInfo.java new file mode 100644 index 000000000..53f6f02fb --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/ArtifactInfo.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ArtifactInfo { + + @JsonProperty("artifact-content") + String artifact_content; + + public String getArtifact_content() { + return artifact_content; + } + + public void setArtifact_content(String artifact_content) { + this.artifact_content = artifact_content; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignInfo.java new file mode 100644 index 000000000..a6d2ba24b --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignInfo.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DesignInfo{ + + @JsonProperty("vnf-type") + String vnf_type; + + @JsonProperty("vnfc-type") + String vnfc_type; + + @JsonProperty("protocol") + String protocol; + + @JsonProperty("incart") + String inCart; + + @JsonProperty("action") + String action; + + @JsonProperty("artifact-name") + String artifact_name; + + + @JsonProperty("artifact-type") + String artifact_type; + + public String getArtifact_type() { + return artifact_type; + } + + public void setArtifact_type(String artifact_type) { + this.artifact_type = artifact_type; + } + + public String getArtifact_name() { + return artifact_name; + } + + public void setArtifact_name(String artifact_name) { + this.artifact_name = artifact_name; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getVnf_type() { + return vnf_type; + } + + public void setVnf_type(String vnf_type) { + this.vnf_type = vnf_type; + } + + public String getVnfc_type() { + return vnfc_type; + } + + public void setVnfc_type(String vnfc_type) { + this.vnfc_type = vnfc_type; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getInCart() { + return inCart; + } + + public void setInCart(String inCart) { + this.inCart = inCart; + } + + @Override + public String toString() { + return "DesignInfo [vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol=" + protocol + ", inCart=" + + inCart + "]"; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignRequest.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignRequest.java new file mode 100644 index 000000000..d61de0282 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignRequest.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.data; + +import java.io.File; +import java.net.URL; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.onap.appc.design.services.util.DesignServiceConstants; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class DesignRequest{ + + + @JsonProperty("userID") + String userId ; + + @JsonProperty("vnf-type") + String vnf_type; + + @JsonProperty("vnfc-type") + String vnfc_type; + + @JsonProperty("protocol") + String protocol; + + @JsonProperty("action") + String action; + + @JsonProperty("artifact-name") + String artifact_name; + + @JsonProperty("artifact-contents") + String artifact_contents ; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getVnf_type() { + return vnf_type; + } + + public void setVnf_type(String vnf_type) { + this.vnf_type = vnf_type; + } + + public String getVnfc_type() { + return vnfc_type; + } + + public void setVnfc_type(String vnfc_type) { + this.vnfc_type = vnfc_type; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getArtifact_name() { + return artifact_name; + } + + public void setArtifact_name(String artifact_name) { + this.artifact_name = artifact_name; + } + + public String getArtifact_contents() { + return artifact_contents; + } + + public void setArtifact_contents(String artifact_contents) { + this.artifact_contents = artifact_contents; + } + + @Override + public String toString() { + return "DesignRequest [userId=" + userId + ", vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol=" + + protocol + ", action=" + action + ", artifact_name=" + artifact_name + ", artifact_contents=" + + artifact_contents + "]"; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignResponse.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignResponse.java new file mode 100644 index 000000000..559620d9e --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/DesignResponse.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.data; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class DesignResponse{ + + + @JsonProperty("userID") + String userId ; + + @JsonProperty("designInfo") + List designInfoList; + + @JsonProperty("statusInfo") + List statusInfoList; + + @JsonProperty("artifactInfo") + List artifactInfo; + + + public List getArtifactInfo() { + return artifactInfo; + } + + public void setArtifactInfo(List artifactInfo) { + this.artifactInfo = artifactInfo; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public List getDesignInfoList() { + return designInfoList; + } + + public void setDesignInfoList(List designInfoList) { + this.designInfoList = designInfoList; + } + + public List getStatusInfoList() { + return statusInfoList; + } + + public void setStatusInfoList(List statusInfoList) { + this.statusInfoList = statusInfoList; + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/StatusInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/StatusInfo.java new file mode 100644 index 000000000..6d4b1a5a1 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/data/StatusInfo.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.data; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class StatusInfo{ + + @JsonProperty("vnf-type") + String vnf_type; + + @JsonProperty("vnfc-type") + String vnfc_type; + + @JsonProperty("action") + String action; + + @JsonProperty("artifact-status") + String artifact_status; + + @JsonProperty("action-status") + String action_status; + + public String getVnf_type() { + return vnf_type; + } + + public void setVnf_type(String vnf_type) { + this.vnf_type = vnf_type; + } + + public String getVnfc_type() { + return vnfc_type; + } + + public void setVnfc_type(String vnfc_type) { + this.vnfc_type = vnfc_type; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getArtifact_status() { + return artifact_status; + } + + public void setArtifact_status(String artifact_status) { + this.artifact_status = artifact_status; + } + + public String getAction_status() { + return action_status; + } + + public void setAction_status(String action_status) { + this.action_status = action_status; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbResponseProcessor.java new file mode 100644 index 000000000..e697a9d4f --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbResponseProcessor.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.dbervices; + +import org.onap.appc.design.services.util.DesignServiceConstants; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DbResponseProcessor { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DbResponseProcessor.class); + public String parseResponse(String dbresposne, String action) throws Exception { + + log.info("Starting Parsing the response for action : " + action + "\n data " + dbresposne ); + String response ; + switch (action) { + case DesignServiceConstants.GETDESIGNS: + response = getDesignsResponse(dbresposne); + break; + case DesignServiceConstants.ADDINCART: + response = getAddInCartResponse(dbresposne); + break ; + case DesignServiceConstants.GETARTIFACTREFERENCE: + response= getArtifactReferenceResponse(dbresposne); + break; + case DesignServiceConstants.GETARTIFACT: + response= getArtifactResponse(dbresposne); + break; + case DesignServiceConstants.GETGUIREFERENCE: + response= getGuiReferenceResponse(dbresposne); + break; + case DesignServiceConstants.GETSTATUS: + response= getStatusResponse(dbresposne); + break; + case DesignServiceConstants.UPLOADARTIFACT: + response= getsetStatusResponse(dbresposne); + break; + case DesignServiceConstants.SETPROTOCOLREFERENCE: + response= getsetStatusResponse(dbresposne); + break; + case DesignServiceConstants.SETINCART: + response= getsetStatusResponse(dbresposne); + break; + default: + log.error("Action " + action + " Not Supported by response Parser"); + throw new Exception(" Action " + action + " not found while processing request "); + + } + return response; + + } + + private String getArtifactResponse(String dbresposne) { + // TODO Auto-generated method stub + return dbresposne; + } + + private String getsetStatusResponse(String dbresposne) { + // TODO Auto-generated method stub + return null; + } + + private String getStatusResponse(String dbresposne) { + log.info("Returning reposne from Response Parser " + dbresposne); + return dbresposne; + } + + private String getGuiReferenceResponse(String dbresposne) { + // TODO Auto-generated method stub + return null; + } + + private String getArtifactReferenceResponse(String dbresposne) { + // TODO Auto-generated method stub + return null; + } + + private String getAddInCartResponse(String dbresposne) { + // TODO Auto-generated method stub + return null; + } + + private String getDesignsResponse(String dbresposne) { + return dbresposne; + + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbService.java new file mode 100644 index 000000000..a2349196f --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DbService.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.dbervices; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; +import java.util.UUID; + +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DbService { + + private static final Logger Log = LoggerFactory.getLogger(DbService.class); + private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DBResourceManager"; + DbLibService dblibSvc = null; + String errorMsg = null; + + public DbService() throws Exception { + DbLibService dblibSvc = null; + Log.info("Initializing DbService service"); + try + { + dblibSvc = getDbLibService(); + if (dblibSvc == null) { + Log.error("Got Exception While getting DB Connection"); + throw new Exception("Got Exception While getting DB Connection"); + } + this.dblibSvc = dblibSvc; + } + catch (Exception e) { + Log.error(e.getMessage()); + throw e; + } + } + + private static DbLibService getDbLibService() { + + DbLibService dblibSvc = null; + BundleContext bctx = null; + ServiceReference sref = null; + + Bundle bundle = FrameworkUtil.getBundle(SvcLogicService.class); + + if (bundle != null) { + bctx = bundle.getBundleContext(); + } + + if (bctx != null) { + Log.debug("Getting bundle Context"); + sref = bctx.getServiceReference(DBLIB_SERVICE); + } + + if (sref == null) { + Log.warn("Could not find service reference for DBLib service"); + + } else { + dblibSvc = (DbLibService) bctx.getService(sref); + if (dblibSvc == null) { + Log.warn("DBLIB_SERVICE is null"); + } + } + if (dblibSvc == null) { + try { + dblibSvc = new DBResourceManager(System.getProperties()); + } catch (Exception e) { + Log.error("Caught exception trying to create db service", e); + } + + if (dblibSvc == null) { + Log.warn("Could not create new DBResourceManager"); + } + } + return (dblibSvc); + } + + public ResultSet getDBData(String query) throws Exception { + ResultSet resultSet; + StringBuilder sqlBuilder = new StringBuilder(query); + Log.info("Query: " + sqlBuilder.toString()); + try { + resultSet = dblibSvc.getData(sqlBuilder.toString(), null, null); + } catch (Exception e) { + Log.error("SQL query "+sqlBuilder+" :: " + e.getMessage()); + throw e; + } + return resultSet; + } + + public ResultSet getDBData(String query, ArrayList paramList) throws Exception { + ResultSet resultSet; + StringBuilder sqlBuilder = new StringBuilder(query); + Log.info("Query :" + sqlBuilder.toString()); + try { + resultSet = dblibSvc.getData(sqlBuilder.toString(), paramList, null); + } catch (Exception expObj) { + Log.error("query "+sqlBuilder+" :: " + expObj.getMessage()); + throw expObj; + } + return resultSet; + } + + public boolean updateDBData(String query, ArrayList paramList) throws Exception { + boolean update; + StringBuilder sqlBuilder = new StringBuilder(query); + Log.info("Query :" + sqlBuilder.toString()); + try { + update = dblibSvc.writeData(sqlBuilder.toString(), paramList, null); + } catch (Exception expObj) { + Log.error("query "+sqlBuilder+" :: " + expObj.getMessage()); + throw expObj; + } + return update; + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DesignDBService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DesignDBService.java new file mode 100644 index 000000000..64251027f --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/DesignDBService.java @@ -0,0 +1,645 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.dbervices; + +import java.io.IOException; +import java.security.SecureRandom; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.onap.appc.design.data.ArtifactInfo; +import org.onap.appc.design.data.DesignInfo; +import org.onap.appc.design.data.DesignResponse; +import org.onap.appc.design.data.StatusInfo; +import org.onap.appc.design.services.util.ArtifactHandlerClient; +import org.onap.appc.design.services.util.DesignServiceConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class DesignDBService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DesignDBService.class); + private SvcLogicResource serviceLogic; + private static DesignDBService dgGeneralDBService = null; + private static DBResourceManager jdbcDataSource; + + DbService dbservice = null; + private static Properties props; + public static DesignDBService initialise() { + if (dgGeneralDBService == null) { + dgGeneralDBService = new DesignDBService(); + } + return dgGeneralDBService; + } + private DesignDBService() { + if (serviceLogic == null) { + serviceLogic = new SqlResource(); + } + } + + public String execute(String action, String payload, String requestID) throws Exception { + + log.info("Received execute request for action : " + action + " with Payload : "+ payload ); + RequestValidator.validate(action, payload); + String response = null; + dbservice = new DbService(); + switch (action) { + case DesignServiceConstants.GETDESIGNS: + response = getDesigns(payload,requestID ); + break; + case DesignServiceConstants.ADDINCART: + response= setInCart(payload, requestID); + break ; + case DesignServiceConstants.GETARTIFACTREFERENCE: + response= getArtifactReference(payload, requestID); + break; + case DesignServiceConstants.GETARTIFACT: + response= getArtifact(payload, requestID); + break; + case DesignServiceConstants.GETGUIREFERENCE: + response= getGuiReference(payload, requestID); + break; + case DesignServiceConstants.GETSTATUS: + response= getStatus(payload, requestID); + break; + case DesignServiceConstants.SETSTATUS: + response= setStatus(payload, requestID); + break; + case DesignServiceConstants.UPLOADARTIFACT: + response= uploadArtifact(payload, requestID); + break; + case DesignServiceConstants.SETPROTOCOLREFERENCE: + response= setProtocolReference(payload, requestID); + break; + default: + throw new Exception(" Action " + action + " not found while processing request "); + + } + return response; + } + + private String setInCart(String payload, String requestID) throws Exception { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get(DesignServiceConstants.INCART).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + + String queryString = "UPDATE DT_ARTIFACT_TRACKING SET INCART= ? WHERE ASDC_REFERENCE_ID IN " + + " (SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE_ID WHERE VNF_TYPE = ? " ; + + if(payloadObject.get(DesignServiceConstants.VNF_TYPE) != null &&! payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) { + queryString = queryString + " AND VNFC_TYPE = ? ) AND USER = ? " ; + argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); + } + else{ + queryString = queryString + " ) AND USER = ? " ; + } + + argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); + + log.info("Query String :" + queryString); + boolean data = dbservice.updateDBData(queryString, argList); + + if(!data) + throw new Exception("Error while updating ProtocolReference"); + + return "{\"update\" : \"success\" } "; + + } + private String setProtocolReference(String payload, String requestID) throws Exception { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + + argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue()); + + String queryString = " DELETE FROM PROTOCOL_REFERENCE WHERE ACTION = ? AND ACTION_LEVEL AND VNF_TYPE= ? AND PROTOCOL = ? " ; + + log.info("Delete Query String :" + queryString); + boolean data = dbservice.updateDBData(queryString, argList); + + log.info("Record Deleted"); + + if((payloadObject.get(DesignServiceConstants.TEMPLATE) != null && !payloadObject.get(DesignServiceConstants.TEMPLATE).textValue().isEmpty())) + argList.add(payloadObject.get(DesignServiceConstants.TEMPLATE).textValue()); + else + argList.add("NO"); + + String insertString = "INSERT INTO PROTOCOL_REFERENCE VALUES (?,?,?,?,?,SYSDATE()) "; + + if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && ! payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ + queryString = queryString + " AND VNFC_TYPE = ? )" ; + } + else{ + queryString = queryString + " ) "; + } + log.info("Query String :" + queryString); + data = dbservice.updateDBData(queryString, argList); + + if(!data) + throw new Exception("Error while updating ProtocolReference"); + + return "{\"update\" : \"success\" } "; + } + private String uploadArtifact(String payload, String requestID) throws Exception { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + log.info("Got upload Aritfact with Payload : " + payloadObject.asText()); + try{ + ArtifactHandlerClient ac = new ArtifactHandlerClient(); + String requestString = ac.createArtifactData(payload, requestID); + ac.execute(requestString, "POST"); + int sdc_artifact_id = getSDCArtifactIDbyRequestID(requestID); + int sdc_reference_id = getSDCReferenceID(payload); + createArtifactTrackingRecord(payload, requestID,sdc_artifact_id, sdc_reference_id ); + String status = getDataFromActionStatus(payload, "STATUS"); + if(status == null || status.isEmpty()) + setActionStatus(payload, "Not Tested"); + linkstatusRelationShip(sdc_artifact_id,sdc_reference_id, payload); + + } + catch(Exception e){ + e.printStackTrace(); + throw e; + } + return "{\"update\" : \"success\" } "; + + } + + private void linkstatusRelationShip(int sdc_artifact_id, int sdc_reference_id, String payload) throws Exception { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(String.valueOf(sdc_artifact_id)); + argList.add(String.valueOf(sdc_reference_id)); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); + + String queryString = "INSERT INTO DT_STATUS_RELATIONSHIP (DT_ARTIFACT_TRACKING_ID,DT_ACTION_STATUS_ID) VALUES " + + "(( SELECT DT_ARTIFACT_TRACKING_ID FROM DT_ARTIFACT_TRACKING WHERE ASDC_ARTIFACTS_ID = ? AND ASDC_REFERENCE_ID = ? ) , " + + "( SELECT DT_ACTION_STATUS_ID FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? " ; + + if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && ! payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ + queryString = queryString + " AND VNFC_TYPE = ? ) )" ; + } + else{ + queryString = queryString + " ) ) "; + } + log.info("Query String :" + queryString); + boolean data = dbservice.updateDBData(queryString, argList); + + if(!data) + throw new Exception("Error while updating RealtionShip table"); + + } + private int getSDCReferenceID(String payload) throws Exception { + + String vnfc_type = null; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + + argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue()); + + String queryString = " SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE WHERE VNF_TYPE = ? " + + " AND ARTIFACT_TYPE = ? AND ARTIFACT_NAME = ? " ; + + if(payloadObject.get(DesignServiceConstants.ACTION) != null && !payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()){ + argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); + queryString = queryString + " AND ACTION = ? "; + } + if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ + argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); + queryString = queryString + " AND VNFC_TYPE = ? "; + + } + + log.info("Query String :" + queryString); + ResultSet data = dbservice.getDBData(queryString, argList); + int sdc_reference_id = 0; + while(data.next()) { + sdc_reference_id = data.getInt("ASDC_REFERENCE_ID"); + } + log.info("Got sdc_reference_id = " + sdc_reference_id ); + return sdc_reference_id; + + } + + private String getDataFromActionStatus(String payload, String dataValue) throws Exception { + String status = null ; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); + String queryString = " SELECT " + dataValue + " FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? "; + if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ + argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); + queryString = queryString + " AND VNFC_TYPE = ? "; + } + log.info("Query String :" + queryString); + ResultSet data = dbservice.getDBData(queryString, argList); + while(data.next()) { + status = data.getString("STATUS"); + } + log.info("DT_ACTION_STATUS Status = " + status ); + return status; + } + + private boolean setActionStatus(String payload, String status) throws Exception { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); + argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); + + + String insertQuery = " INSERT INTO DT_ACTION_STATUS (ACTION, VNF_TYPE, VNFC_TYPE, USER, TECHNOLOGY, UPDATED_DATE, STATUS) VALUES (?,?,?,?,?,sysdate() , ?); "; + if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ + argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); + } + else{ + argList.add(null); + } + argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); + if(payloadObject.get(DesignServiceConstants.TECHNOLOGY) !=null && !payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()){ + argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue()); + } + else{ + argList.add(null); + } + argList.add(status); + + boolean updateStatus = dbservice.updateDBData(insertQuery, argList); + if(!updateStatus) + throw new Exception("Error while updating Action Status"); + return updateStatus; + } + + private void createArtifactTrackingRecord(String payload, String requestID, int sdc_artifact_id, int sdc_reference_id) throws Exception { + String vnfc_type = null; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + + ArrayList argList = new ArrayList<>(); + argList.add(String.valueOf(sdc_artifact_id)); + argList.add(String.valueOf(sdc_reference_id)); + argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); + if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null &&! payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) + argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue()); + else + argList.add(""); + + if (payloadObject.get(DesignServiceConstants.PROTOCOL) != null &&! payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) + argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue()); + else + argList.add(""); + + + String queryString = "INSERT INTO DT_ARTIFACT_TRACKING (ASDC_ARTIFACTS_ID, ASDC_REFERENCE_ID, USER, TECHNOLOGY, CREATION_DATE, UPDATED_DATE, ARTIFACT_STATUS, PROTOCOL, IN_CART) VALUES (? , ? , ?, ?, sysdate() , sysdate(), 'Created', ? ,'N' )" ; + + log.info("Query String :" + queryString); + boolean data = dbservice.updateDBData(queryString, argList); + if(!data) + throw new Exception("Error Updating DT_ARTIFACT_TRACKING "); + + + } + + private int getSDCArtifactIDbyRequestID(String requestID) throws Exception { + log.info("Starting getArtifactIDbyRequestID DB Operation"); + int artifact_id = 0; + try{ + ArrayList argList = new ArrayList<>(); + argList.add("TLSUUID" + requestID); + String queryString = " SELECT ASDC_ARTIFACTS_ID FROM ASDC_ARTIFACTS where SERVICE_UUID = ? "; + log.info("Query String :" + queryString); + ResultSet data = dbservice.getDBData(queryString, argList); + while(data.next()){ + artifact_id = data.getInt("ASDC_ARTIFACTS_ID"); + } + } + catch(Exception e){ + e.printStackTrace(); + throw e; + } + log.info("Got SDC_ARTIFACTS_ID As :" + artifact_id); + return artifact_id; + } + + + private String getArtifact(String payload, String requestID) throws Exception { + String fn = "DBService.getStatus "; + log.info("Starting getArtifact DB Operation"); + try{ + String vnfc_type = null; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get("artifact-name").textValue()); + argList.add(payloadObject.get("artifact-type").textValue()); + + String queryString = "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS where " + + " ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ? " ; + + log.info("Query String :" + queryString); + ResultSet data = dbservice.getDBData(queryString, argList); + String artifact_content = null; + int hightestVerion = 0 ; + while(data.next()) { + int version = data.getInt("INTERNAL_VERSION"); + if(hightestVerion < version) + artifact_content = data.getString("ARTIFACT_CONTENT"); + } + + if(artifact_content == null || artifact_content.isEmpty()) + throw new Exception("Sorry !!! I dont have any artifact Named : " + payloadObject.get("artifact-name").textValue()); + DesignResponse designResponse = new DesignResponse(); + designResponse.setUserId(payloadObject.get("userID").textValue()); + List artifactInfoList = new ArrayList(); + ArtifactInfo artifactInfo = new ArtifactInfo(); + artifactInfo.setArtifact_content(artifact_content); + artifactInfoList.add(artifactInfo); + designResponse.setArtifactInfo(artifactInfoList); + + ObjectMapper mapper = new ObjectMapper(); + String jsonString = mapper.writeValueAsString(designResponse); + log.info("Info : " + jsonString); + return jsonString; + } + catch(SQLException e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + catch(Exception e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + + } + private String setStatus(String payload, String requestID) throws Exception { + String fn = "DBService.getStatus "; + log.info("Starting getStatus DB Operation"); + try{ + String vnfc_type = null; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + + + ArrayList argList = new ArrayList<>(); + argList.add(payloadObject.get("artifact_status").textValue()); + argList.add(payloadObject.get("action_status").textValue()); + + argList.add(payloadObject.get("userID").textValue()); + argList.add(payloadObject.get("vnf-type").textValue()); + + String queryString = " UPDATE DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR SET DAT.ARTIFACT_STATUS = ? , DAS.DT_ACTION_STATUS = ? " + + " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID " + + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ? " + + " and DAS.VNF_TYPE = ? " ; + + if(payloadObject.get("vnfc-type") !=null && !payloadObject.get("vnfc-type").textValue().isEmpty()){ + argList.add(payloadObject.get("vnfc-type").textValue()); + queryString = queryString + " and DAS.VNFC_TYPE = ? "; + } + + log.info("Query String :" + queryString); + + DesignResponse designResponse = new DesignResponse(); + designResponse.setUserId(payloadObject.get("userID").textValue()); + List statusInfoList = new ArrayList(); + boolean update = dbservice.updateDBData(queryString, argList); + if(!update) + throw new Exception("Sorry .....Something went wrong while updating the Status"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonString = mapper.writeValueAsString(designResponse); + log.info("Info : " + jsonString); + return jsonString; + } + catch(SQLException e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + catch(Exception e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + } + private String getStatus(String payload, String requestID) throws Exception { + String fn = "DBService.getStatus "; + log.info("Starting getStatus DB Operation"); + try{ + String vnfc_type = null; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + String UserID = payloadObject.get("userID").textValue(); + String vnf_type = payloadObject.get("vnf-type").textValue(); + if(payloadObject.get("vnfc-type") != null ) + vnfc_type = payloadObject.get("vnfc-type").textValue(); + ArrayList argList = new ArrayList<>(); + + argList.add(UserID); + argList.add(vnf_type); + + String queryString = "SELECT DAS.VNF_TYPE, DAS.VNFC_TYPE, DAS.STATUS, DAS.ACTION, DAT.ARTIFACT_STATUS " + + "from DT_ACTION_STATUS DAS , DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR " + + " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID " + + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ? " + + " and DAS.VNF_TYPE = ? " ; + + if(vnfc_type !=null && ! vnfc_type.isEmpty()){ + argList.add(vnfc_type); + queryString = queryString + " and DAS.VNFC_TYPE = ? "; + } + + log.info("Query String :" + queryString); + + DesignResponse designResponse = new DesignResponse(); + designResponse.setUserId(UserID); + List statusInfoList = new ArrayList(); + ResultSet data = dbservice.getDBData(queryString, argList); + while(data.next()) { + StatusInfo statusInfo = new StatusInfo(); + statusInfo.setAction(data.getString("ACTION")); + statusInfo.setAction_status(data.getString("STATUS")); + statusInfo.setArtifact_status(data.getString("ARTIFACT_STATUS")); + statusInfo.setVnf_type(data.getString("VNF_TYPE")); + statusInfo.setVnfc_type(data.getString("VNFC_TYPE")); + statusInfoList.add(statusInfo); + } + + if(statusInfoList.size() < 1) + throw new Exception("OOPS !!!! No VNF information available for VNF-TYPE : " + vnf_type + " for User : " + UserID); + designResponse.setStatusInfoList(statusInfoList); + ObjectMapper mapper = new ObjectMapper(); + String jsonString = mapper.writeValueAsString(designResponse); + log.info("Info : " + jsonString); + return jsonString; + } + catch(SQLException e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + catch(Exception e) + { + log.error("Error while DB operation : " + e.getMessage()); + e.printStackTrace(); + throw e; + } + } + private String getGuiReference(String payload, String requestID) { + // TODO Auto-generated method stub + return null; + } + private String getArtifactReference(String payload, String requestID) { + // TODO Auto-generated method stub + return null; + } + private String getAddInCart(String payload, String requestID) { + // TODO Auto-generated method stub + return null; + } + + // private String getDesigns(String payload, String requestID) throws SQLException, JsonProcessingException, IOException, SvcLogicException { + // + // String fn = "DBService.getDesigns "; + // QueryStatus status = null; + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode jnode = objectMapper.readTree(payload); + // String UserId = jnode.get("userID").textValue(); + // SvcLogicContext localContext = new SvcLogicContext(); + // localContext.setAttribute("requestID", requestID); + // localContext.setAttribute("userID", UserId); + // if (serviceLogic != null && localContext != null) { + // String queryString = "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART from " + + // DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , " + DesignServiceConstants.DB_SDC_REFERENCE + + // " AR where DAT.SDC_REFERENCE_ID= AR.SDC_REFERENCE_ID and DAT.USER = $userID" ; + // + // log.info(fn + "Query String : " + queryString); + // try { + // status = serviceLogic.query("SQL", true, null, queryString, null, null, localContext); + // } catch (SvcLogicException e1) { + // // TODO Auto-generated catch block + // e1.printStackTrace(); + // } + // + // if(status.toString().equals("FAILURE")) + // throw new SvcLogicException("Error - while getting FlowReferenceData "); + // + // Properties props = localContext.toProperties(); + // log.info("SvcLogicContext contains the following : " + props.toString()); + // for (Enumeration e = props.propertyNames(); e.hasMoreElements() ; ) { + // String propName = (String) e.nextElement(); + // log.info(propName+" = "+props.getProperty(propName)); + // + // } + // } + // return requestID; + // + // } + + private String getDesigns(String payload, String requestID) throws Exception { + + String fn = "DBService.getDesigns "; + log.info("Starting getDesgins DB Operation"); + + + try{ + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + String UserID = payloadObject.get("userID").textValue(); + ArrayList argList = new ArrayList<>(); + argList.add(UserID); + + String queryString = "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART, AR.ACTION, AR.ARTIFACT_NAME, AR.ARTIFACT_TYPE from " + + DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , " + DesignServiceConstants.DB_SDC_REFERENCE + + " AR where DAT.ASDC_REFERENCE_ID= AR.ASDC_REFERENCE_ID and DAT.USER = ? "; + + DesignResponse designResponse = new DesignResponse(); + designResponse.setUserId(UserID); + List designInfoList = new ArrayList(); + ResultSet data = dbservice.getDBData(queryString, argList); + while(data.next()) { + DesignInfo designInfo = new DesignInfo(); + designInfo.setInCart(data.getString("IN_CART")); + designInfo.setProtocol(data.getString("PROTOCOL")); + designInfo.setVnf_type(data.getString("VNF_TYPE")); + designInfo.setVnfc_type(data.getString("VNFC_TYPE")); + designInfo.setAction(data.getString("ACTION")); + designInfo.setArtifact_type(data.getString("ARTIFACT_TYPE")); + designInfo.setArtifact_name(data.getString("ARTIFACT_NAME")); + designInfoList.add(designInfo); + } + if(designInfoList.size() < 1) + throw new Exception(" Welcome to CDT, Looks like you dont have Design Yet... Lets create some...."); + designResponse.setDesignInfoList(designInfoList); + ObjectMapper mapper = new ObjectMapper(); + String jsonString = mapper.writeValueAsString(designResponse); + log.info("Info : " + jsonString); + return jsonString; + } + catch(Exception e) + { + e.printStackTrace(); + throw e; + } + } + +} + + diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/RequestValidator.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/RequestValidator.java new file mode 100644 index 000000000..c0b710deb --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/dbervices/RequestValidator.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.dbervices; + +import org.onap.appc.design.services.util.ArtifactHandlerClient; +import org.onap.appc.design.services.util.DesignServiceConstants; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RequestValidator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(RequestValidator.class); + public static void validate(String action, String payload) throws Exception { + log.info("payload" + payload); + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + log.info("payloadObject" + payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS)); + + String errorString = null; + switch (action) { + case DesignServiceConstants.GETDESIGNS: + if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) + errorString = DesignServiceConstants.USER_ID; + break; + case DesignServiceConstants.GETARTIFACT: + if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_TYPE; + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_NAME; + break; + case DesignServiceConstants.GETSTATUS: + if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) + errorString = DesignServiceConstants.USER_ID; + else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + break; + case DesignServiceConstants.SETSTATUS: + if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) + errorString = DesignServiceConstants.USER_ID; + else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + else if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION; + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_TYPE; + else if(payloadObject.get(DesignServiceConstants.STATUS) == null || payloadObject.get(DesignServiceConstants.STATUS).textValue().isEmpty()) + errorString = DesignServiceConstants.STATUS; + break; + case DesignServiceConstants.UPLOADARTIFACT: + if(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_NAME; + else if(! payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().contains("reference")){ + if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION; + } + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_VERSOIN; + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS) == null) + errorString = DesignServiceConstants.ARTIFACT_CONTENTS; + else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.ARTIFACT_TYPE; + + else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + + + break; + case DesignServiceConstants.SETPROTOCOLREFERENCE: + if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION; + else if(payloadObject.get(DesignServiceConstants.ACTION_LEVEL) == null || payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION_LEVEL; + else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + else if(payloadObject.get(DesignServiceConstants.PROTOCOL) == null || payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) + errorString = DesignServiceConstants.PROTOCOL; + + case DesignServiceConstants.SETINCART: + if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION; + else if(payloadObject.get(DesignServiceConstants.ACTION_LEVEL) == null || payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue().isEmpty()) + errorString = DesignServiceConstants.ACTION_LEVEL; + else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) + errorString = DesignServiceConstants.VNF_TYPE; + else if(payloadObject.get(DesignServiceConstants.PROTOCOL) == null || payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) + errorString = DesignServiceConstants.PROTOCOL; + break; + default: + throw new Exception(" Action " + action + " not found while processing request "); + + } + if(errorString != null) + throw new Exception(" Missing input parameter :-" + errorString + " -:"); + + } + +} + + diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/propertyServices/PropertyUpdateService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/propertyServices/PropertyUpdateService.java new file mode 100644 index 000000000..87e84d495 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/propertyServices/PropertyUpdateService.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.propertyServices; + +public class PropertyUpdateService { + + // to set the properties this placeholder will be used. +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/DesignServiceProvider.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/DesignServiceProvider.java new file mode 100644 index 000000000..f41bbac46 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/DesignServiceProvider.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services; + +import java.util.concurrent.Future; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DesignServicesService; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.design.services.impl.DesignServicesImpl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DesignServiceProvider{ + + private static final EELFLogger log = EELFManager.getInstance().getLogger(DesignServiceProvider.class); + + private final DataBroker dataBroker; + private final RpcProviderRegistry rpcProviderRegistry; + private RpcRegistration serviceRegistration; + + + public DesignServiceProvider(final DataBroker dataBroker, RpcProviderRegistry rpcProviderRegistry) { + this.dataBroker = dataBroker; + this.rpcProviderRegistry = rpcProviderRegistry; + } + + /** + * Method called when the blueprint container is created. + */ + public void init() { + // initialize data broker + this.serviceRegistration = this.rpcProviderRegistry.addRpcImplementation(DesignServicesService.class, new DesignServicesImpl()); + log.info("DesignServicesImpl Session Initiated"); + } + + /** + * Method called when the blueprint container is destroyed. + */ + public void close() { + if(this.serviceRegistration != null){ + this.serviceRegistration.close(); + } + log.info("DesignServicesImpl Closed"); + } + + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/impl/DesignServicesImpl.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/impl/DesignServicesImpl.java new file mode 100644 index 000000000..1787618e6 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/impl/DesignServicesImpl.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services.impl; + +import java.util.concurrent.Future; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DesignServicesService; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.data.DataBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.status.StatusBuilder; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.design.dbervices.DbResponseProcessor; +import org.onap.appc.design.dbervices.DesignDBService; +import org.onap.appc.design.services.util.DesignServiceConstants; +import org.onap.appc.design.validator.ValidatorResponseProcessor; +import org.onap.appc.design.validator.ValidatorService; +import org.onap.appc.design.xinterface.XInterfaceService; +import org.onap.appc.design.xinterface.XResponseProcessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Futures; + +public class DesignServicesImpl implements DesignServicesService { + + private static final Logger log = LoggerFactory.getLogger(DesignServicesImpl.class); + + @Override + public Future> dbservice(DbserviceInput input) { + + log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + + input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload()); + + + DbserviceOutputBuilder outputBuilder = new DbserviceOutputBuilder(); + DataBuilder databuilder = new DataBuilder(); + StatusBuilder statusBuilder = new StatusBuilder(); + + try{ + DesignDBService dbservices = DesignDBService.initialise(); + DbResponseProcessor responseProcessor = new DbResponseProcessor(); + String response = responseProcessor.parseResponse(dbservices.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload(), input.getDesignRequest().getRequestId()), input.getDesignRequest().getAction()); + log.info("Response in for Design Service : " + response); + databuilder.setBlock(response); + databuilder.setRequestId(input.getDesignRequest().getRequestId()); + statusBuilder.setCode("400"); + statusBuilder.setMessage("success"); + } + catch(Exception e){ + log.error("Error" + e.getMessage()); + e.printStackTrace(); + statusBuilder.setCode("401"); + statusBuilder.setMessage(e.getMessage()); + } + + outputBuilder.setData(databuilder.build()); + outputBuilder.setStatus(statusBuilder.build()); + + RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> xinterfaceservice(XinterfaceserviceInput input) { + log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + + input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload()); + XinterfaceserviceOutputBuilder outputBuilder = new XinterfaceserviceOutputBuilder(); + DataBuilder databuilder = new DataBuilder(); + StatusBuilder statusBuilder = new StatusBuilder(); + try { + + XInterfaceService xInterfaceService = new XInterfaceService(); + XResponseProcessor responseProcessor = new XResponseProcessor(); + String response = responseProcessor.parseResponse(xInterfaceService.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload()), input.getDesignRequest().getAction()); + databuilder.setBlock(response); + databuilder.setRequestId(input.getDesignRequest().getRequestId()); + statusBuilder.setCode("400"); + statusBuilder.setMessage("success"); + } catch (Exception e) { + e.printStackTrace(); + statusBuilder.setCode("401"); + statusBuilder.setMessage(e.getMessage()); + } + outputBuilder.setData(databuilder.build()); + outputBuilder.setStatus(statusBuilder.build()); + + RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> validator(ValidatorInput input) { + log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + + input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload() + " and Data Type = " + input.getDesignRequest().getDataType()); + ValidatorOutputBuilder outputBuilder = new ValidatorOutputBuilder(); + StatusBuilder statusBuilder = new StatusBuilder(); + + + try { + if(input.getDesignRequest().getDataType() == null || input.getDesignRequest().getDataType().isEmpty()) + throw new Exception ("Data Type required for validate Serivce"); + if(input.getDesignRequest().getAction()== null || input.getDesignRequest().getAction().isEmpty()) + throw new Exception ("Action required for validate Serivce"); + + + if(! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_JSON) && + ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_YAML) && + ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_XML) && + ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_VELOCITY)) + throw new Exception ("Request Data format " + input.getDesignRequest().getDataType() + + " is not supported by validate Service : Supported data types are : XML, YAML, VELOCITY, JSON "); + + ValidatorService validatorService = new ValidatorService(); + ValidatorResponseProcessor responseProcessor = new ValidatorResponseProcessor(); + String response = validatorService.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload(), input.getDesignRequest().getDataType()); + statusBuilder.setCode("400"); + statusBuilder.setMessage(response); + } catch (Exception e) { + e.printStackTrace(); + statusBuilder.setCode("401"); + statusBuilder.setMessage(e.getMessage()); + } + + outputBuilder.setStatus(statusBuilder.build()); + + RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/ArtifactHandlerClient.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/ArtifactHandlerClient.java new file mode 100644 index 000000000..b250faca9 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/ArtifactHandlerClient.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services.util; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.Charset; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public class ArtifactHandlerClient { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerClient.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + Properties props = new Properties(); + public ArtifactHandlerClient() throws Exception { + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); + String propFile = propDir + "/" + DesignServiceConstants.DESIGN_SERVICE_PROPERTIES; + InputStream propStream = new FileInputStream(propFile); + try{ + props.load(propStream); + } + catch (Exception e){ + throw new Exception("Could not load properties file " + propFile, e); + } + finally{ + try{ + propStream.close(); + } + catch (Exception e){ + log.warn("Could not close FileInputStream", e); + } + } + } + + public String createArtifactData(String payload, String requestID) throws JsonProcessingException, IOException { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode payloadObject = objectMapper.readTree(payload); + + ObjectNode json = objectMapper.createObjectNode(); + + String artifact_name = payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue(); + String artifact_version = payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue(); + String artifact_contents = payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS).textValue(); + + ObjectNode requestInfo = objectMapper.createObjectNode(); + + requestInfo.put(DesignServiceConstants.REQUETS_ID, requestID); + requestInfo.put(DesignServiceConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); + requestInfo.put(DesignServiceConstants.SOURCE, DesignServiceConstants.DESIGN_TOOL); + + String random = getRandom(); + + ObjectNode docParams = objectMapper.createObjectNode(); + + docParams.put(DesignServiceConstants.ARTIFACT_VERSOIN, artifact_version); + docParams.put(DesignServiceConstants.ARTIFACT_NAME, artifact_name); + docParams.put(DesignServiceConstants.ARTIFACT_CONTENTS, artifact_contents); + + + json.put(DesignServiceConstants.REQUEST_INFORMATION, requestInfo); + json.put(DesignServiceConstants.DOCUMENT_PARAMETERS, docParams); + log.info("Final data =" + json.toString()); + return String.format("{\"input\": %s}", json.toString()); + } + + public HashMap execute(String payload, String rpc) throws Exception{ + log.info("Configuring Rest Operation for Payload " + payload + " RPC : " + rpc ); + HashMap outputMessage = new HashMap(); + Client client = null; + WebResource webResource = null; + ClientResponse clientResponse = null; + String responseDataType=MediaType.APPLICATION_JSON; + String requestDataType=MediaType.APPLICATION_JSON; + + try{ + DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); + System.setProperty("jsse.enableSNIExtension", "false"); + SSLContext sslContext = null; + SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); + sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); + defaultClientConfig.getProperties().put( + com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, + new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); + client = Client.create(defaultClientConfig); + client.addFilter(new HTTPBasicAuthFilter(props.getProperty("appc.upload.user"), props.getProperty("appc.upload.pass"))); + webResource = client.resource(new URI(props.getProperty("appc.upload.provider.url"))); + webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); + + log.info("Starting Rest Operation....."); + if(HttpMethod.GET.equalsIgnoreCase(rpc)){ + clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); + }else if(HttpMethod.POST.equalsIgnoreCase(rpc)){ + clientResponse = webResource.type(requestDataType).post(ClientResponse.class, payload); + }else if(HttpMethod.PUT.equalsIgnoreCase(rpc)){ + clientResponse = webResource.type(requestDataType).put(ClientResponse.class,payload); + }else if(HttpMethod.DELETE.equalsIgnoreCase(rpc)){ + clientResponse = webResource.delete(ClientResponse.class); + } + + if(!(clientResponse.getStatus() == 200)) + throw new Exception("HTTP error code : " + clientResponse.getStatus()); + + + log.info("Completed Rest Operation....."); + + }catch (Exception e) { + e.printStackTrace(); + log.debug("failed in RESTCONT Action with falut message :"+e.getMessage()); + throw new Exception("Error While Sending Rest Request" + e.getMessage()); + } + finally { + // clean up. + webResource = null; + if(client != null){ + client.destroy(); + client = null; + } + } + + return outputMessage; + } + private String getRandom() { + SecureRandom random = new SecureRandom(); + int num = random.nextInt(100000); + String formatted = String.format("%05d", num); + return formatted; + } + + private HostnameVerifier getHostnameVerifier() { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { + return true; + } + }; + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/DesignServiceConstants.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/DesignServiceConstants.java new file mode 100644 index 000000000..9ad5e10ac --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/DesignServiceConstants.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services.util; + +public class DesignServiceConstants { + + public static String STRING_ENCODING = "utf-8"; + public static String Y = "Y"; + public static String N = "N"; + public static String DATA_TYPE_TEXT = "TEXT"; + public static String DATA_TYPE_JSON = "JSON"; + public static String DATA_TYPE_XML = "XML"; + public static String DATA_TYPE_YAML = "YAML"; + public static String DATA_TYPE_VELOCITY = "VELOCITY"; + public static String DATA_TYPE_SQL = "SQL"; + + public static final String GETDESIGNS = "getDesigns"; + public static final String UPLOADARTIFACTS = "uploadArtifacts"; + public static final String VALIDATETEMPLATE = "validateTemplate"; + public static final String GETSTATUS = "getStatus"; + public static final String SETSTATUS = "setStatus"; + public static final String GETGUIREFERENCE = "getGUIReference"; + public static final String GETARTIFACTREFERENCE = "getArtifactReference"; + public static final String GETAAIDATA = "getAAIData"; + public static final String GETINSTARDATA = "getInstarData"; + public static final String PUBLISHARTIFACTS = "publishdArtifacts"; + public static final String ADDINCART = "addInCart"; + + public static final String SUCCESS = "success"; + public static final String DESINGTIME = "DesignTime"; + public static final String RUNTIME = "RunTime"; + public static final String APPC_FLOW_CONTROLLER = "/appc-flow-controller.properties"; + public static final String VNF_TYPE = "vnf-type"; + public static final String ACTION = "action"; + public static final String VNFC_TYPE = "vnfc-type"; + public static final String VM_INSTANCE = "vm-instance"; + public static final String VM = "vm"; + public static final String VNFC = "vnfc"; + + public static final String DOCUMENT_PARAMETERS = "document-parameters"; + public static final String SERVICE_UUID = "service-uuid"; + public static final String DISTRIBUTION_ID = "distribution-id"; + + public static final String SERVICE_NAME = "service-name"; + public static final String SERVICE_DESCRIPTION ="service-description"; + public static final String SERVICE_ARTIFACTS = "service-artifacts"; + public static final String RESOURCE_UUID ="resource-uuid"; + public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name"; + public static final String REOURCE_NAME = "resource-name"; + public static final String RESOURCE_VERSOIN ="resource-version"; + public static final String RESOURCE_TYPE= "resource-type"; + public static final String ARTIFACT_UUID ="artifact-uuid"; + public static final String ARTIFACT_NAME = "artifact-name"; + + public static final String ARTIFACT_VERSOIN = "artifact-version"; + public static final String ARTIFACT_DESRIPTION = "artifact-description"; + public static final String ARTIFACT_CONTENTS = "artifact-contents"; + public static final String REQUEST_INFORMATION = "request-information"; + public static final String INTERNAL_VERSION = "internal-versoin"; + + + + public static final String DB_DT_ARTIFACT_TRACKING = "DT_ARTIFACT_TRACKING"; + public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; + public static final String SCHEMA_SDNCTL = "SDNCTL"; + public static final String GETARTIFACT = "getArtifact"; + public static final String USER_ID = "userID"; + public static final String ARTIFACT_TYPE = "artifact-type"; + public static final String STATUS = "status"; + public static final String UPLOADARTIFACT = "uploadArtifact"; + public static final String REQUETS_ID = "request-id"; + public static final String REQUEST_ACTION = "request-action"; + public static final String SOURCE = "source"; + public static final String DESIGN_SERVICE_PROPERTIES = "designService.properties"; + public static final String DESIGN_TOOL = "Design-tool"; + public static final String TECHNOLOGY = "technology"; + public static final String PROTOCOL = "protocol"; + public static final String SETPROTOCOLREFERENCE = "setProtocolReference"; + public static final String ACTION_LEVEL = "action-level"; + public static final String TEMPLATE = "template"; + public static final String SETINCART = "setInCart"; + public static final String INCART = "inCart"; + public static final String STOREPASSWORD = "storeProperty"; + } diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/EscapeUtils.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/EscapeUtils.java new file mode 100644 index 000000000..80f756f3a --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/EscapeUtils.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services.util; + +import org.apache.commons.lang3.StringUtils; + +public class EscapeUtils { + + public EscapeUtils() { + // TODO Auto-generated constructor stub + } + + public static String escapeSql(String str) { + if (str == null) { + return null; + } + String searchList[] = new String[]{"'","\\", "\"" }; + String replacementList[] = new String[]{ "''","\\\\" ,"\\\""}; + return StringUtils.replaceEach(str,searchList, replacementList); + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/SecureRestClientTrustManager.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/SecureRestClientTrustManager.java new file mode 100644 index 000000000..8e31d9540 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/services/util/SecureRestClientTrustManager.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.services.util; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.X509TrustManager; + + +public class SecureRestClientTrustManager implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public boolean isClientTrusted(X509Certificate[] arg0) { + return true; + } + + public boolean isServerTrusted(X509Certificate[] arg0) { + return true; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorResponseProcessor.java new file mode 100644 index 000000000..faea6a5ee --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorResponseProcessor.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import org.onap.appc.design.services.impl.DesignServicesImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ValidatorResponseProcessor { + + private static final Logger log = LoggerFactory.getLogger(ValidatorResponseProcessor.class); + public String parseResponse(Object execute, String action) { + return null; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorService.java new file mode 100644 index 000000000..6660dd825 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/validator/ValidatorService.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.validation.Validator; + +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.resource.loader.StringResourceLoader; +import org.apache.velocity.runtime.resource.util.StringResourceRepository; +import org.onap.appc.design.services.util.DesignServiceConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; +import com.fasterxml.jackson.dataformat.yaml.snakeyaml.introspector.BeanAccess; + +public class ValidatorService { + + private static final Logger log = LoggerFactory.getLogger(ValidatorService.class); + public String execute(String action, String payload, String dataType) throws Exception { + + String validateResponse = null; + log.info("Received validation for action= " + action + "Data :" + payload + " dataType = " + dataType); + if(dataType.equals(DesignServiceConstants.DATA_TYPE_XML)) + validateResponse = validateXML(payload); + else if(dataType.equals(DesignServiceConstants.DATA_TYPE_JSON)) + validateResponse = validateJOSN(payload); + else if(dataType.equals(DesignServiceConstants.DATA_TYPE_VELOCITY)) + validateResponse = validateVelocity(payload); + else if(dataType.equals(DesignServiceConstants.DATA_TYPE_YAML)) + validateResponse = validateYAML(payload); + + return validateResponse; + + } + + private String validateYAML(String payload) throws Exception { + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + try{ + InputStream is = new ByteArrayInputStream(payload.getBytes()); + + Reader in = new InputStreamReader(is); + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + yaml.load(in); + return DesignServiceConstants.SUCCESS; + } + catch(Exception e){ + log.error("Not a Valid YAML Format "); + throw e; + } + + } + + private String validateVelocity(String payload) { + + try{ + VelocityEngine engine = new VelocityEngine(); + engine.setProperty(Velocity.RESOURCE_LOADER, "string"); + engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); + engine.addProperty("string.resource.loader.repository.static", "false"); + engine.init(); + StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); + repo.putStringResource("TestTemplate", payload); + //Template t = ve.getTemplate(payload); + Template t = engine.getTemplate("TestTemplate"); + + return DesignServiceConstants.SUCCESS; + } + catch(ResourceNotFoundException e ){ + log.error("Not a Valid Velocity Template "); + throw e; + } + catch(ParseErrorException pe){ + log.error("Not a Valid Velocity Template "); + throw pe; + } + catch(MethodInvocationException mi){ + log.error("Not a Valid Velocity Template "); + throw mi; + } + } + + private String validateJOSN(String payload) throws Exception { + + try{ + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.readTree(payload); + return DesignServiceConstants.SUCCESS; + } catch(JsonProcessingException e){ + log.error("Not a Valid JOSN file "); + throw e; + } + + } + + private String validateXML(String payload) throws IOException, SAXException, ParserConfigurationException { + + try{ + + DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = dBF.newDocumentBuilder(); + InputSource is = new InputSource(payload); + builder.parse(new InputSource(new ByteArrayInputStream(payload.getBytes("utf-8")))); + return DesignServiceConstants.SUCCESS; + + } catch(ParserConfigurationException e){ + log.info("Error While parsing Payload : " + e.getMessage()); + throw e; + } + catch(SAXException se){ + log.info("Error While parsing Payload : " + se.getMessage()); + throw se; + } + catch(IOException io){ + log.info("Error While parsing Payload : " + io.getMessage()); + throw io; + } + } +} + diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XInterfaceService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XInterfaceService.java new file mode 100644 index 000000000..157e52937 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XInterfaceService.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.xinterface; + +import java.io.File; +import java.io.IOException; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; + +public class XInterfaceService { + + + public String execute(String action, String payload) throws IOException { + //Remove this once hte interfaces are up and running + File targetFile = new File("/tmp/" + action + "-response.txt" ); + String interfaceResponse = Files.toString(targetFile, Charsets.UTF_8); + return interfaceResponse; + } + +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XResponseProcessor.java new file mode 100644 index 000000000..aa72e2f09 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/main/java/org/onap/appc/design/xinterface/XResponseProcessor.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.xinterface; + +import java.io.File; +import java.io.IOException; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; + +public class XResponseProcessor { + + public String parseResponse(Object execute, String action) { + return null; + } +} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/ArtifactInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/ArtifactInfo.java deleted file mode 100644 index 53f6f02fb..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/ArtifactInfo.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ArtifactInfo { - - @JsonProperty("artifact-content") - String artifact_content; - - public String getArtifact_content() { - return artifact_content; - } - - public void setArtifact_content(String artifact_content) { - this.artifact_content = artifact_content; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignInfo.java deleted file mode 100644 index a6d2ba24b..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignInfo.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class DesignInfo{ - - @JsonProperty("vnf-type") - String vnf_type; - - @JsonProperty("vnfc-type") - String vnfc_type; - - @JsonProperty("protocol") - String protocol; - - @JsonProperty("incart") - String inCart; - - @JsonProperty("action") - String action; - - @JsonProperty("artifact-name") - String artifact_name; - - - @JsonProperty("artifact-type") - String artifact_type; - - public String getArtifact_type() { - return artifact_type; - } - - public void setArtifact_type(String artifact_type) { - this.artifact_type = artifact_type; - } - - public String getArtifact_name() { - return artifact_name; - } - - public void setArtifact_name(String artifact_name) { - this.artifact_name = artifact_name; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getVnf_type() { - return vnf_type; - } - - public void setVnf_type(String vnf_type) { - this.vnf_type = vnf_type; - } - - public String getVnfc_type() { - return vnfc_type; - } - - public void setVnfc_type(String vnfc_type) { - this.vnfc_type = vnfc_type; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getInCart() { - return inCart; - } - - public void setInCart(String inCart) { - this.inCart = inCart; - } - - @Override - public String toString() { - return "DesignInfo [vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol=" + protocol + ", inCart=" - + inCart + "]"; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignRequest.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignRequest.java deleted file mode 100644 index d61de0282..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignRequest.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.data; - -import java.io.File; -import java.net.URL; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.onap.appc.design.services.util.DesignServiceConstants; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -public class DesignRequest{ - - - @JsonProperty("userID") - String userId ; - - @JsonProperty("vnf-type") - String vnf_type; - - @JsonProperty("vnfc-type") - String vnfc_type; - - @JsonProperty("protocol") - String protocol; - - @JsonProperty("action") - String action; - - @JsonProperty("artifact-name") - String artifact_name; - - @JsonProperty("artifact-contents") - String artifact_contents ; - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getVnf_type() { - return vnf_type; - } - - public void setVnf_type(String vnf_type) { - this.vnf_type = vnf_type; - } - - public String getVnfc_type() { - return vnfc_type; - } - - public void setVnfc_type(String vnfc_type) { - this.vnfc_type = vnfc_type; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getArtifact_name() { - return artifact_name; - } - - public void setArtifact_name(String artifact_name) { - this.artifact_name = artifact_name; - } - - public String getArtifact_contents() { - return artifact_contents; - } - - public void setArtifact_contents(String artifact_contents) { - this.artifact_contents = artifact_contents; - } - - @Override - public String toString() { - return "DesignRequest [userId=" + userId + ", vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol=" - + protocol + ", action=" + action + ", artifact_name=" + artifact_name + ", artifact_contents=" - + artifact_contents + "]"; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignResponse.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignResponse.java deleted file mode 100644 index 559620d9e..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/DesignResponse.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.data; - -import java.util.List; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class DesignResponse{ - - - @JsonProperty("userID") - String userId ; - - @JsonProperty("designInfo") - List designInfoList; - - @JsonProperty("statusInfo") - List statusInfoList; - - @JsonProperty("artifactInfo") - List artifactInfo; - - - public List getArtifactInfo() { - return artifactInfo; - } - - public void setArtifactInfo(List artifactInfo) { - this.artifactInfo = artifactInfo; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public List getDesignInfoList() { - return designInfoList; - } - - public void setDesignInfoList(List designInfoList) { - this.designInfoList = designInfoList; - } - - public List getStatusInfoList() { - return statusInfoList; - } - - public void setStatusInfoList(List statusInfoList) { - this.statusInfoList = statusInfoList; - } -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/StatusInfo.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/StatusInfo.java deleted file mode 100644 index 6d4b1a5a1..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/data/StatusInfo.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.data; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class StatusInfo{ - - @JsonProperty("vnf-type") - String vnf_type; - - @JsonProperty("vnfc-type") - String vnfc_type; - - @JsonProperty("action") - String action; - - @JsonProperty("artifact-status") - String artifact_status; - - @JsonProperty("action-status") - String action_status; - - public String getVnf_type() { - return vnf_type; - } - - public void setVnf_type(String vnf_type) { - this.vnf_type = vnf_type; - } - - public String getVnfc_type() { - return vnfc_type; - } - - public void setVnfc_type(String vnfc_type) { - this.vnfc_type = vnfc_type; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getArtifact_status() { - return artifact_status; - } - - public void setArtifact_status(String artifact_status) { - this.artifact_status = artifact_status; - } - - public String getAction_status() { - return action_status; - } - - public void setAction_status(String action_status) { - this.action_status = action_status; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbResponseProcessor.java deleted file mode 100644 index e697a9d4f..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbResponseProcessor.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.dbervices; - -import org.onap.appc.design.services.util.DesignServiceConstants; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DbResponseProcessor { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DbResponseProcessor.class); - public String parseResponse(String dbresposne, String action) throws Exception { - - log.info("Starting Parsing the response for action : " + action + "\n data " + dbresposne ); - String response ; - switch (action) { - case DesignServiceConstants.GETDESIGNS: - response = getDesignsResponse(dbresposne); - break; - case DesignServiceConstants.ADDINCART: - response = getAddInCartResponse(dbresposne); - break ; - case DesignServiceConstants.GETARTIFACTREFERENCE: - response= getArtifactReferenceResponse(dbresposne); - break; - case DesignServiceConstants.GETARTIFACT: - response= getArtifactResponse(dbresposne); - break; - case DesignServiceConstants.GETGUIREFERENCE: - response= getGuiReferenceResponse(dbresposne); - break; - case DesignServiceConstants.GETSTATUS: - response= getStatusResponse(dbresposne); - break; - case DesignServiceConstants.UPLOADARTIFACT: - response= getsetStatusResponse(dbresposne); - break; - case DesignServiceConstants.SETPROTOCOLREFERENCE: - response= getsetStatusResponse(dbresposne); - break; - case DesignServiceConstants.SETINCART: - response= getsetStatusResponse(dbresposne); - break; - default: - log.error("Action " + action + " Not Supported by response Parser"); - throw new Exception(" Action " + action + " not found while processing request "); - - } - return response; - - } - - private String getArtifactResponse(String dbresposne) { - // TODO Auto-generated method stub - return dbresposne; - } - - private String getsetStatusResponse(String dbresposne) { - // TODO Auto-generated method stub - return null; - } - - private String getStatusResponse(String dbresposne) { - log.info("Returning reposne from Response Parser " + dbresposne); - return dbresposne; - } - - private String getGuiReferenceResponse(String dbresposne) { - // TODO Auto-generated method stub - return null; - } - - private String getArtifactReferenceResponse(String dbresposne) { - // TODO Auto-generated method stub - return null; - } - - private String getAddInCartResponse(String dbresposne) { - // TODO Auto-generated method stub - return null; - } - - private String getDesignsResponse(String dbresposne) { - return dbresposne; - - } -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbService.java deleted file mode 100644 index a2349196f..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DbService.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.dbervices; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Properties; -import java.util.UUID; - -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.DbLibService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbService { - - private static final Logger Log = LoggerFactory.getLogger(DbService.class); - private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DBResourceManager"; - DbLibService dblibSvc = null; - String errorMsg = null; - - public DbService() throws Exception { - DbLibService dblibSvc = null; - Log.info("Initializing DbService service"); - try - { - dblibSvc = getDbLibService(); - if (dblibSvc == null) { - Log.error("Got Exception While getting DB Connection"); - throw new Exception("Got Exception While getting DB Connection"); - } - this.dblibSvc = dblibSvc; - } - catch (Exception e) { - Log.error(e.getMessage()); - throw e; - } - } - - private static DbLibService getDbLibService() { - - DbLibService dblibSvc = null; - BundleContext bctx = null; - ServiceReference sref = null; - - Bundle bundle = FrameworkUtil.getBundle(SvcLogicService.class); - - if (bundle != null) { - bctx = bundle.getBundleContext(); - } - - if (bctx != null) { - Log.debug("Getting bundle Context"); - sref = bctx.getServiceReference(DBLIB_SERVICE); - } - - if (sref == null) { - Log.warn("Could not find service reference for DBLib service"); - - } else { - dblibSvc = (DbLibService) bctx.getService(sref); - if (dblibSvc == null) { - Log.warn("DBLIB_SERVICE is null"); - } - } - if (dblibSvc == null) { - try { - dblibSvc = new DBResourceManager(System.getProperties()); - } catch (Exception e) { - Log.error("Caught exception trying to create db service", e); - } - - if (dblibSvc == null) { - Log.warn("Could not create new DBResourceManager"); - } - } - return (dblibSvc); - } - - public ResultSet getDBData(String query) throws Exception { - ResultSet resultSet; - StringBuilder sqlBuilder = new StringBuilder(query); - Log.info("Query: " + sqlBuilder.toString()); - try { - resultSet = dblibSvc.getData(sqlBuilder.toString(), null, null); - } catch (Exception e) { - Log.error("SQL query "+sqlBuilder+" :: " + e.getMessage()); - throw e; - } - return resultSet; - } - - public ResultSet getDBData(String query, ArrayList paramList) throws Exception { - ResultSet resultSet; - StringBuilder sqlBuilder = new StringBuilder(query); - Log.info("Query :" + sqlBuilder.toString()); - try { - resultSet = dblibSvc.getData(sqlBuilder.toString(), paramList, null); - } catch (Exception expObj) { - Log.error("query "+sqlBuilder+" :: " + expObj.getMessage()); - throw expObj; - } - return resultSet; - } - - public boolean updateDBData(String query, ArrayList paramList) throws Exception { - boolean update; - StringBuilder sqlBuilder = new StringBuilder(query); - Log.info("Query :" + sqlBuilder.toString()); - try { - update = dblibSvc.writeData(sqlBuilder.toString(), paramList, null); - } catch (Exception expObj) { - Log.error("query "+sqlBuilder+" :: " + expObj.getMessage()); - throw expObj; - } - return update; - } -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DesignDBService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DesignDBService.java deleted file mode 100644 index 64251027f..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/DesignDBService.java +++ /dev/null @@ -1,645 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.dbervices; - -import java.io.IOException; -import java.security.SecureRandom; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.onap.appc.design.data.ArtifactInfo; -import org.onap.appc.design.data.DesignInfo; -import org.onap.appc.design.data.DesignResponse; -import org.onap.appc.design.data.StatusInfo; -import org.onap.appc.design.services.util.ArtifactHandlerClient; -import org.onap.appc.design.services.util.DesignServiceConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -public class DesignDBService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DesignDBService.class); - private SvcLogicResource serviceLogic; - private static DesignDBService dgGeneralDBService = null; - private static DBResourceManager jdbcDataSource; - - DbService dbservice = null; - private static Properties props; - public static DesignDBService initialise() { - if (dgGeneralDBService == null) { - dgGeneralDBService = new DesignDBService(); - } - return dgGeneralDBService; - } - private DesignDBService() { - if (serviceLogic == null) { - serviceLogic = new SqlResource(); - } - } - - public String execute(String action, String payload, String requestID) throws Exception { - - log.info("Received execute request for action : " + action + " with Payload : "+ payload ); - RequestValidator.validate(action, payload); - String response = null; - dbservice = new DbService(); - switch (action) { - case DesignServiceConstants.GETDESIGNS: - response = getDesigns(payload,requestID ); - break; - case DesignServiceConstants.ADDINCART: - response= setInCart(payload, requestID); - break ; - case DesignServiceConstants.GETARTIFACTREFERENCE: - response= getArtifactReference(payload, requestID); - break; - case DesignServiceConstants.GETARTIFACT: - response= getArtifact(payload, requestID); - break; - case DesignServiceConstants.GETGUIREFERENCE: - response= getGuiReference(payload, requestID); - break; - case DesignServiceConstants.GETSTATUS: - response= getStatus(payload, requestID); - break; - case DesignServiceConstants.SETSTATUS: - response= setStatus(payload, requestID); - break; - case DesignServiceConstants.UPLOADARTIFACT: - response= uploadArtifact(payload, requestID); - break; - case DesignServiceConstants.SETPROTOCOLREFERENCE: - response= setProtocolReference(payload, requestID); - break; - default: - throw new Exception(" Action " + action + " not found while processing request "); - - } - return response; - } - - private String setInCart(String payload, String requestID) throws Exception { - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get(DesignServiceConstants.INCART).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - - String queryString = "UPDATE DT_ARTIFACT_TRACKING SET INCART= ? WHERE ASDC_REFERENCE_ID IN " - + " (SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE_ID WHERE VNF_TYPE = ? " ; - - if(payloadObject.get(DesignServiceConstants.VNF_TYPE) != null &&! payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) { - queryString = queryString + " AND VNFC_TYPE = ? ) AND USER = ? " ; - argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); - } - else{ - queryString = queryString + " ) AND USER = ? " ; - } - - argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); - - log.info("Query String :" + queryString); - boolean data = dbservice.updateDBData(queryString, argList); - - if(!data) - throw new Exception("Error while updating ProtocolReference"); - - return "{\"update\" : \"success\" } "; - - } - private String setProtocolReference(String payload, String requestID) throws Exception { - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - - argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue()); - - String queryString = " DELETE FROM PROTOCOL_REFERENCE WHERE ACTION = ? AND ACTION_LEVEL AND VNF_TYPE= ? AND PROTOCOL = ? " ; - - log.info("Delete Query String :" + queryString); - boolean data = dbservice.updateDBData(queryString, argList); - - log.info("Record Deleted"); - - if((payloadObject.get(DesignServiceConstants.TEMPLATE) != null && !payloadObject.get(DesignServiceConstants.TEMPLATE).textValue().isEmpty())) - argList.add(payloadObject.get(DesignServiceConstants.TEMPLATE).textValue()); - else - argList.add("NO"); - - String insertString = "INSERT INTO PROTOCOL_REFERENCE VALUES (?,?,?,?,?,SYSDATE()) "; - - if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && ! payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ - queryString = queryString + " AND VNFC_TYPE = ? )" ; - } - else{ - queryString = queryString + " ) "; - } - log.info("Query String :" + queryString); - data = dbservice.updateDBData(queryString, argList); - - if(!data) - throw new Exception("Error while updating ProtocolReference"); - - return "{\"update\" : \"success\" } "; - } - private String uploadArtifact(String payload, String requestID) throws Exception { - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - log.info("Got upload Aritfact with Payload : " + payloadObject.asText()); - try{ - ArtifactHandlerClient ac = new ArtifactHandlerClient(); - String requestString = ac.createArtifactData(payload, requestID); - ac.execute(requestString, "POST"); - int sdc_artifact_id = getSDCArtifactIDbyRequestID(requestID); - int sdc_reference_id = getSDCReferenceID(payload); - createArtifactTrackingRecord(payload, requestID,sdc_artifact_id, sdc_reference_id ); - String status = getDataFromActionStatus(payload, "STATUS"); - if(status == null || status.isEmpty()) - setActionStatus(payload, "Not Tested"); - linkstatusRelationShip(sdc_artifact_id,sdc_reference_id, payload); - - } - catch(Exception e){ - e.printStackTrace(); - throw e; - } - return "{\"update\" : \"success\" } "; - - } - - private void linkstatusRelationShip(int sdc_artifact_id, int sdc_reference_id, String payload) throws Exception { - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(String.valueOf(sdc_artifact_id)); - argList.add(String.valueOf(sdc_reference_id)); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); - - String queryString = "INSERT INTO DT_STATUS_RELATIONSHIP (DT_ARTIFACT_TRACKING_ID,DT_ACTION_STATUS_ID) VALUES " + - "(( SELECT DT_ARTIFACT_TRACKING_ID FROM DT_ARTIFACT_TRACKING WHERE ASDC_ARTIFACTS_ID = ? AND ASDC_REFERENCE_ID = ? ) , " - + "( SELECT DT_ACTION_STATUS_ID FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? " ; - - if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && ! payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ - queryString = queryString + " AND VNFC_TYPE = ? ) )" ; - } - else{ - queryString = queryString + " ) ) "; - } - log.info("Query String :" + queryString); - boolean data = dbservice.updateDBData(queryString, argList); - - if(!data) - throw new Exception("Error while updating RealtionShip table"); - - } - private int getSDCReferenceID(String payload) throws Exception { - - String vnfc_type = null; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - - argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue()); - - String queryString = " SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE WHERE VNF_TYPE = ? " - + " AND ARTIFACT_TYPE = ? AND ARTIFACT_NAME = ? " ; - - if(payloadObject.get(DesignServiceConstants.ACTION) != null && !payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()){ - argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); - queryString = queryString + " AND ACTION = ? "; - } - if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ - argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); - queryString = queryString + " AND VNFC_TYPE = ? "; - - } - - log.info("Query String :" + queryString); - ResultSet data = dbservice.getDBData(queryString, argList); - int sdc_reference_id = 0; - while(data.next()) { - sdc_reference_id = data.getInt("ASDC_REFERENCE_ID"); - } - log.info("Got sdc_reference_id = " + sdc_reference_id ); - return sdc_reference_id; - - } - - private String getDataFromActionStatus(String payload, String dataValue) throws Exception { - String status = null ; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); - String queryString = " SELECT " + dataValue + " FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? "; - if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ - argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); - queryString = queryString + " AND VNFC_TYPE = ? "; - } - log.info("Query String :" + queryString); - ResultSet data = dbservice.getDBData(queryString, argList); - while(data.next()) { - status = data.getString("STATUS"); - } - log.info("DT_ACTION_STATUS Status = " + status ); - return status; - } - - private boolean setActionStatus(String payload, String status) throws Exception { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue()); - argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue()); - - - String insertQuery = " INSERT INTO DT_ACTION_STATUS (ACTION, VNF_TYPE, VNFC_TYPE, USER, TECHNOLOGY, UPDATED_DATE, STATUS) VALUES (?,?,?,?,?,sysdate() , ?); "; - if(payloadObject.get(DesignServiceConstants.VNFC_TYPE) !=null && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()){ - argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue()); - } - else{ - argList.add(null); - } - argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); - if(payloadObject.get(DesignServiceConstants.TECHNOLOGY) !=null && !payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()){ - argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue()); - } - else{ - argList.add(null); - } - argList.add(status); - - boolean updateStatus = dbservice.updateDBData(insertQuery, argList); - if(!updateStatus) - throw new Exception("Error while updating Action Status"); - return updateStatus; - } - - private void createArtifactTrackingRecord(String payload, String requestID, int sdc_artifact_id, int sdc_reference_id) throws Exception { - String vnfc_type = null; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - - ArrayList argList = new ArrayList<>(); - argList.add(String.valueOf(sdc_artifact_id)); - argList.add(String.valueOf(sdc_reference_id)); - argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue()); - if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null &&! payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) - argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue()); - else - argList.add(""); - - if (payloadObject.get(DesignServiceConstants.PROTOCOL) != null &&! payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) - argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue()); - else - argList.add(""); - - - String queryString = "INSERT INTO DT_ARTIFACT_TRACKING (ASDC_ARTIFACTS_ID, ASDC_REFERENCE_ID, USER, TECHNOLOGY, CREATION_DATE, UPDATED_DATE, ARTIFACT_STATUS, PROTOCOL, IN_CART) VALUES (? , ? , ?, ?, sysdate() , sysdate(), 'Created', ? ,'N' )" ; - - log.info("Query String :" + queryString); - boolean data = dbservice.updateDBData(queryString, argList); - if(!data) - throw new Exception("Error Updating DT_ARTIFACT_TRACKING "); - - - } - - private int getSDCArtifactIDbyRequestID(String requestID) throws Exception { - log.info("Starting getArtifactIDbyRequestID DB Operation"); - int artifact_id = 0; - try{ - ArrayList argList = new ArrayList<>(); - argList.add("TLSUUID" + requestID); - String queryString = " SELECT ASDC_ARTIFACTS_ID FROM ASDC_ARTIFACTS where SERVICE_UUID = ? "; - log.info("Query String :" + queryString); - ResultSet data = dbservice.getDBData(queryString, argList); - while(data.next()){ - artifact_id = data.getInt("ASDC_ARTIFACTS_ID"); - } - } - catch(Exception e){ - e.printStackTrace(); - throw e; - } - log.info("Got SDC_ARTIFACTS_ID As :" + artifact_id); - return artifact_id; - } - - - private String getArtifact(String payload, String requestID) throws Exception { - String fn = "DBService.getStatus "; - log.info("Starting getArtifact DB Operation"); - try{ - String vnfc_type = null; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get("artifact-name").textValue()); - argList.add(payloadObject.get("artifact-type").textValue()); - - String queryString = "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS where " + - " ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ? " ; - - log.info("Query String :" + queryString); - ResultSet data = dbservice.getDBData(queryString, argList); - String artifact_content = null; - int hightestVerion = 0 ; - while(data.next()) { - int version = data.getInt("INTERNAL_VERSION"); - if(hightestVerion < version) - artifact_content = data.getString("ARTIFACT_CONTENT"); - } - - if(artifact_content == null || artifact_content.isEmpty()) - throw new Exception("Sorry !!! I dont have any artifact Named : " + payloadObject.get("artifact-name").textValue()); - DesignResponse designResponse = new DesignResponse(); - designResponse.setUserId(payloadObject.get("userID").textValue()); - List artifactInfoList = new ArrayList(); - ArtifactInfo artifactInfo = new ArtifactInfo(); - artifactInfo.setArtifact_content(artifact_content); - artifactInfoList.add(artifactInfo); - designResponse.setArtifactInfo(artifactInfoList); - - ObjectMapper mapper = new ObjectMapper(); - String jsonString = mapper.writeValueAsString(designResponse); - log.info("Info : " + jsonString); - return jsonString; - } - catch(SQLException e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - catch(Exception e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - - } - private String setStatus(String payload, String requestID) throws Exception { - String fn = "DBService.getStatus "; - log.info("Starting getStatus DB Operation"); - try{ - String vnfc_type = null; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - - - ArrayList argList = new ArrayList<>(); - argList.add(payloadObject.get("artifact_status").textValue()); - argList.add(payloadObject.get("action_status").textValue()); - - argList.add(payloadObject.get("userID").textValue()); - argList.add(payloadObject.get("vnf-type").textValue()); - - String queryString = " UPDATE DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR SET DAT.ARTIFACT_STATUS = ? , DAS.DT_ACTION_STATUS = ? " - + " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID " - + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ? " - + " and DAS.VNF_TYPE = ? " ; - - if(payloadObject.get("vnfc-type") !=null && !payloadObject.get("vnfc-type").textValue().isEmpty()){ - argList.add(payloadObject.get("vnfc-type").textValue()); - queryString = queryString + " and DAS.VNFC_TYPE = ? "; - } - - log.info("Query String :" + queryString); - - DesignResponse designResponse = new DesignResponse(); - designResponse.setUserId(payloadObject.get("userID").textValue()); - List statusInfoList = new ArrayList(); - boolean update = dbservice.updateDBData(queryString, argList); - if(!update) - throw new Exception("Sorry .....Something went wrong while updating the Status"); - - ObjectMapper mapper = new ObjectMapper(); - String jsonString = mapper.writeValueAsString(designResponse); - log.info("Info : " + jsonString); - return jsonString; - } - catch(SQLException e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - catch(Exception e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - } - private String getStatus(String payload, String requestID) throws Exception { - String fn = "DBService.getStatus "; - log.info("Starting getStatus DB Operation"); - try{ - String vnfc_type = null; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - String UserID = payloadObject.get("userID").textValue(); - String vnf_type = payloadObject.get("vnf-type").textValue(); - if(payloadObject.get("vnfc-type") != null ) - vnfc_type = payloadObject.get("vnfc-type").textValue(); - ArrayList argList = new ArrayList<>(); - - argList.add(UserID); - argList.add(vnf_type); - - String queryString = "SELECT DAS.VNF_TYPE, DAS.VNFC_TYPE, DAS.STATUS, DAS.ACTION, DAT.ARTIFACT_STATUS " - + "from DT_ACTION_STATUS DAS , DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR " + - " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID " - + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ? " - + " and DAS.VNF_TYPE = ? " ; - - if(vnfc_type !=null && ! vnfc_type.isEmpty()){ - argList.add(vnfc_type); - queryString = queryString + " and DAS.VNFC_TYPE = ? "; - } - - log.info("Query String :" + queryString); - - DesignResponse designResponse = new DesignResponse(); - designResponse.setUserId(UserID); - List statusInfoList = new ArrayList(); - ResultSet data = dbservice.getDBData(queryString, argList); - while(data.next()) { - StatusInfo statusInfo = new StatusInfo(); - statusInfo.setAction(data.getString("ACTION")); - statusInfo.setAction_status(data.getString("STATUS")); - statusInfo.setArtifact_status(data.getString("ARTIFACT_STATUS")); - statusInfo.setVnf_type(data.getString("VNF_TYPE")); - statusInfo.setVnfc_type(data.getString("VNFC_TYPE")); - statusInfoList.add(statusInfo); - } - - if(statusInfoList.size() < 1) - throw new Exception("OOPS !!!! No VNF information available for VNF-TYPE : " + vnf_type + " for User : " + UserID); - designResponse.setStatusInfoList(statusInfoList); - ObjectMapper mapper = new ObjectMapper(); - String jsonString = mapper.writeValueAsString(designResponse); - log.info("Info : " + jsonString); - return jsonString; - } - catch(SQLException e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - catch(Exception e) - { - log.error("Error while DB operation : " + e.getMessage()); - e.printStackTrace(); - throw e; - } - } - private String getGuiReference(String payload, String requestID) { - // TODO Auto-generated method stub - return null; - } - private String getArtifactReference(String payload, String requestID) { - // TODO Auto-generated method stub - return null; - } - private String getAddInCart(String payload, String requestID) { - // TODO Auto-generated method stub - return null; - } - - // private String getDesigns(String payload, String requestID) throws SQLException, JsonProcessingException, IOException, SvcLogicException { - // - // String fn = "DBService.getDesigns "; - // QueryStatus status = null; - // ObjectMapper objectMapper = new ObjectMapper(); - // JsonNode jnode = objectMapper.readTree(payload); - // String UserId = jnode.get("userID").textValue(); - // SvcLogicContext localContext = new SvcLogicContext(); - // localContext.setAttribute("requestID", requestID); - // localContext.setAttribute("userID", UserId); - // if (serviceLogic != null && localContext != null) { - // String queryString = "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART from " + - // DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , " + DesignServiceConstants.DB_SDC_REFERENCE + - // " AR where DAT.SDC_REFERENCE_ID= AR.SDC_REFERENCE_ID and DAT.USER = $userID" ; - // - // log.info(fn + "Query String : " + queryString); - // try { - // status = serviceLogic.query("SQL", true, null, queryString, null, null, localContext); - // } catch (SvcLogicException e1) { - // // TODO Auto-generated catch block - // e1.printStackTrace(); - // } - // - // if(status.toString().equals("FAILURE")) - // throw new SvcLogicException("Error - while getting FlowReferenceData "); - // - // Properties props = localContext.toProperties(); - // log.info("SvcLogicContext contains the following : " + props.toString()); - // for (Enumeration e = props.propertyNames(); e.hasMoreElements() ; ) { - // String propName = (String) e.nextElement(); - // log.info(propName+" = "+props.getProperty(propName)); - // - // } - // } - // return requestID; - // - // } - - private String getDesigns(String payload, String requestID) throws Exception { - - String fn = "DBService.getDesigns "; - log.info("Starting getDesgins DB Operation"); - - - try{ - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - String UserID = payloadObject.get("userID").textValue(); - ArrayList argList = new ArrayList<>(); - argList.add(UserID); - - String queryString = "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART, AR.ACTION, AR.ARTIFACT_NAME, AR.ARTIFACT_TYPE from " + - DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , " + DesignServiceConstants.DB_SDC_REFERENCE + - " AR where DAT.ASDC_REFERENCE_ID= AR.ASDC_REFERENCE_ID and DAT.USER = ? "; - - DesignResponse designResponse = new DesignResponse(); - designResponse.setUserId(UserID); - List designInfoList = new ArrayList(); - ResultSet data = dbservice.getDBData(queryString, argList); - while(data.next()) { - DesignInfo designInfo = new DesignInfo(); - designInfo.setInCart(data.getString("IN_CART")); - designInfo.setProtocol(data.getString("PROTOCOL")); - designInfo.setVnf_type(data.getString("VNF_TYPE")); - designInfo.setVnfc_type(data.getString("VNFC_TYPE")); - designInfo.setAction(data.getString("ACTION")); - designInfo.setArtifact_type(data.getString("ARTIFACT_TYPE")); - designInfo.setArtifact_name(data.getString("ARTIFACT_NAME")); - designInfoList.add(designInfo); - } - if(designInfoList.size() < 1) - throw new Exception(" Welcome to CDT, Looks like you dont have Design Yet... Lets create some...."); - designResponse.setDesignInfoList(designInfoList); - ObjectMapper mapper = new ObjectMapper(); - String jsonString = mapper.writeValueAsString(designResponse); - log.info("Info : " + jsonString); - return jsonString; - } - catch(Exception e) - { - e.printStackTrace(); - throw e; - } - } - -} - - diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/RequestValidator.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/RequestValidator.java deleted file mode 100644 index c0b710deb..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/dbervices/RequestValidator.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.dbervices; - -import org.onap.appc.design.services.util.ArtifactHandlerClient; -import org.onap.appc.design.services.util.DesignServiceConstants; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class RequestValidator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(RequestValidator.class); - public static void validate(String action, String payload) throws Exception { - log.info("payload" + payload); - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - log.info("payloadObject" + payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS)); - - String errorString = null; - switch (action) { - case DesignServiceConstants.GETDESIGNS: - if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) - errorString = DesignServiceConstants.USER_ID; - break; - case DesignServiceConstants.GETARTIFACT: - if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_TYPE; - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_NAME; - break; - case DesignServiceConstants.GETSTATUS: - if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) - errorString = DesignServiceConstants.USER_ID; - else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - break; - case DesignServiceConstants.SETSTATUS: - if(payloadObject.get(DesignServiceConstants.USER_ID) == null || payloadObject.get(DesignServiceConstants.USER_ID).textValue().isEmpty()) - errorString = DesignServiceConstants.USER_ID; - else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - else if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION; - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_TYPE; - else if(payloadObject.get(DesignServiceConstants.STATUS) == null || payloadObject.get(DesignServiceConstants.STATUS).textValue().isEmpty()) - errorString = DesignServiceConstants.STATUS; - break; - case DesignServiceConstants.UPLOADARTIFACT: - if(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_NAME; - else if(! payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue().contains("reference")){ - if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION; - } - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_VERSOIN; - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS) == null) - errorString = DesignServiceConstants.ARTIFACT_CONTENTS; - else if(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE) == null || payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.ARTIFACT_TYPE; - - else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - - - break; - case DesignServiceConstants.SETPROTOCOLREFERENCE: - if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION; - else if(payloadObject.get(DesignServiceConstants.ACTION_LEVEL) == null || payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION_LEVEL; - else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - else if(payloadObject.get(DesignServiceConstants.PROTOCOL) == null || payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) - errorString = DesignServiceConstants.PROTOCOL; - - case DesignServiceConstants.SETINCART: - if(payloadObject.get(DesignServiceConstants.ACTION) == null || payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION; - else if(payloadObject.get(DesignServiceConstants.ACTION_LEVEL) == null || payloadObject.get(DesignServiceConstants.ACTION_LEVEL).textValue().isEmpty()) - errorString = DesignServiceConstants.ACTION_LEVEL; - else if(payloadObject.get(DesignServiceConstants.VNF_TYPE) == null || payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) - errorString = DesignServiceConstants.VNF_TYPE; - else if(payloadObject.get(DesignServiceConstants.PROTOCOL) == null || payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) - errorString = DesignServiceConstants.PROTOCOL; - break; - default: - throw new Exception(" Action " + action + " not found while processing request "); - - } - if(errorString != null) - throw new Exception(" Missing input parameter :-" + errorString + " -:"); - - } - -} - - diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/propertyServices/PropertyUpdateService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/propertyServices/PropertyUpdateService.java deleted file mode 100644 index 87e84d495..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/propertyServices/PropertyUpdateService.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.propertyServices; - -public class PropertyUpdateService { - - // to set the properties this placeholder will be used. -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/DesignServiceProvider.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/DesignServiceProvider.java deleted file mode 100644 index f41bbac46..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/DesignServiceProvider.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services; - -import java.util.concurrent.Future; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DesignServicesService; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.onap.appc.design.services.impl.DesignServicesImpl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DesignServiceProvider{ - - private static final EELFLogger log = EELFManager.getInstance().getLogger(DesignServiceProvider.class); - - private final DataBroker dataBroker; - private final RpcProviderRegistry rpcProviderRegistry; - private RpcRegistration serviceRegistration; - - - public DesignServiceProvider(final DataBroker dataBroker, RpcProviderRegistry rpcProviderRegistry) { - this.dataBroker = dataBroker; - this.rpcProviderRegistry = rpcProviderRegistry; - } - - /** - * Method called when the blueprint container is created. - */ - public void init() { - // initialize data broker - this.serviceRegistration = this.rpcProviderRegistry.addRpcImplementation(DesignServicesService.class, new DesignServicesImpl()); - log.info("DesignServicesImpl Session Initiated"); - } - - /** - * Method called when the blueprint container is destroyed. - */ - public void close() { - if(this.serviceRegistration != null){ - this.serviceRegistration.close(); - } - log.info("DesignServicesImpl Closed"); - } - - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/impl/DesignServicesImpl.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/impl/DesignServicesImpl.java deleted file mode 100644 index 1787618e6..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/impl/DesignServicesImpl.java +++ /dev/null @@ -1,160 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services.impl; - -import java.util.concurrent.Future; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DbserviceOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.DesignServicesService; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.ValidatorOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.XinterfaceserviceOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.data.DataBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev170627.status.StatusBuilder; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.design.dbervices.DbResponseProcessor; -import org.onap.appc.design.dbervices.DesignDBService; -import org.onap.appc.design.services.util.DesignServiceConstants; -import org.onap.appc.design.validator.ValidatorResponseProcessor; -import org.onap.appc.design.validator.ValidatorService; -import org.onap.appc.design.xinterface.XInterfaceService; -import org.onap.appc.design.xinterface.XResponseProcessor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Futures; - -public class DesignServicesImpl implements DesignServicesService { - - private static final Logger log = LoggerFactory.getLogger(DesignServicesImpl.class); - - @Override - public Future> dbservice(DbserviceInput input) { - - log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + - input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload()); - - - DbserviceOutputBuilder outputBuilder = new DbserviceOutputBuilder(); - DataBuilder databuilder = new DataBuilder(); - StatusBuilder statusBuilder = new StatusBuilder(); - - try{ - DesignDBService dbservices = DesignDBService.initialise(); - DbResponseProcessor responseProcessor = new DbResponseProcessor(); - String response = responseProcessor.parseResponse(dbservices.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload(), input.getDesignRequest().getRequestId()), input.getDesignRequest().getAction()); - log.info("Response in for Design Service : " + response); - databuilder.setBlock(response); - databuilder.setRequestId(input.getDesignRequest().getRequestId()); - statusBuilder.setCode("400"); - statusBuilder.setMessage("success"); - } - catch(Exception e){ - log.error("Error" + e.getMessage()); - e.printStackTrace(); - statusBuilder.setCode("401"); - statusBuilder.setMessage(e.getMessage()); - } - - outputBuilder.setData(databuilder.build()); - outputBuilder.setStatus(statusBuilder.build()); - - RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> xinterfaceservice(XinterfaceserviceInput input) { - log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + - input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload()); - XinterfaceserviceOutputBuilder outputBuilder = new XinterfaceserviceOutputBuilder(); - DataBuilder databuilder = new DataBuilder(); - StatusBuilder statusBuilder = new StatusBuilder(); - try { - - XInterfaceService xInterfaceService = new XInterfaceService(); - XResponseProcessor responseProcessor = new XResponseProcessor(); - String response = responseProcessor.parseResponse(xInterfaceService.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload()), input.getDesignRequest().getAction()); - databuilder.setBlock(response); - databuilder.setRequestId(input.getDesignRequest().getRequestId()); - statusBuilder.setCode("400"); - statusBuilder.setMessage("success"); - } catch (Exception e) { - e.printStackTrace(); - statusBuilder.setCode("401"); - statusBuilder.setMessage(e.getMessage()); - } - outputBuilder.setData(databuilder.build()); - outputBuilder.setStatus(statusBuilder.build()); - - RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> validator(ValidatorInput input) { - log.info("Received Request: " + input.getDesignRequest().getRequestId() + " Action : " + - input.getDesignRequest().getAction() + " with Payload :" + input.getDesignRequest().getPayload() + " and Data Type = " + input.getDesignRequest().getDataType()); - ValidatorOutputBuilder outputBuilder = new ValidatorOutputBuilder(); - StatusBuilder statusBuilder = new StatusBuilder(); - - - try { - if(input.getDesignRequest().getDataType() == null || input.getDesignRequest().getDataType().isEmpty()) - throw new Exception ("Data Type required for validate Serivce"); - if(input.getDesignRequest().getAction()== null || input.getDesignRequest().getAction().isEmpty()) - throw new Exception ("Action required for validate Serivce"); - - - if(! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_JSON) && - ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_YAML) && - ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_XML) && - ! input.getDesignRequest().getDataType().equals(DesignServiceConstants.DATA_TYPE_VELOCITY)) - throw new Exception ("Request Data format " + input.getDesignRequest().getDataType() - + " is not supported by validate Service : Supported data types are : XML, YAML, VELOCITY, JSON "); - - ValidatorService validatorService = new ValidatorService(); - ValidatorResponseProcessor responseProcessor = new ValidatorResponseProcessor(); - String response = validatorService.execute(input.getDesignRequest().getAction(), input.getDesignRequest().getPayload(), input.getDesignRequest().getDataType()); - statusBuilder.setCode("400"); - statusBuilder.setMessage(response); - } catch (Exception e) { - e.printStackTrace(); - statusBuilder.setCode("401"); - statusBuilder.setMessage(e.getMessage()); - } - - outputBuilder.setStatus(statusBuilder.build()); - - RpcResult result = RpcResultBuilder.status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/ArtifactHandlerClient.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/ArtifactHandlerClient.java deleted file mode 100644 index b250faca9..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/ArtifactHandlerClient.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services.util; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.Charset; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Properties; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - - -public class ArtifactHandlerClient { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerClient.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - Properties props = new Properties(); - public ArtifactHandlerClient() throws Exception { - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); - String propFile = propDir + "/" + DesignServiceConstants.DESIGN_SERVICE_PROPERTIES; - InputStream propStream = new FileInputStream(propFile); - try{ - props.load(propStream); - } - catch (Exception e){ - throw new Exception("Could not load properties file " + propFile, e); - } - finally{ - try{ - propStream.close(); - } - catch (Exception e){ - log.warn("Could not close FileInputStream", e); - } - } - } - - public String createArtifactData(String payload, String requestID) throws JsonProcessingException, IOException { - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode payloadObject = objectMapper.readTree(payload); - - ObjectNode json = objectMapper.createObjectNode(); - - String artifact_name = payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue(); - String artifact_version = payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue(); - String artifact_contents = payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS).textValue(); - - ObjectNode requestInfo = objectMapper.createObjectNode(); - - requestInfo.put(DesignServiceConstants.REQUETS_ID, requestID); - requestInfo.put(DesignServiceConstants.REQUEST_ACTION, "StoreSdcDocumentRequest"); - requestInfo.put(DesignServiceConstants.SOURCE, DesignServiceConstants.DESIGN_TOOL); - - String random = getRandom(); - - ObjectNode docParams = objectMapper.createObjectNode(); - - docParams.put(DesignServiceConstants.ARTIFACT_VERSOIN, artifact_version); - docParams.put(DesignServiceConstants.ARTIFACT_NAME, artifact_name); - docParams.put(DesignServiceConstants.ARTIFACT_CONTENTS, artifact_contents); - - - json.put(DesignServiceConstants.REQUEST_INFORMATION, requestInfo); - json.put(DesignServiceConstants.DOCUMENT_PARAMETERS, docParams); - log.info("Final data =" + json.toString()); - return String.format("{\"input\": %s}", json.toString()); - } - - public HashMap execute(String payload, String rpc) throws Exception{ - log.info("Configuring Rest Operation for Payload " + payload + " RPC : " + rpc ); - HashMap outputMessage = new HashMap(); - Client client = null; - WebResource webResource = null; - ClientResponse clientResponse = null; - String responseDataType=MediaType.APPLICATION_JSON; - String requestDataType=MediaType.APPLICATION_JSON; - - try{ - DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); - System.setProperty("jsse.enableSNIExtension", "false"); - SSLContext sslContext = null; - SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); - sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); - defaultClientConfig.getProperties().put( - com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); - client = Client.create(defaultClientConfig); - client.addFilter(new HTTPBasicAuthFilter(props.getProperty("appc.upload.user"), props.getProperty("appc.upload.pass"))); - webResource = client.resource(new URI(props.getProperty("appc.upload.provider.url"))); - webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); - - log.info("Starting Rest Operation....."); - if(HttpMethod.GET.equalsIgnoreCase(rpc)){ - clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); - }else if(HttpMethod.POST.equalsIgnoreCase(rpc)){ - clientResponse = webResource.type(requestDataType).post(ClientResponse.class, payload); - }else if(HttpMethod.PUT.equalsIgnoreCase(rpc)){ - clientResponse = webResource.type(requestDataType).put(ClientResponse.class,payload); - }else if(HttpMethod.DELETE.equalsIgnoreCase(rpc)){ - clientResponse = webResource.delete(ClientResponse.class); - } - - if(!(clientResponse.getStatus() == 200)) - throw new Exception("HTTP error code : " + clientResponse.getStatus()); - - - log.info("Completed Rest Operation....."); - - }catch (Exception e) { - e.printStackTrace(); - log.debug("failed in RESTCONT Action with falut message :"+e.getMessage()); - throw new Exception("Error While Sending Rest Request" + e.getMessage()); - } - finally { - // clean up. - webResource = null; - if(client != null){ - client.destroy(); - client = null; - } - } - - return outputMessage; - } - private String getRandom() { - SecureRandom random = new SecureRandom(); - int num = random.nextInt(100000); - String formatted = String.format("%05d", num); - return formatted; - } - - private HostnameVerifier getHostnameVerifier() { - return new HostnameVerifier() { - @Override - public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { - return true; - } - }; - } -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/DesignServiceConstants.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/DesignServiceConstants.java deleted file mode 100644 index 9ad5e10ac..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/DesignServiceConstants.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services.util; - -public class DesignServiceConstants { - - public static String STRING_ENCODING = "utf-8"; - public static String Y = "Y"; - public static String N = "N"; - public static String DATA_TYPE_TEXT = "TEXT"; - public static String DATA_TYPE_JSON = "JSON"; - public static String DATA_TYPE_XML = "XML"; - public static String DATA_TYPE_YAML = "YAML"; - public static String DATA_TYPE_VELOCITY = "VELOCITY"; - public static String DATA_TYPE_SQL = "SQL"; - - public static final String GETDESIGNS = "getDesigns"; - public static final String UPLOADARTIFACTS = "uploadArtifacts"; - public static final String VALIDATETEMPLATE = "validateTemplate"; - public static final String GETSTATUS = "getStatus"; - public static final String SETSTATUS = "setStatus"; - public static final String GETGUIREFERENCE = "getGUIReference"; - public static final String GETARTIFACTREFERENCE = "getArtifactReference"; - public static final String GETAAIDATA = "getAAIData"; - public static final String GETINSTARDATA = "getInstarData"; - public static final String PUBLISHARTIFACTS = "publishdArtifacts"; - public static final String ADDINCART = "addInCart"; - - public static final String SUCCESS = "success"; - public static final String DESINGTIME = "DesignTime"; - public static final String RUNTIME = "RunTime"; - public static final String APPC_FLOW_CONTROLLER = "/appc-flow-controller.properties"; - public static final String VNF_TYPE = "vnf-type"; - public static final String ACTION = "action"; - public static final String VNFC_TYPE = "vnfc-type"; - public static final String VM_INSTANCE = "vm-instance"; - public static final String VM = "vm"; - public static final String VNFC = "vnfc"; - - public static final String DOCUMENT_PARAMETERS = "document-parameters"; - public static final String SERVICE_UUID = "service-uuid"; - public static final String DISTRIBUTION_ID = "distribution-id"; - - public static final String SERVICE_NAME = "service-name"; - public static final String SERVICE_DESCRIPTION ="service-description"; - public static final String SERVICE_ARTIFACTS = "service-artifacts"; - public static final String RESOURCE_UUID ="resource-uuid"; - public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name"; - public static final String REOURCE_NAME = "resource-name"; - public static final String RESOURCE_VERSOIN ="resource-version"; - public static final String RESOURCE_TYPE= "resource-type"; - public static final String ARTIFACT_UUID ="artifact-uuid"; - public static final String ARTIFACT_NAME = "artifact-name"; - - public static final String ARTIFACT_VERSOIN = "artifact-version"; - public static final String ARTIFACT_DESRIPTION = "artifact-description"; - public static final String ARTIFACT_CONTENTS = "artifact-contents"; - public static final String REQUEST_INFORMATION = "request-information"; - public static final String INTERNAL_VERSION = "internal-versoin"; - - - - public static final String DB_DT_ARTIFACT_TRACKING = "DT_ARTIFACT_TRACKING"; - public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE"; - public static final String SCHEMA_SDNCTL = "SDNCTL"; - public static final String GETARTIFACT = "getArtifact"; - public static final String USER_ID = "userID"; - public static final String ARTIFACT_TYPE = "artifact-type"; - public static final String STATUS = "status"; - public static final String UPLOADARTIFACT = "uploadArtifact"; - public static final String REQUETS_ID = "request-id"; - public static final String REQUEST_ACTION = "request-action"; - public static final String SOURCE = "source"; - public static final String DESIGN_SERVICE_PROPERTIES = "designService.properties"; - public static final String DESIGN_TOOL = "Design-tool"; - public static final String TECHNOLOGY = "technology"; - public static final String PROTOCOL = "protocol"; - public static final String SETPROTOCOLREFERENCE = "setProtocolReference"; - public static final String ACTION_LEVEL = "action-level"; - public static final String TEMPLATE = "template"; - public static final String SETINCART = "setInCart"; - public static final String INCART = "inCart"; - public static final String STOREPASSWORD = "storeProperty"; - } diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/EscapeUtils.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/EscapeUtils.java deleted file mode 100644 index 80f756f3a..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/EscapeUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services.util; - -import org.apache.commons.lang3.StringUtils; - -public class EscapeUtils { - - public EscapeUtils() { - // TODO Auto-generated constructor stub - } - - public static String escapeSql(String str) { - if (str == null) { - return null; - } - String searchList[] = new String[]{"'","\\", "\"" }; - String replacementList[] = new String[]{ "''","\\\\" ,"\\\""}; - return StringUtils.replaceEach(str,searchList, replacementList); - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/SecureRestClientTrustManager.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/SecureRestClientTrustManager.java deleted file mode 100644 index 8e31d9540..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/services/util/SecureRestClientTrustManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.services.util; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.X509TrustManager; - - -public class SecureRestClientTrustManager implements X509TrustManager { - - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public boolean isClientTrusted(X509Certificate[] arg0) { - return true; - } - - public boolean isServerTrusted(X509Certificate[] arg0) { - return true; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorResponseProcessor.java deleted file mode 100644 index faea6a5ee..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorResponseProcessor.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import org.onap.appc.design.services.impl.DesignServicesImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ValidatorResponseProcessor { - - private static final Logger log = LoggerFactory.getLogger(ValidatorResponseProcessor.class); - public String parseResponse(Object execute, String action) { - return null; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorService.java deleted file mode 100644 index 6660dd825..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/validator/ValidatorService.java +++ /dev/null @@ -1,168 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.validation.Validator; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.MethodInvocationException; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.resource.loader.StringResourceLoader; -import org.apache.velocity.runtime.resource.util.StringResourceRepository; -import org.onap.appc.design.services.util.DesignServiceConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.introspector.BeanAccess; - -public class ValidatorService { - - private static final Logger log = LoggerFactory.getLogger(ValidatorService.class); - public String execute(String action, String payload, String dataType) throws Exception { - - String validateResponse = null; - log.info("Received validation for action= " + action + "Data :" + payload + " dataType = " + dataType); - if(dataType.equals(DesignServiceConstants.DATA_TYPE_XML)) - validateResponse = validateXML(payload); - else if(dataType.equals(DesignServiceConstants.DATA_TYPE_JSON)) - validateResponse = validateJOSN(payload); - else if(dataType.equals(DesignServiceConstants.DATA_TYPE_VELOCITY)) - validateResponse = validateVelocity(payload); - else if(dataType.equals(DesignServiceConstants.DATA_TYPE_YAML)) - validateResponse = validateYAML(payload); - - return validateResponse; - - } - - private String validateYAML(String payload) throws Exception { - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - try{ - InputStream is = new ByteArrayInputStream(payload.getBytes()); - - Reader in = new InputStreamReader(is); - Yaml yaml = new Yaml(); - yaml.setBeanAccess(BeanAccess.FIELD); - yaml.load(in); - return DesignServiceConstants.SUCCESS; - } - catch(Exception e){ - log.error("Not a Valid YAML Format "); - throw e; - } - - } - - private String validateVelocity(String payload) { - - try{ - VelocityEngine engine = new VelocityEngine(); - engine.setProperty(Velocity.RESOURCE_LOADER, "string"); - engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName()); - engine.addProperty("string.resource.loader.repository.static", "false"); - engine.init(); - StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT); - repo.putStringResource("TestTemplate", payload); - //Template t = ve.getTemplate(payload); - Template t = engine.getTemplate("TestTemplate"); - - return DesignServiceConstants.SUCCESS; - } - catch(ResourceNotFoundException e ){ - log.error("Not a Valid Velocity Template "); - throw e; - } - catch(ParseErrorException pe){ - log.error("Not a Valid Velocity Template "); - throw pe; - } - catch(MethodInvocationException mi){ - log.error("Not a Valid Velocity Template "); - throw mi; - } - } - - private String validateJOSN(String payload) throws Exception { - - try{ - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.readTree(payload); - return DesignServiceConstants.SUCCESS; - } catch(JsonProcessingException e){ - log.error("Not a Valid JOSN file "); - throw e; - } - - } - - private String validateXML(String payload) throws IOException, SAXException, ParserConfigurationException { - - try{ - - DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = dBF.newDocumentBuilder(); - InputSource is = new InputSource(payload); - builder.parse(new InputSource(new ByteArrayInputStream(payload.getBytes("utf-8")))); - return DesignServiceConstants.SUCCESS; - - } catch(ParserConfigurationException e){ - log.info("Error While parsing Payload : " + e.getMessage()); - throw e; - } - catch(SAXException se){ - log.info("Error While parsing Payload : " + se.getMessage()); - throw se; - } - catch(IOException io){ - log.info("Error While parsing Payload : " + io.getMessage()); - throw io; - } - } -} - diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XInterfaceService.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XInterfaceService.java deleted file mode 100644 index 157e52937..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XInterfaceService.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.xinterface; - -import java.io.File; -import java.io.IOException; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; - -public class XInterfaceService { - - - public String execute(String action, String payload) throws IOException { - //Remove this once hte interfaces are up and running - File targetFile = new File("/tmp/" + action + "-response.txt" ); - String interfaceResponse = Files.toString(targetFile, Charsets.UTF_8); - return interfaceResponse; - } - -} diff --git a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XResponseProcessor.java b/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XResponseProcessor.java deleted file mode 100644 index aa72e2f09..000000000 --- a/appc-inbound/appc-design-services/provider/src/main/java/org/openecomp/appc/design/xinterface/XResponseProcessor.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.xinterface; - -import java.io.File; -import java.io.IOException; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; - -public class XResponseProcessor { - - public String parseResponse(Object execute, String action) { - return null; - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestArifactHandlerClient.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestArifactHandlerClient.java new file mode 100644 index 000000000..9f6622e36 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestArifactHandlerClient.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.design.services.util.ArtifactHandlerClient; +import junit.framework.Assert; +import static org.mockito.Mockito.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Properties; +import org.apache.commons.io.FileUtils; + +public class TestArifactHandlerClient { + + @Test + public void testCreateArtifactData(){ + + try{ + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"00000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": " + + content + + " } "; + String requestID ="0000"; + ArtifactHandlerClient ahi = new ArtifactHandlerClient(); + String value = ahi.createArtifactData(payload, requestID); + Assert.assertTrue(!value.isEmpty()); + }catch(Exception e) + { + } + } + + @Test + public void testExecute(){ + + try{ + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"00000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": " + + content + + " } "; + String rpc = "Post"; + ArtifactHandlerClient ahi = new ArtifactHandlerClient(); + ahi.execute(payload, rpc); + }catch(Exception e) + { + } + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDBService.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDBService.java new file mode 100644 index 000000000..ffc2cadce --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDBService.java @@ -0,0 +1,242 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Properties; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.design.dbervices.DbService; +import org.onap.appc.design.dbervices.DesignDBService; +import org.onap.appc.design.propertyServices.PropertyUpdateService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import junit.framework.Assert; +import org.powermock.reflect.Whitebox; + +public class TestDBService { + + private final org.slf4j.Logger logger = LoggerFactory.getLogger(TestDBService.class); + + @Ignore("Test is taking 60 seconds") + @Test + public void testGetDesigns() { + try { + String payload = "{\"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\" }"; + DesignDBService dbservice = DesignDBService.initialise(); + dbservice.execute("getDesigns", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testGetStatus() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; + DesignDBService dbservice = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + dbservice.execute("getStatus", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testUploadArtifact() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; + DesignDBService dbservice = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + dbservice.execute("uploadArtifact", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testGetArtifact() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("getArtifact", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testSetIncart() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"action-level\":\"VNf\",\"protocol\":\"Test\", \"inCart\":\"Y\",\"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("setInCart", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testSetProtocolReference() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"action-level\":\"VNf\",\"protocol\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("setProtocolReference", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testSetStatus() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("setStatus", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testGetArtifactReference() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("getArtifactReference", payload, "1234"); + } catch (Exception e) { + } + } + + @Ignore("Test is taking 120 seconds") + @Test + public void testGetGuiReference() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + DbService db = new DbService(); + Whitebox.invokeMethod(db, "getDbLibService"); + design.execute("getGuiReference", payload, "1234"); + } catch (Exception e) { + } + } + + @Test + public void testPropertyUpdateService() { + PropertyUpdateService ps = new PropertyUpdateService(); + } + + @Test + public void testLinkstatusRelationShip() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "linkstatusRelationShip", 1, 1, payload); + } catch (Exception e) { + } + } + + @Test + public void testGetSDCReferenceID() { + + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "getSDCReferenceID", payload); + } catch (Exception e) { + } + } + + @Test + public void testGetDataFromActionStatus() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "getDataFromActionStatus", payload, "Test"); + } catch (Exception e) { + } + } + + @Test + public void testSetActionStatus() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "setActionStatus", payload, "Accepted"); + } catch (Exception e) { + } + } + + @Test + public void testGetSDCArtifactIDbyRequestID() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "getSDCArtifactIDbyRequestID", "0"); + } catch (Exception e) { + } + } + + @Test + public void testCreateArtifactTrackingRecord() { + try { + String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); + String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; + DesignDBService design = DesignDBService.initialise(); + Whitebox.invokeMethod(design, "createArtifactTrackingRecord",payload,"0",1,1); + } catch (Exception e) { + } + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDbResponse.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDbResponse.java new file mode 100644 index 000000000..73e3dfc99 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDbResponse.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.util.ArrayList; +import org.junit.Test; +import org.onap.appc.design.dbervices.DbResponseProcessor; + +public class TestDbResponse { + + @Test + public void testDbResponse() { + DbResponseProcessor dbResponse = new DbResponseProcessor(); + try { + dbResponse.parseResponse("Test", "getDesigns"); + dbResponse.parseResponse("Test", "addInCart"); + dbResponse.parseResponse("Test", "getArtifactReference"); + dbResponse.parseResponse("Test", "getArtifact"); + dbResponse.parseResponse("Test", "getGUIReference"); + dbResponse.parseResponse("Test", "getStatus"); + dbResponse.parseResponse("Test", "uploadArtifact"); + dbResponse.parseResponse("Test", "setProtocolReference"); + dbResponse.parseResponse("Test", "setInCart"); + dbResponse.parseResponse("Test", "getStatus"); + dbResponse.parseResponse("Test", "Test"); + } catch (Exception e) { + } + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDesigndata.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDesigndata.java new file mode 100644 index 000000000..f5c4bfffd --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestDesigndata.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import org.onap.appc.design.data.ArtifactInfo; +import org.onap.appc.design.data.DesignInfo; +import org.onap.appc.design.data.DesignRequest; +import org.onap.appc.design.data.DesignResponse; +import org.onap.appc.design.data.StatusInfo; + +public class TestDesigndata { + + DesignResponse dr = new DesignResponse(); + + @Test + public void testSetUserID() { + dr.setUserId("00000"); + dr.getUserId(); + } + + @Test + public void testSetDesignInfoList() { + DesignInfo di = new DesignInfo(); + List li = new ArrayList(); + di.setAction("TestAction"); + di.setArtifact_name("TestName"); + di.setArtifact_type("TestType"); + di.setInCart("TestCart"); + di.setProtocol("TestProtocol"); + di.setVnf_type("TestVNF"); + di.setVnfc_type("TestVNFC"); + li.add(di); + dr.setDesignInfoList(li); + } + + @Test + public void testSetArtifactInfo() { + ArtifactInfo ai = new ArtifactInfo(); + List li = new ArrayList(); + ai.setArtifact_content("TestContent"); + li.add(ai); + dr.setArtifactInfo(li); + } + + @Test + public void testStatusInfo() { + StatusInfo si = new StatusInfo(); + List li = new ArrayList(); + si.setAction("TestAction"); + si.setAction_status("TestActionStatus"); + si.setArtifact_status("TestArtifactStatus"); + si.setVnf_type("TestVNF"); + si.setVnfc_type("TestVNFC"); + li.add(si); + dr.setStatusInfoList(li); + } + + @Test + public void testDesignRequest() { + DesignRequest dreq = new DesignRequest(); + dreq.setAction("TestAction"); + dreq.setArtifact_contents("TestContent"); + dreq.setArtifact_name("TestName"); + dreq.setProtocol("TestProtocol"); + dreq.setUserId("0000"); + dreq.setVnf_type("testvnf"); + dreq.setVnfc_type("testvnfc"); + dreq.getAction(); + dreq.getArtifact_contents(); + dreq.getArtifact_name(); + dreq.getProtocol(); + dreq.getUserId(); + dreq.getVnf_type(); + dreq.getVnfc_type(); + dreq.toString(); + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestEscapeUtils.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestEscapeUtils.java new file mode 100644 index 000000000..4a99d42e9 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestEscapeUtils.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.io.IOException; +import org.junit.Test; +import org.onap.appc.design.services.util.EscapeUtils; +import org.onap.appc.design.xinterface.XInterfaceService; +import org.onap.appc.design.xinterface.XResponseProcessor; +import junit.framework.Assert; + +public class TestEscapeUtils { + + @Test + public void testEscapeUtils() { + + EscapeUtils escapeUtils = new EscapeUtils(); + String str = escapeUtils.escapeSql("\\'Test Data\\'"); + assert (true); + } + + @Test + public void testXResponseProcessor(){ + + XResponseProcessor xr = new XResponseProcessor(); + Object o = new Object(); + xr.parseResponse(o, "Test"); + Assert.assertEquals(null, null); + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestValidatorService.java b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestValidatorService.java new file mode 100644 index 000000000..622483c66 --- /dev/null +++ b/appc-inbound/appc-design-services/provider/src/test/java/org/onap/appc/design/validator/TestValidatorService.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.design.validator; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.design.services.util.DesignServiceConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import junit.framework.Assert; + +public class TestValidatorService { + +//Onap Migration + + private final Logger logger = LoggerFactory.getLogger(TestValidatorService.class); + @Test + public void testValidXMLValidation(){ + String response = null; + String xmlString = "" + "create" + "" + "" + + "SDN-GP" + "" + "" + "" + ""; + + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", xmlString, "XML"); + } catch (Exception e) { + } + Assert.assertEquals("success", response); + + } + @Test + public void testInvalidXMLValidation() { + String response = null; + String xmlString = "" + "create" + "" + "" + + "SDN-GP" + "" + "" + ""; + + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", xmlString, "XML"); + } catch (Exception e) { + } + Assert.assertEquals(null, response); + } + @Test + public void testYAMLValidation() { + String response = null; + String YAMLString = "en:"; + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", YAMLString, "YAML"); + } catch (Exception e) { + } + Assert.assertEquals("success", response); + } + @Test + public void testInvalidYAMLValidation() { + String response = null; + String YAMLString = "Test \n A:"; + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", YAMLString, "YAML"); + } catch (Exception e) { + } + + Assert.assertEquals(null, response); + } + + @Test + public void testJSONValidation(){ + String response = null; + String YAMLString = "{\"Test\": \"Test1\" }"; + + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", YAMLString, "JSON"); + } catch (Exception e) { + } + Assert.assertEquals("success", response); + } + @Test + public void testInvalidJSONValidation(){ + String response = null; + String YAMLString = "{\"Test\" \"Test1\" }"; + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", YAMLString, "JSON"); + } catch (Exception e) { + } + Assert.assertEquals(null, response); + } + + @Test + public void testInvalidvalidateVelocity(){ + String response = null; + String validateVelocity = "{\"Test\" \"Test1\" }"; + ValidatorService vs = new ValidatorService(); + try { + response = vs.execute("", validateVelocity, "Velocity"); + } catch (Exception e) { + } + Assert.assertEquals(null, response); + + } +} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestArifactHandlerClient.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestArifactHandlerClient.java deleted file mode 100644 index 9f6622e36..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestArifactHandlerClient.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.design.services.util.ArtifactHandlerClient; -import junit.framework.Assert; -import static org.mockito.Mockito.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Properties; -import org.apache.commons.io.FileUtils; - -public class TestArifactHandlerClient { - - @Test - public void testCreateArtifactData(){ - - try{ - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"00000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": " - + content + - " } "; - String requestID ="0000"; - ArtifactHandlerClient ahi = new ArtifactHandlerClient(); - String value = ahi.createArtifactData(payload, requestID); - Assert.assertTrue(!value.isEmpty()); - }catch(Exception e) - { - } - } - - @Test - public void testExecute(){ - - try{ - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"00000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": " - + content + - " } "; - String rpc = "Post"; - ArtifactHandlerClient ahi = new ArtifactHandlerClient(); - ahi.execute(payload, rpc); - }catch(Exception e) - { - } - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDBService.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDBService.java deleted file mode 100644 index ffc2cadce..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDBService.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.io.File; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Properties; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.design.dbervices.DbService; -import org.onap.appc.design.dbervices.DesignDBService; -import org.onap.appc.design.propertyServices.PropertyUpdateService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import junit.framework.Assert; -import org.powermock.reflect.Whitebox; - -public class TestDBService { - - private final org.slf4j.Logger logger = LoggerFactory.getLogger(TestDBService.class); - - @Ignore("Test is taking 60 seconds") - @Test - public void testGetDesigns() { - try { - String payload = "{\"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\" }"; - DesignDBService dbservice = DesignDBService.initialise(); - dbservice.execute("getDesigns", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testGetStatus() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; - DesignDBService dbservice = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - dbservice.execute("getStatus", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testUploadArtifact() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; - DesignDBService dbservice = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - dbservice.execute("uploadArtifact", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testGetArtifact() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("getArtifact", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testSetIncart() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"action-level\":\"VNf\",\"protocol\":\"Test\", \"inCart\":\"Y\",\"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("setInCart", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testSetProtocolReference() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"action-level\":\"VNf\",\"protocol\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("setProtocolReference", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testSetStatus() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("setStatus", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testGetArtifactReference() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("getArtifactReference", payload, "1234"); - } catch (Exception e) { - } - } - - @Ignore("Test is taking 120 seconds") - @Test - public void testGetGuiReference() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - DbService db = new DbService(); - Whitebox.invokeMethod(db, "getDbLibService"); - design.execute("getGuiReference", payload, "1234"); - } catch (Exception e) { - } - } - - @Test - public void testPropertyUpdateService() { - PropertyUpdateService ps = new PropertyUpdateService(); - } - - @Test - public void testLinkstatusRelationShip() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "linkstatusRelationShip", 1, 1, payload); - } catch (Exception e) { - } - } - - @Test - public void testGetSDCReferenceID() { - - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "getSDCReferenceID", payload); - } catch (Exception e) { - } - } - - @Test - public void testGetDataFromActionStatus() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "getDataFromActionStatus", payload, "Test"); - } catch (Exception e) { - } - } - - @Test - public void testSetActionStatus() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "setActionStatus", payload, "Accepted"); - } catch (Exception e) { - } - } - - @Test - public void testGetSDCArtifactIDbyRequestID() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "getSDCArtifactIDbyRequestID", "0"); - } catch (Exception e) { - } - } - - @Test - public void testCreateArtifactTrackingRecord() { - try { - String content = FileUtils.readFileToString(new File("src/test/resources/uploadArtifact")); - String payload = " { \"userID\": \"0000\",\"status\":\"Test\", \"vnf-type\" : \"DesigTest-VNF\", \"action\" : \"Configure\", \"artifact-name\":\"DesignRestArtifact_reference\",\"artifact-version\" :\"0.01\",\"artifact-type\" :\"DESIGNTOOL-TEST\",\"artifact-status\":\"\",\"artifact-contents\": "+ content + " } "; - DesignDBService design = DesignDBService.initialise(); - Whitebox.invokeMethod(design, "createArtifactTrackingRecord",payload,"0",1,1); - } catch (Exception e) { - } - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDbResponse.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDbResponse.java deleted file mode 100644 index 73e3dfc99..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDbResponse.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.util.ArrayList; -import org.junit.Test; -import org.onap.appc.design.dbervices.DbResponseProcessor; - -public class TestDbResponse { - - @Test - public void testDbResponse() { - DbResponseProcessor dbResponse = new DbResponseProcessor(); - try { - dbResponse.parseResponse("Test", "getDesigns"); - dbResponse.parseResponse("Test", "addInCart"); - dbResponse.parseResponse("Test", "getArtifactReference"); - dbResponse.parseResponse("Test", "getArtifact"); - dbResponse.parseResponse("Test", "getGUIReference"); - dbResponse.parseResponse("Test", "getStatus"); - dbResponse.parseResponse("Test", "uploadArtifact"); - dbResponse.parseResponse("Test", "setProtocolReference"); - dbResponse.parseResponse("Test", "setInCart"); - dbResponse.parseResponse("Test", "getStatus"); - dbResponse.parseResponse("Test", "Test"); - } catch (Exception e) { - } - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDesigndata.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDesigndata.java deleted file mode 100644 index f5c4bfffd..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestDesigndata.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.onap.appc.design.data.ArtifactInfo; -import org.onap.appc.design.data.DesignInfo; -import org.onap.appc.design.data.DesignRequest; -import org.onap.appc.design.data.DesignResponse; -import org.onap.appc.design.data.StatusInfo; - -public class TestDesigndata { - - DesignResponse dr = new DesignResponse(); - - @Test - public void testSetUserID() { - dr.setUserId("00000"); - dr.getUserId(); - } - - @Test - public void testSetDesignInfoList() { - DesignInfo di = new DesignInfo(); - List li = new ArrayList(); - di.setAction("TestAction"); - di.setArtifact_name("TestName"); - di.setArtifact_type("TestType"); - di.setInCart("TestCart"); - di.setProtocol("TestProtocol"); - di.setVnf_type("TestVNF"); - di.setVnfc_type("TestVNFC"); - li.add(di); - dr.setDesignInfoList(li); - } - - @Test - public void testSetArtifactInfo() { - ArtifactInfo ai = new ArtifactInfo(); - List li = new ArrayList(); - ai.setArtifact_content("TestContent"); - li.add(ai); - dr.setArtifactInfo(li); - } - - @Test - public void testStatusInfo() { - StatusInfo si = new StatusInfo(); - List li = new ArrayList(); - si.setAction("TestAction"); - si.setAction_status("TestActionStatus"); - si.setArtifact_status("TestArtifactStatus"); - si.setVnf_type("TestVNF"); - si.setVnfc_type("TestVNFC"); - li.add(si); - dr.setStatusInfoList(li); - } - - @Test - public void testDesignRequest() { - DesignRequest dreq = new DesignRequest(); - dreq.setAction("TestAction"); - dreq.setArtifact_contents("TestContent"); - dreq.setArtifact_name("TestName"); - dreq.setProtocol("TestProtocol"); - dreq.setUserId("0000"); - dreq.setVnf_type("testvnf"); - dreq.setVnfc_type("testvnfc"); - dreq.getAction(); - dreq.getArtifact_contents(); - dreq.getArtifact_name(); - dreq.getProtocol(); - dreq.getUserId(); - dreq.getVnf_type(); - dreq.getVnfc_type(); - dreq.toString(); - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestEscapeUtils.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestEscapeUtils.java deleted file mode 100644 index 4a99d42e9..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestEscapeUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.io.IOException; -import org.junit.Test; -import org.onap.appc.design.services.util.EscapeUtils; -import org.onap.appc.design.xinterface.XInterfaceService; -import org.onap.appc.design.xinterface.XResponseProcessor; -import junit.framework.Assert; - -public class TestEscapeUtils { - - @Test - public void testEscapeUtils() { - - EscapeUtils escapeUtils = new EscapeUtils(); - String str = escapeUtils.escapeSql("\\'Test Data\\'"); - assert (true); - } - - @Test - public void testXResponseProcessor(){ - - XResponseProcessor xr = new XResponseProcessor(); - Object o = new Object(); - xr.parseResponse(o, "Test"); - Assert.assertEquals(null, null); - } -} diff --git a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestValidatorService.java b/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestValidatorService.java deleted file mode 100644 index 622483c66..000000000 --- a/appc-inbound/appc-design-services/provider/src/test/java/org/openecomp/appc/design/validator/TestValidatorService.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.design.validator; - -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.design.services.util.DesignServiceConstants; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import junit.framework.Assert; - -public class TestValidatorService { - -//Onap Migration - - private final Logger logger = LoggerFactory.getLogger(TestValidatorService.class); - @Test - public void testValidXMLValidation(){ - String response = null; - String xmlString = "" + "create" + "" + "" - + "SDN-GP" + "" + "" + "" + ""; - - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", xmlString, "XML"); - } catch (Exception e) { - } - Assert.assertEquals("success", response); - - } - @Test - public void testInvalidXMLValidation() { - String response = null; - String xmlString = "" + "create" + "" + "" - + "SDN-GP" + "" + "" + ""; - - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", xmlString, "XML"); - } catch (Exception e) { - } - Assert.assertEquals(null, response); - } - @Test - public void testYAMLValidation() { - String response = null; - String YAMLString = "en:"; - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", YAMLString, "YAML"); - } catch (Exception e) { - } - Assert.assertEquals("success", response); - } - @Test - public void testInvalidYAMLValidation() { - String response = null; - String YAMLString = "Test \n A:"; - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", YAMLString, "YAML"); - } catch (Exception e) { - } - - Assert.assertEquals(null, response); - } - - @Test - public void testJSONValidation(){ - String response = null; - String YAMLString = "{\"Test\": \"Test1\" }"; - - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", YAMLString, "JSON"); - } catch (Exception e) { - } - Assert.assertEquals("success", response); - } - @Test - public void testInvalidJSONValidation(){ - String response = null; - String YAMLString = "{\"Test\" \"Test1\" }"; - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", YAMLString, "JSON"); - } catch (Exception e) { - } - Assert.assertEquals(null, response); - } - - @Test - public void testInvalidvalidateVelocity(){ - String response = null; - String validateVelocity = "{\"Test\" \"Test1\" }"; - ValidatorService vs = new ValidatorService(); - try { - response = vs.execute("", validateVelocity, "Velocity"); - } catch (Exception e) { - } - Assert.assertEquals(null, response); - - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/LifecycleManager.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/LifecycleManager.java new file mode 100644 index 000000000..0ab535ffc --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/LifecycleManager.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager; + +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; + +public interface LifecycleManager { + String getNextState(String vnfType, String currentState, String event) + throws NoTransitionDefinedException,LifecycleException; +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LCMResponse.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LCMResponse.java new file mode 100644 index 000000000..541f39fb2 --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LCMResponse.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager.objects; + +public enum LCMResponse { + INVALID_INPUT_PARAMETERS, + NO_STATE_CHANGE, + NO_TRANSITION_DEFINED, + VALID_TRANSITION; + + public String toString(){ + return this.name(); + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LifecycleException.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LifecycleException.java new file mode 100644 index 000000000..2fbdb740c --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/LifecycleException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager.objects; + +public class LifecycleException extends Exception { + public final String currentState; + public final String event; + + public LifecycleException(Exception e,String currentState,String event){ + super(e); + this.currentState = currentState; + this.event = event; + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/NoTransitionDefinedException.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/NoTransitionDefinedException.java new file mode 100644 index 000000000..ced81b812 --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/NoTransitionDefinedException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager.objects; + +public class NoTransitionDefinedException extends Exception { + public final String currentState; + public final String event; + + public NoTransitionDefinedException(String message,String currentState,String event){ + super(message); + this.currentState = currentState; + this.event = event; + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/VNFOperationOutcome.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/VNFOperationOutcome.java new file mode 100644 index 000000000..16cf08168 --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/onap/appc/lifecyclemanager/objects/VNFOperationOutcome.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager.objects; + +public enum VNFOperationOutcome { + SUCCESS,FAILURE,EXPIRE; + public String toString(){ + return this.name(); + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/LifecycleManager.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/LifecycleManager.java deleted file mode 100644 index 0ab535ffc..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/LifecycleManager.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager; - -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; - -public interface LifecycleManager { - String getNextState(String vnfType, String currentState, String event) - throws NoTransitionDefinedException,LifecycleException; -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LCMResponse.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LCMResponse.java deleted file mode 100644 index 541f39fb2..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LCMResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager.objects; - -public enum LCMResponse { - INVALID_INPUT_PARAMETERS, - NO_STATE_CHANGE, - NO_TRANSITION_DEFINED, - VALID_TRANSITION; - - public String toString(){ - return this.name(); - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LifecycleException.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LifecycleException.java deleted file mode 100644 index 2fbdb740c..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/LifecycleException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager.objects; - -public class LifecycleException extends Exception { - public final String currentState; - public final String event; - - public LifecycleException(Exception e,String currentState,String event){ - super(e); - this.currentState = currentState; - this.event = event; - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/NoTransitionDefinedException.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/NoTransitionDefinedException.java deleted file mode 100644 index ced81b812..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/NoTransitionDefinedException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager.objects; - -public class NoTransitionDefinedException extends Exception { - public final String currentState; - public final String event; - - public NoTransitionDefinedException(String message,String currentState,String event){ - super(message); - this.currentState = currentState; - this.event = event; - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/VNFOperationOutcome.java b/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/VNFOperationOutcome.java deleted file mode 100644 index 16cf08168..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-api/src/main/java/org/openecomp/appc/lifecyclemanager/objects/VNFOperationOutcome.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager.objects; - -public enum VNFOperationOutcome { - SUCCESS,FAILURE,EXPIRE; - public String toString(){ - return this.name(); - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/onap/appc/lifecyclemanager/impl/LifecycleManagerImpl.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/onap/appc/lifecyclemanager/impl/LifecycleManagerImpl.java new file mode 100644 index 000000000..12c48b481 --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/onap/appc/lifecyclemanager/impl/LifecycleManagerImpl.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.lifecyclemanager.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.statemachine.StateMachine; +import org.onap.appc.statemachine.StateMetaDataReader; +import org.onap.appc.statemachine.impl.StateMachineFactory; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader; +import org.onap.appc.statemachine.objects.*; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class LifecycleManagerImpl implements LifecycleManager{ + + private StateMetaDataReader metadataReader; + private static Map stateMachineMap = new ConcurrentHashMap<>(); + private final EELFLogger logger = EELFManager.getInstance().getLogger(LifecycleManagerImpl.class); + private final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + + @Override + public String getNextState(String vnfType, String currentState, String event) throws NoTransitionDefinedException,LifecycleException{ + if (logger.isTraceEnabled()) { + logger.trace("Entering to getNextState with vnfType = "+ vnfType + ", currentState = " + currentState + ", event = " + event); + } + + State nextState; + StateMachine machine; + StateMachineResponse response; + try { + machine = this.getStateMachine(vnfType); + response = machine.handleEvent(new State(currentState),new Event(event)); + if(Response.NO_TRANSITION_DEFINED.equals(response.getResponse())){ + errorLogger.error(EELFResourceManager.format(Msg.VF_ILLEGAL_COMMAND, vnfType,event,currentState)); + throw new NoTransitionDefinedException("No Transition Defined for currentState = " + currentState + ", event = " + event,currentState,event); + } + nextState = response.getNextState(); + } catch (InvalidInputException e) { + logger.error(e.getMessage()); + throw new LifecycleException(e,currentState,event); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from getNextState with (nextState = " + nextState.getStateName() + ")"); + } + return nextState.getStateName(); + } + + private StateMachine getStateMachine(String vnfType){ + if (logger.isTraceEnabled()) { + logger.trace("Entering to getNextState with vnfType = "+ vnfType); + } + if(vnfType == null){ + vnfType = "DEFAULT"; + } + StateMachine machine = stateMachineMap.get(vnfType); + if(machine == null){ + metadataReader = getMetadataReader(vnfType); + StateMachineMetadata metadata = metadataReader.readMetadata(); + machine = StateMachineFactory.getStateMachine(metadata); + stateMachineMap.put(vnfType,machine); + } + + logger.trace("Exiting getStateMachine with StateMachine = " + stateMachineMap.get(vnfType).toString()); + return stateMachineMap.get(vnfType); + } + + private StateMetaDataReader getMetadataReader(String vnfType) { + return vnfType.equals("APPC") ? new AppcOamMetaDataReader() : new VnfMetaDataReader(); + } + +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/impl/LifecycleManagerImpl.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/impl/LifecycleManagerImpl.java deleted file mode 100644 index 12c48b481..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/impl/LifecycleManagerImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.lifecyclemanager.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.statemachine.StateMachine; -import org.onap.appc.statemachine.StateMetaDataReader; -import org.onap.appc.statemachine.impl.StateMachineFactory; -import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; -import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader; -import org.onap.appc.statemachine.objects.*; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class LifecycleManagerImpl implements LifecycleManager{ - - private StateMetaDataReader metadataReader; - private static Map stateMachineMap = new ConcurrentHashMap<>(); - private final EELFLogger logger = EELFManager.getInstance().getLogger(LifecycleManagerImpl.class); - private final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - - @Override - public String getNextState(String vnfType, String currentState, String event) throws NoTransitionDefinedException,LifecycleException{ - if (logger.isTraceEnabled()) { - logger.trace("Entering to getNextState with vnfType = "+ vnfType + ", currentState = " + currentState + ", event = " + event); - } - - State nextState; - StateMachine machine; - StateMachineResponse response; - try { - machine = this.getStateMachine(vnfType); - response = machine.handleEvent(new State(currentState),new Event(event)); - if(Response.NO_TRANSITION_DEFINED.equals(response.getResponse())){ - errorLogger.error(EELFResourceManager.format(Msg.VF_ILLEGAL_COMMAND, vnfType,event,currentState)); - throw new NoTransitionDefinedException("No Transition Defined for currentState = " + currentState + ", event = " + event,currentState,event); - } - nextState = response.getNextState(); - } catch (InvalidInputException e) { - logger.error(e.getMessage()); - throw new LifecycleException(e,currentState,event); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from getNextState with (nextState = " + nextState.getStateName() + ")"); - } - return nextState.getStateName(); - } - - private StateMachine getStateMachine(String vnfType){ - if (logger.isTraceEnabled()) { - logger.trace("Entering to getNextState with vnfType = "+ vnfType); - } - if(vnfType == null){ - vnfType = "DEFAULT"; - } - StateMachine machine = stateMachineMap.get(vnfType); - if(machine == null){ - metadataReader = getMetadataReader(vnfType); - StateMachineMetadata metadata = metadataReader.readMetadata(); - machine = StateMachineFactory.getStateMachine(metadata); - stateMachineMap.put(vnfType,machine); - } - - logger.trace("Exiting getStateMachine with StateMachine = " + stateMachineMap.get(vnfType).toString()); - return stateMachineMap.get(vnfType); - } - - private StateMetaDataReader getMetadataReader(String vnfType) { - return vnfType.equals("APPC") ? new AppcOamMetaDataReader() : new VnfMetaDataReader(); - } - -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/onap/appc/default.properties b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..0c4de19aa --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,39 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-LC-MGMT-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/openecomp/appc/default.properties b/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 0c4de19aa..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,39 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-LC-MGMT-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/LifecycleManagerTest.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/LifecycleManagerTest.java new file mode 100644 index 000000000..07aef6cb3 --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/LifecycleManagerTest.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.statemachine.StateMetaDataReader; +import org.onap.appc.lifecyclemanager.impl.LifecycleManagerImpl; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader; +import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader.VNFOperation; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; +import org.onap.appc.statemachine.objects.Transition; + +import java.util.*; + + +public class LifecycleManagerTest { + + private static final State[] VALID_LOCK_STATES = new State[] { + new State("instantiated"), + new State("configured"), + new State("tested"), + new State("running"), + new State("error"), + new State("unknown"), + new State("created"), + new State("not orchestrated"), + new State("stopped"), + }; + + @Test + public void handleEvent() throws InvalidInputException, LifecycleException, NoTransitionDefinedException { + + StateMachineMetadata metadata = getMetaDataReader().readMetadata(); + LifecycleManagerImpl lifecycleManager = new LifecycleManagerImpl(); + + /* + * Testing Positive Scenario passing the valid events and validating the StateMachineResponse + */ + for(State state:metadata.getStates()){ + + for(Transition transition:state.getTransitions()){ + Event event = transition.getEvent(); + State nextStateFromMetadata = transition.getNextState(); + + String expectedNextState = lifecycleManager.getNextState(null,state.toString(),event.toString()); + Assert.assertEquals(expectedNextState,nextStateFromMetadata.toString()); + } + } + + /* + Testing Negative Scenarios, 1. Passing the valid Events for which Transition is not defined in + Metadata and validating the StateMachineResponse 2. Passing the invalid events which are not + registered as events in the StateMachineMetadata and validating StateMachineResponse + */ + for(State state:metadata.getStates()){ + + for(Transition transition:state.getTransitions()){ + List negativeEvents = getNegativeEvents(state,metadata.getEvents()); + + for(Event negativeEvent:negativeEvents){ + boolean flag =false; + try{ + lifecycleManager.getNextState(null,state.toString(),negativeEvent.toString()); + + } + catch (NoTransitionDefinedException e){ + flag =true; + } + Assert.assertEquals(flag,true); + + flag = false; + try{ + lifecycleManager.getNextState(null,state.toString(),"PUT"); + } + catch(LifecycleException e){ + flag = true; + } + Assert.assertTrue(flag); + + } + } + } + } + + @Test + public void testNotOrchestratedState() throws LifecycleException, NoTransitionDefinedException { + LifecycleManager lifecycleManager = new LifecycleManagerImpl(); + String nextState = lifecycleManager.getNextState( + null,"NOT ORCHESTRATED",VNFOperation.Configure.toString()); + Assert.assertEquals(nextState,"Configuring"); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testBakckingUpState() throws LifecycleException, NoTransitionDefinedException { + LifecycleManager lifecycleManager = new LifecycleManagerImpl(); + lifecycleManager.getNextState(null,"Software_Uploading",VNFOperation.Configure.toString()); + } + + private List getNegativeEvents(State state,Set events) { + List negativeEventList = new ArrayList<>(); + negativeEventList.addAll(events); + + for(Transition transition: state.getTransitions()){ + negativeEventList.remove(transition.getEvent()); + } + return negativeEventList; + } + + @Test + public void testLockStates() throws LifecycleException, NoTransitionDefinedException { + StateMachineMetadata metadata = getMetaDataReader().readMetadata(); + LifecycleManagerImpl lifecycleManager = new LifecycleManagerImpl(); + + for(State state: metadata.getStates()) { + if(isValidState(state, VALID_LOCK_STATES)) { + assertSameNextState(lifecycleManager, state, VNFOperation.Lock); + assertSameNextState(lifecycleManager, state, VnfMetaDataReader.VNFOperation.Unlock); + assertSameNextState(lifecycleManager, state, VNFOperation.CheckLock); + } else { + assertNoNextState(lifecycleManager, state, VNFOperation.Lock); + assertNoNextState(lifecycleManager, state, VNFOperation.Unlock); + assertNoNextState(lifecycleManager, state, VNFOperation.CheckLock); + } + } + } + + private boolean isValidState(State state, State[] validStates) { + for(State validState: validStates) { + if(validState.equals(state)) { + return true; + } + } + return false; + } + + private void assertSameNextState(LifecycleManager lifecycleManager, State state, VNFOperation operation) + throws LifecycleException, NoTransitionDefinedException { + Assert.assertEquals(state.getStateName(), + lifecycleManager.getNextState("no-matter", state.getStateName(), operation.toString())); + } + + private void assertNoNextState(LifecycleManager lifecycleManager, State state, VNFOperation operation) + throws LifecycleException { + try { + lifecycleManager.getNextState("no-matter", state.getStateName(), operation.toString()); + Assert.fail("lifecycleManager.getNextState() should fail for state [" + state + + "], operation [" + operation + "]"); + } catch(NoTransitionDefinedException e) { + // this exception is excepted + } + } + + private StateMetaDataReader getMetaDataReader() { + return new VnfMetaDataReader(); + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/OamLifeCycleManagerTest.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/OamLifeCycleManagerTest.java new file mode 100644 index 000000000..403a9f39e --- /dev/null +++ b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/onap/appc/OamLifeCycleManagerTest.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.appc.lifecyclemanager.impl.LifecycleManagerImpl; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +import java.util.Arrays; +import java.util.List; + + +public class OamLifeCycleManagerTest { + private static final String VNF_TYPE_APPC = "APPC"; + private static final String NO_DEFINITION_FORMAT = "No Transition Defined for currentState = %s, event = %s"; + + private LifecycleManagerImpl lifecycleManager; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + lifecycleManager = new LifecycleManagerImpl(); + } + + private void validateProper(String state, String event, String expectedResult) + throws LifecycleException, NoTransitionDefinedException { + String nextState = lifecycleManager.getNextState(VNF_TYPE_APPC, state, event); + Assert.assertEquals(String.format("Should return %s", expectedResult), expectedResult, nextState); + } + + private void validateException(String state, String event) throws LifecycleException, NoTransitionDefinedException { + expectedException.expect(NoTransitionDefinedException.class); + expectedException.expectMessage(String.format(NO_DEFINITION_FORMAT, state, event)); + lifecycleManager.getNextState(VNF_TYPE_APPC, state, event); + + // Reset to no expectation + expectedException = ExpectedException.none(); + } + + @Test + public void testOamStateTransitionForMaintenanceMode() throws Exception { + String event = AppcOamMetaDataReader.AppcOperation.MaintenanceMode.name(); + String expecteResult = AppcOamStates.EnteringMaintenanceMode.toString(); + + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + String state = appcOamStates.toString(); + if (appcOamStates == AppcOamStates.Started) { + validateProper(state, event, expecteResult); + } else { + validateException(state, event); + } + } + } + + @Test + public void testOamStateTransitionForStart() throws Exception { + String event = AppcOamMetaDataReader.AppcOperation.Start.name(); + String expectResult = AppcOamStates.Starting.toString(); + + List goodStates = Arrays.asList( + AppcOamStates.MaintenanceMode, + AppcOamStates.Stopped, + AppcOamStates.Stopping); + + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + String state = appcOamStates.toString(); + if (goodStates.contains(appcOamStates)) { + validateProper(state, event, expectResult); + } else { + validateException(state, event); + } + } + } + + @Test + public void testOamStateTransitionForStop() throws Exception { + String event = AppcOamMetaDataReader.AppcOperation.Stop.name(); + String expectResult = AppcOamStates.Stopping.toString(); + + List goodStates = Arrays.asList( + AppcOamStates.Error, + AppcOamStates.EnteringMaintenanceMode, + AppcOamStates.MaintenanceMode, + AppcOamStates.Started, + AppcOamStates.Starting); + + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + String state = appcOamStates.toString(); + if (goodStates.contains(appcOamStates)) { + validateProper(state, event, expectResult); + } else { + validateException(state, event); + } + } + } + + + @Test + public void testOamStateTransitionForRestart() throws Exception { + String event = AppcOamMetaDataReader.AppcOperation.Restart.name(); + String expectResult = AppcOamStates.Restarting.toString(); + + List goodStates = Arrays.asList( + AppcOamStates.Error, + AppcOamStates.EnteringMaintenanceMode, + AppcOamStates.MaintenanceMode, + AppcOamStates.Started, + AppcOamStates.Starting, + AppcOamStates.Stopped, + AppcOamStates.Stopping); + + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + String state = appcOamStates.toString(); + if (goodStates.contains(appcOamStates)) { + validateProper(state, event, expectResult); + } else { + validateException(state, event); + } + } + } +} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/LifecycleManagerTest.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/LifecycleManagerTest.java deleted file mode 100644 index 07aef6cb3..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/LifecycleManagerTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.statemachine.StateMetaDataReader; -import org.onap.appc.lifecyclemanager.impl.LifecycleManagerImpl; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader; -import org.onap.appc.statemachine.impl.readers.VnfMetaDataReader.VNFOperation; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; -import org.onap.appc.statemachine.objects.Transition; - -import java.util.*; - - -public class LifecycleManagerTest { - - private static final State[] VALID_LOCK_STATES = new State[] { - new State("instantiated"), - new State("configured"), - new State("tested"), - new State("running"), - new State("error"), - new State("unknown"), - new State("created"), - new State("not orchestrated"), - new State("stopped"), - }; - - @Test - public void handleEvent() throws InvalidInputException, LifecycleException, NoTransitionDefinedException { - - StateMachineMetadata metadata = getMetaDataReader().readMetadata(); - LifecycleManagerImpl lifecycleManager = new LifecycleManagerImpl(); - - /* - * Testing Positive Scenario passing the valid events and validating the StateMachineResponse - */ - for(State state:metadata.getStates()){ - - for(Transition transition:state.getTransitions()){ - Event event = transition.getEvent(); - State nextStateFromMetadata = transition.getNextState(); - - String expectedNextState = lifecycleManager.getNextState(null,state.toString(),event.toString()); - Assert.assertEquals(expectedNextState,nextStateFromMetadata.toString()); - } - } - - /* - Testing Negative Scenarios, 1. Passing the valid Events for which Transition is not defined in - Metadata and validating the StateMachineResponse 2. Passing the invalid events which are not - registered as events in the StateMachineMetadata and validating StateMachineResponse - */ - for(State state:metadata.getStates()){ - - for(Transition transition:state.getTransitions()){ - List negativeEvents = getNegativeEvents(state,metadata.getEvents()); - - for(Event negativeEvent:negativeEvents){ - boolean flag =false; - try{ - lifecycleManager.getNextState(null,state.toString(),negativeEvent.toString()); - - } - catch (NoTransitionDefinedException e){ - flag =true; - } - Assert.assertEquals(flag,true); - - flag = false; - try{ - lifecycleManager.getNextState(null,state.toString(),"PUT"); - } - catch(LifecycleException e){ - flag = true; - } - Assert.assertTrue(flag); - - } - } - } - } - - @Test - public void testNotOrchestratedState() throws LifecycleException, NoTransitionDefinedException { - LifecycleManager lifecycleManager = new LifecycleManagerImpl(); - String nextState = lifecycleManager.getNextState( - null,"NOT ORCHESTRATED",VNFOperation.Configure.toString()); - Assert.assertEquals(nextState,"Configuring"); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testBakckingUpState() throws LifecycleException, NoTransitionDefinedException { - LifecycleManager lifecycleManager = new LifecycleManagerImpl(); - lifecycleManager.getNextState(null,"Software_Uploading",VNFOperation.Configure.toString()); - } - - private List getNegativeEvents(State state,Set events) { - List negativeEventList = new ArrayList<>(); - negativeEventList.addAll(events); - - for(Transition transition: state.getTransitions()){ - negativeEventList.remove(transition.getEvent()); - } - return negativeEventList; - } - - @Test - public void testLockStates() throws LifecycleException, NoTransitionDefinedException { - StateMachineMetadata metadata = getMetaDataReader().readMetadata(); - LifecycleManagerImpl lifecycleManager = new LifecycleManagerImpl(); - - for(State state: metadata.getStates()) { - if(isValidState(state, VALID_LOCK_STATES)) { - assertSameNextState(lifecycleManager, state, VNFOperation.Lock); - assertSameNextState(lifecycleManager, state, VnfMetaDataReader.VNFOperation.Unlock); - assertSameNextState(lifecycleManager, state, VNFOperation.CheckLock); - } else { - assertNoNextState(lifecycleManager, state, VNFOperation.Lock); - assertNoNextState(lifecycleManager, state, VNFOperation.Unlock); - assertNoNextState(lifecycleManager, state, VNFOperation.CheckLock); - } - } - } - - private boolean isValidState(State state, State[] validStates) { - for(State validState: validStates) { - if(validState.equals(state)) { - return true; - } - } - return false; - } - - private void assertSameNextState(LifecycleManager lifecycleManager, State state, VNFOperation operation) - throws LifecycleException, NoTransitionDefinedException { - Assert.assertEquals(state.getStateName(), - lifecycleManager.getNextState("no-matter", state.getStateName(), operation.toString())); - } - - private void assertNoNextState(LifecycleManager lifecycleManager, State state, VNFOperation operation) - throws LifecycleException { - try { - lifecycleManager.getNextState("no-matter", state.getStateName(), operation.toString()); - Assert.fail("lifecycleManager.getNextState() should fail for state [" + state - + "], operation [" + operation + "]"); - } catch(NoTransitionDefinedException e) { - // this exception is excepted - } - } - - private StateMetaDataReader getMetaDataReader() { - return new VnfMetaDataReader(); - } -} diff --git a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/OamLifeCycleManagerTest.java b/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/OamLifeCycleManagerTest.java deleted file mode 100644 index 403a9f39e..000000000 --- a/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/OamLifeCycleManagerTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.appc.lifecyclemanager.impl.LifecycleManagerImpl; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -import java.util.Arrays; -import java.util.List; - - -public class OamLifeCycleManagerTest { - private static final String VNF_TYPE_APPC = "APPC"; - private static final String NO_DEFINITION_FORMAT = "No Transition Defined for currentState = %s, event = %s"; - - private LifecycleManagerImpl lifecycleManager; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - lifecycleManager = new LifecycleManagerImpl(); - } - - private void validateProper(String state, String event, String expectedResult) - throws LifecycleException, NoTransitionDefinedException { - String nextState = lifecycleManager.getNextState(VNF_TYPE_APPC, state, event); - Assert.assertEquals(String.format("Should return %s", expectedResult), expectedResult, nextState); - } - - private void validateException(String state, String event) throws LifecycleException, NoTransitionDefinedException { - expectedException.expect(NoTransitionDefinedException.class); - expectedException.expectMessage(String.format(NO_DEFINITION_FORMAT, state, event)); - lifecycleManager.getNextState(VNF_TYPE_APPC, state, event); - - // Reset to no expectation - expectedException = ExpectedException.none(); - } - - @Test - public void testOamStateTransitionForMaintenanceMode() throws Exception { - String event = AppcOamMetaDataReader.AppcOperation.MaintenanceMode.name(); - String expecteResult = AppcOamStates.EnteringMaintenanceMode.toString(); - - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - String state = appcOamStates.toString(); - if (appcOamStates == AppcOamStates.Started) { - validateProper(state, event, expecteResult); - } else { - validateException(state, event); - } - } - } - - @Test - public void testOamStateTransitionForStart() throws Exception { - String event = AppcOamMetaDataReader.AppcOperation.Start.name(); - String expectResult = AppcOamStates.Starting.toString(); - - List goodStates = Arrays.asList( - AppcOamStates.MaintenanceMode, - AppcOamStates.Stopped, - AppcOamStates.Stopping); - - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - String state = appcOamStates.toString(); - if (goodStates.contains(appcOamStates)) { - validateProper(state, event, expectResult); - } else { - validateException(state, event); - } - } - } - - @Test - public void testOamStateTransitionForStop() throws Exception { - String event = AppcOamMetaDataReader.AppcOperation.Stop.name(); - String expectResult = AppcOamStates.Stopping.toString(); - - List goodStates = Arrays.asList( - AppcOamStates.Error, - AppcOamStates.EnteringMaintenanceMode, - AppcOamStates.MaintenanceMode, - AppcOamStates.Started, - AppcOamStates.Starting); - - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - String state = appcOamStates.toString(); - if (goodStates.contains(appcOamStates)) { - validateProper(state, event, expectResult); - } else { - validateException(state, event); - } - } - } - - - @Test - public void testOamStateTransitionForRestart() throws Exception { - String event = AppcOamMetaDataReader.AppcOperation.Restart.name(); - String expectResult = AppcOamStates.Restarting.toString(); - - List goodStates = Arrays.asList( - AppcOamStates.Error, - AppcOamStates.EnteringMaintenanceMode, - AppcOamStates.MaintenanceMode, - AppcOamStates.Started, - AppcOamStates.Starting, - AppcOamStates.Stopped, - AppcOamStates.Stopping); - - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - String state = appcOamStates.toString(); - if (goodStates.contains(appcOamStates)) { - validateProper(state, event, expectResult); - } else { - validateException(state, event); - } - } - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMachine.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMachine.java new file mode 100644 index 000000000..52350852e --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMachine.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine; + +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineResponse; + +/** + * Interface of the StateMachine + */ +public interface StateMachine { + /** + * Handle event + * @param currentState the current State which the event should be handled from + * @param event the Event that needs to be handled + * @return StateMachineResponse + * @throws InvalidInputException + * when the passed in currentState and event are not predefined or no relevant transition + */ + StateMachineResponse handleEvent(State currentState, Event event) throws InvalidInputException; +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMetaDataReader.java new file mode 100644 index 000000000..fe2b193e1 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/StateMetaDataReader.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine; + +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +public interface StateMetaDataReader { + StateMachineMetadata readMetadata(); +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineFactory.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineFactory.java new file mode 100644 index 000000000..bfcafeb7d --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineFactory.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl; + +import org.onap.appc.statemachine.StateMachine; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +/** + * Factory of StateMachine + */ +public class StateMachineFactory { + + private StateMachineFactory(){ + throw new IllegalAccessError("StateMachineFactory"); + } + + public static StateMachine getStateMachine(StateMachineMetadata metadata){ + return new StateMachineImpl(metadata); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineImpl.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineImpl.java new file mode 100644 index 000000000..b56250708 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/StateMachineImpl.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl; + +import java.util.HashSet; +import java.util.Set; + +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.statemachine.StateMachine; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.Response; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; +import org.onap.appc.statemachine.objects.StateMachineResponse; +import org.onap.appc.statemachine.objects.Transition; + +/** + * Implementation of StateMachine + */ +public class StateMachineImpl implements StateMachine { + private static final String invalidInputFormat = "VNF State or incoming event is invalid. State = %s event = %s"; + static final String toStringFormat = "StateMachineImpl{states=%s, events=%s}"; + + private final Set states; + private final Set events; + + StateMachineImpl(StateMachineMetadata metadata){ + this.states = new HashSet<>(); + this.states.addAll(metadata.getStates()); + this.events = new HashSet<>(); + this.events.addAll(metadata.getEvents()); + } + + @Override + public StateMachineResponse handleEvent(State inputState, Event event) throws InvalidInputException{ + + if(!validateInputs(inputState,event)){ + throw new InvalidInputException(String.format(invalidInputFormat, inputState, event)); + } + + StateMachineResponse response = new StateMachineResponse(); + State currentState = null; + State nextState = null; + for(State stateInSet:states){ + if(stateInSet.equals(inputState)){ + currentState = stateInSet; + break; + } + } + if (currentState != null) { + for (Transition transition : currentState.getTransitions()) { + if (event.equals(transition.getEvent())) { + nextState = transition.getNextState(); + } + } + } + if(nextState == null){ + response.setResponse(Response.NO_TRANSITION_DEFINED); + } + else if(inputState.equals(nextState)){ + response.setResponse(Response.NO_STATE_CHANGE); + } + else{ + response.setResponse(Response.VALID_TRANSITION); + } + response.setNextState(nextState); + return response; + } + + boolean validateInputs(State state,Event event) { + return state != null + && event != null + && this.states.contains(state) + && this.events.contains(event); + } + + @Override + public String toString() { + return String.format(toStringFormat, states, events); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReader.java new file mode 100644 index 000000000..7451cf3af --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReader.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.onap.appc.statemachine.StateMetaDataReader; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +/** + * Reader for APPC OAM MetaData + */ +public class AppcOamMetaDataReader implements StateMetaDataReader { + + /** + * APPC Operation Enum + */ + public enum AppcOperation { + MaintenanceMode, + Restart, + Start, + Stop + } + + @Override + public StateMachineMetadata readMetadata() { + State notInstantiated = new State(AppcOamStates.NotInstantiated.toString()); + State instantiated = new State(AppcOamStates.Instantiated.toString()); + State restarting = new State(AppcOamStates.Restarting.toString()); + State starting = new State(AppcOamStates.Starting.toString()); + State started = new State(AppcOamStates.Started.toString()); + State enteringMaintenanceMode = new State(AppcOamStates.EnteringMaintenanceMode.toString()); + State maintenanceMode = new State(AppcOamStates.MaintenanceMode.toString()); + State error = new State(AppcOamStates.Error.toString()); + State unknown = new State(AppcOamStates.Unknown.toString()); + State stopping = new State(AppcOamStates.Stopping.toString()); + State stopped = new State(AppcOamStates.Stopped.toString()); + + Event start = new Event(AppcOperation.Start.toString()); + Event stop = new Event(AppcOperation.Stop.toString()); + Event maintenanceModeEvent = new Event(AppcOperation.MaintenanceMode.toString()); + Event restart = new Event(AppcOperation.Restart.toString()); + + StateMachineMetadata.StateMachineMetadataBuilder builder = new StateMachineMetadata + .StateMachineMetadataBuilder(); + + builder = builder.addState(notInstantiated); + builder = builder.addState(instantiated); + builder = builder.addState(starting); + builder = builder.addState(started); + builder = builder.addState(error); + builder = builder.addState(unknown); + builder = builder.addState(stopping); + builder = builder.addState(stopped); + builder = builder.addState(enteringMaintenanceMode); + builder = builder.addState(maintenanceMode); + builder = builder.addState(restarting); + + builder = builder.addEvent(start); + builder = builder.addEvent(stop); + builder = builder.addEvent(restart); + builder = builder.addEvent(maintenanceModeEvent); + + /* + * for addTransition: + * param 1: current state; param 2: received command/request; param 3: new transition state + */ + // start + builder = builder.addTransition(stopped, start, starting); + builder = builder.addTransition(maintenanceMode, start, starting); + builder = builder.addTransition(error, start, starting); + // stop + builder = builder.addTransition(started, stop, stopping); + builder = builder.addTransition(starting, stop, stopping); + builder = builder.addTransition(enteringMaintenanceMode, stop, stopping); + builder = builder.addTransition(maintenanceMode, stop, stopping); + builder = builder.addTransition(error, stop, stopping); + // maintenance mode + builder = builder.addTransition( + started, maintenanceModeEvent, enteringMaintenanceMode); + // restart + builder = builder.addTransition(stopped, restart, restarting); + builder = builder.addTransition(starting, restart, restarting); + builder = builder.addTransition(started, restart, restarting); + builder = builder.addTransition(enteringMaintenanceMode, restart, restarting); + builder = builder.addTransition(maintenanceMode, restart, restarting); + builder = builder.addTransition(error, restart, restarting); + + return builder.build(); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamStates.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamStates.java new file mode 100644 index 000000000..70a044bfa --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/AppcOamStates.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.osgi.framework.Bundle; + +public enum AppcOamStates { + EnteringMaintenanceMode(0), + Error(0), + Instantiated(Bundle.INSTALLED), + MaintenanceMode(0), + NotInstantiated(Bundle.UNINSTALLED), + Restarting(0), + Started(Bundle.ACTIVE), + Starting(Bundle.STARTING), + Stopped(Bundle.RESOLVED), + Stopping(Bundle.STOPPING), + Unknown(0); + + int osgiBundleState; + + AppcOamStates(Integer bundleState) { + osgiBundleState = bundleState; + } + + public static AppcOamStates getOamStateFromBundleState(int bundleState) { + for (AppcOamStates aState : values()) { + if (aState.osgiBundleState == bundleState) { + return aState; + } + } + return Unknown; + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReader.java new file mode 100644 index 000000000..2ba949f38 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReader.java @@ -0,0 +1,493 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.onap.appc.statemachine.StateMetaDataReader; +import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +/** + * Reader for VNF MetaData + */ +public class VnfMetaDataReader implements StateMetaDataReader { + + /** + * VNF Operations + */ + public enum VNFOperation { + + Configure, Test, HealthCheck, Start, Terminate, Restart, Rebuild, Stop, ConfigModify, + ConfigScaleOut,ConfigRestore,Backup, Snapshot, + SoftwareUpload, LiveUpgrade, Rollback, Sync, Audit, Test_lic, Migrate, Evacuate, + ConfigBackup, ConfigBackupDelete, ConfigExport, + Lock(true), Unlock(true), CheckLock(true), StartApplication,StopApplication; + + private boolean builtIn; + + VNFOperation(boolean builtIn) { + this.builtIn = builtIn; + } + + VNFOperation() { + this(false); + } + } + + /** + * VNF States + */ + enum VNFStates { + Not_Instantiated, Instantiated, Configuring, Configured, Testing, Tested, + Rebuilding, Restarting, Starting, + Error, Running, Unknown, Terminating, Stopping, Stopped, + Backing_Up, Snapshotting, Software_Uploading, Upgrading, + Rollbacking, Licensing, Migrating, Evacuating, + NOT_ORCHESTRATED("NOT ORCHESTRATED"), Created; + + String stateName; + + VNFStates(String name) { + this.stateName = name; + } + + VNFStates() { + this.stateName = name(); + } + + @Override + public String toString() { + return this.stateName; + } + } + + @Override + public StateMachineMetadata readMetadata() { + State notInstantiated = new State(VNFStates.Not_Instantiated.toString()); + State instantiated = new State(VNFStates.Instantiated.toString()); + State configuring = new State(VNFStates.Configuring.toString()); + State configured = new State(VNFStates.Configured.toString()); + State testing = new State(VNFStates.Testing.toString()); + State tested = new State(VNFStates.Tested.toString()); + State rebuilding = new State(VNFStates.Rebuilding.toString()); + State restarting = new State(VNFStates.Restarting.toString()); + State starting = new State(VNFStates.Starting.toString()); + State error = new State(VNFStates.Error.toString()); + State running = new State(VNFStates.Running.toString()); + State unknown = new State(VNFStates.Unknown.toString()); + State terminating = new State(VNFStates.Terminating.toString()); + State stopping = new State(VNFStates.Stopping.toString()); + State stopped = new State(VNFStates.Stopped.toString()); + State notOrchestrated = new State(VNFStates.NOT_ORCHESTRATED.toString()); + + State backingUp = new State(VNFStates.Backing_Up.toString()); + State snapshotting = new State(VNFStates.Snapshotting.toString()); + State softwareUploading = new State(VNFStates.Software_Uploading.toString()); + State upgrading = new State(VNFStates.Upgrading.toString()); + State rollbacking = new State(VNFStates.Rollbacking.toString()); + + State migrating = new State(VNFStates.Migrating.toString()); + State evacuating = new State(VNFStates.Evacuating.toString()); + State created= new State(VNFStates.Created.toString()); + + Event startApplication = new Event(VNFOperation.StartApplication.toString()); + Event configure = new Event(VNFOperation.Configure.toString()); + Event healthcheck = new Event(VNFOperation.HealthCheck.toString()); + Event test = new Event(VNFOperation.Test.toString()); + Event start = new Event(VNFOperation.Start.toString()); + Event terminate = new Event(VNFOperation.Terminate.toString()); + Event restart = new Event(VNFOperation.Restart.toString()); + Event rebuild = new Event(VNFOperation.Rebuild.toString()); + Event stop = new Event(VNFOperation.Stop.toString()); + Event configModify = new Event(VNFOperation.ConfigModify.toString()); + Event configScaleout = new Event(VNFOperation.ConfigScaleOut.toString()); + Event configRestore = new Event(VNFOperation.ConfigRestore.toString()); + Event backup = new Event(VNFOperation.Backup.toString()); + Event snapshot = new Event(VNFOperation.Snapshot.toString()); + Event softwareUpload = new Event(VNFOperation.SoftwareUpload.toString()); + Event liveUpgrade = new Event(VNFOperation.LiveUpgrade.toString()); + Event rollback = new Event(VNFOperation.Rollback.toString()); + Event sync = new Event(VNFOperation.Sync.toString()); + Event audit = new Event(VNFOperation.Audit.toString()); + Event migrate = new Event(VNFOperation.Migrate.toString()); + Event evacuate = new Event(VNFOperation.Evacuate.toString()); + Event configBackup = new Event(VNFOperation.ConfigBackup.toString()); + Event configBackupDelete = new Event(VNFOperation.ConfigBackupDelete.toString()); + Event configExport = new Event(VNFOperation.ConfigExport.toString()); + Event stopApplication= new Event(VNFOperation.StopApplication.toString()); + + Event lock = new Event(VNFOperation.Lock.toString()); + Event unlock = new Event(VNFOperation.Unlock.toString()); + Event checklock = new Event(VNFOperation.CheckLock.toString()); + + Event success = new Event(VNFOperationOutcome.SUCCESS.toString()); + Event failure = new Event(VNFOperationOutcome.FAILURE.toString()); + + + StateMachineMetadata.StateMachineMetadataBuilder builder = + new StateMachineMetadata.StateMachineMetadataBuilder(); + + builder = builder.addState(notInstantiated); + builder = builder.addState(instantiated); + builder = builder.addState(configuring); + builder = builder.addState(configured); + builder = builder.addState(testing); + builder = builder.addState(tested); + builder = builder.addState(rebuilding); + builder = builder.addState(restarting); + builder = builder.addState(starting); + builder = builder.addState(error); + builder = builder.addState(running); + builder = builder.addState(unknown); + builder = builder.addState(terminating); + builder = builder.addState(stopping); + builder = builder.addState(stopped); + + builder = builder.addState(backingUp); + builder = builder.addState(snapshotting); + builder = builder.addState(softwareUploading); + builder = builder.addState(upgrading); + builder = builder.addState(rollbacking); + builder = builder.addState(migrating); + builder = builder.addState(evacuating); + builder = builder.addState(notOrchestrated); + builder = builder.addState(created); + builder = builder.addEvent(startApplication); + builder = builder.addEvent(configure); + builder = builder.addEvent(test); + builder = builder.addEvent(start); + builder = builder.addEvent(terminate); + builder = builder.addEvent(restart); + builder = builder.addEvent(rebuild); + builder = builder.addEvent(success); + builder = builder.addEvent(failure); + builder = builder.addEvent(stop); + builder = builder.addEvent(configModify); + builder = builder.addEvent(configScaleout); + builder = builder.addEvent(configRestore); + builder = builder.addEvent(healthcheck); + builder = builder.addEvent(backup); + builder = builder.addEvent(snapshot); + builder = builder.addEvent(softwareUpload); + builder = builder.addEvent(liveUpgrade); + builder = builder.addEvent(rollback); + builder = builder.addEvent(sync); + builder = builder.addEvent(audit); + builder = builder.addEvent(migrate); + builder = builder.addEvent(evacuate); + builder = builder.addEvent(lock); + builder = builder.addEvent(unlock); + builder = builder.addEvent(checklock); + builder = builder.addEvent(configBackup); + builder = builder.addEvent(configBackupDelete); + builder = builder.addEvent(configExport); + builder = builder.addEvent(stopApplication); + + builder = builder.addTransition(notOrchestrated,configure,configuring); + builder = builder.addTransition(notOrchestrated,test,testing); + builder = builder.addTransition(notOrchestrated,start,starting); + builder = builder.addTransition(notOrchestrated,terminate,terminating); + builder = builder.addTransition(notOrchestrated,restart,restarting); + builder = builder.addTransition(notOrchestrated,rebuild,rebuilding); + builder = builder.addTransition(notOrchestrated,stop,stopping); + builder = builder.addTransition(notOrchestrated,configModify,configuring); + builder = builder.addTransition(notOrchestrated,configScaleout,configuring); + builder = builder.addTransition(notOrchestrated,configRestore,configuring); + builder = builder.addTransition(notOrchestrated,healthcheck,testing); + builder = builder.addTransition(notOrchestrated,backup,backingUp); + builder = builder.addTransition(notOrchestrated,snapshot,snapshotting); + builder = builder.addTransition(notOrchestrated,softwareUpload,softwareUploading); + builder = builder.addTransition(notOrchestrated,liveUpgrade,upgrading); + builder = builder.addTransition(notOrchestrated,rollback,rollbacking); + builder = builder.addTransition(notOrchestrated,migrate,migrating); + builder = builder.addTransition(notOrchestrated,evacuate,evacuating); + builder = builder.addTransition(notOrchestrated,lock,notOrchestrated); + builder = builder.addTransition(notOrchestrated,unlock,notOrchestrated); + builder = builder.addTransition(notOrchestrated,checklock,notOrchestrated); + builder = builder.addTransition(notOrchestrated,startApplication,starting); + builder = builder.addTransition(notOrchestrated,stopApplication,stopping); + builder = builder.addTransition(notOrchestrated,configBackup,notOrchestrated); + + builder = builder.addTransition(created,configure,configuring); + builder = builder.addTransition(created,test,testing); + builder = builder.addTransition(created,start,starting); + builder = builder.addTransition(created,terminate,terminating); + builder = builder.addTransition(created,restart,restarting); + builder = builder.addTransition(created,rebuild,rebuilding); + builder = builder.addTransition(created,stop,stopping); + builder = builder.addTransition(created,configModify,configuring); + builder = builder.addTransition(created,configScaleout,configuring); + builder = builder.addTransition(created,configRestore,configuring); + builder = builder.addTransition(created,healthcheck,testing); + builder = builder.addTransition(created,backup,backingUp); + builder = builder.addTransition(created,snapshot,snapshotting); + builder = builder.addTransition(created,softwareUpload,softwareUploading); + builder = builder.addTransition(created,liveUpgrade,upgrading); + builder = builder.addTransition(created,rollback,rollbacking); + builder = builder.addTransition(created,migrate,migrating); + builder = builder.addTransition(created,evacuate,evacuating); + builder = builder.addTransition(created,lock,created); + builder = builder.addTransition(created,unlock,created); + builder = builder.addTransition(created,checklock,created); + builder = builder.addTransition(created,startApplication,starting); + builder = builder.addTransition(created,stopApplication,stopping); + builder = builder.addTransition(created,configBackup,created); + + builder = builder.addTransition(instantiated,configure,configuring); + builder = builder.addTransition(instantiated,test,testing); + builder = builder.addTransition(instantiated,start,starting); + builder = builder.addTransition(instantiated,terminate,terminating); + builder = builder.addTransition(instantiated,restart,restarting); + builder = builder.addTransition(instantiated,rebuild,rebuilding); + builder = builder.addTransition(instantiated,stop,stopping); + builder = builder.addTransition(instantiated,configModify,configuring); + builder = builder.addTransition(instantiated,configScaleout,configuring); + builder = builder.addTransition(instantiated,configRestore,configuring); + builder = builder.addTransition(instantiated,healthcheck,testing); + builder = builder.addTransition(instantiated,backup,backingUp); + builder = builder.addTransition(instantiated,snapshot,snapshotting); + builder = builder.addTransition(instantiated,softwareUpload,softwareUploading); + builder = builder.addTransition(instantiated,liveUpgrade,upgrading); + builder = builder.addTransition(instantiated,rollback,rollbacking); + builder = builder.addTransition(instantiated,migrate,migrating); + builder = builder.addTransition(instantiated,evacuate,evacuating); + builder = builder.addTransition(instantiated,lock,instantiated); + builder = builder.addTransition(instantiated,unlock,instantiated); + builder = builder.addTransition(instantiated,checklock,instantiated); + + builder = builder.addTransition(configured,configure,configuring); + builder = builder.addTransition(configured,test,testing); + builder = builder.addTransition(configured,start,starting); + builder = builder.addTransition(configured,terminate,terminating); + builder = builder.addTransition(configured,restart,restarting); + builder = builder.addTransition(configured,rebuild,rebuilding); + builder = builder.addTransition(configured,stop,stopping); + builder = builder.addTransition(configured,configModify,configuring); + builder = builder.addTransition(configured,configScaleout,configuring); + builder = builder.addTransition(configured,configRestore,configuring); + builder = builder.addTransition(configured,healthcheck,testing); + builder = builder.addTransition(configured,backup,backingUp); + builder = builder.addTransition(configured,snapshot,snapshotting); + builder = builder.addTransition(configured,softwareUpload,softwareUploading); + builder = builder.addTransition(configured,liveUpgrade,upgrading); + builder = builder.addTransition(configured,rollback,rollbacking); + builder = builder.addTransition(configured,sync,configured); + builder = builder.addTransition(configured,audit,configured); + builder = builder.addTransition(configured,migrate,migrating); + builder = builder.addTransition(configured,evacuate,evacuating); + builder = builder.addTransition(configured,lock,configured); + builder = builder.addTransition(configured,unlock,configured); + builder = builder.addTransition(configured,checklock,configured); + builder = builder.addTransition(configured,configBackup,configured); + builder = builder.addTransition(configured,configBackupDelete,configured); + builder = builder.addTransition(configured,configExport,configured); + builder = builder.addTransition(configured,stopApplication,stopping); + + builder = builder.addTransition(tested,configure,configuring); + builder = builder.addTransition(tested,test,testing); + builder = builder.addTransition(tested,start,starting); + builder = builder.addTransition(tested,terminate,terminating); + builder = builder.addTransition(tested,restart,restarting); + builder = builder.addTransition(tested,rebuild,rebuilding); + builder = builder.addTransition(tested,stop,stopping); + builder = builder.addTransition(tested,configModify,configuring); + builder = builder.addTransition(tested,configScaleout,configuring); + builder = builder.addTransition(tested,configRestore,configuring); + builder = builder.addTransition(tested,healthcheck,testing); + builder = builder.addTransition(tested,backup,backingUp); + builder = builder.addTransition(tested,snapshot,snapshotting); + builder = builder.addTransition(tested,softwareUpload,softwareUploading); + builder = builder.addTransition(tested,liveUpgrade,upgrading); + builder = builder.addTransition(tested,rollback,rollbacking); + builder = builder.addTransition(tested,sync,tested); + builder = builder.addTransition(tested,audit,tested); + builder = builder.addTransition(tested,migrate,migrating); + builder = builder.addTransition(tested,evacuate,evacuating); + builder = builder.addTransition(tested,lock,tested); + builder = builder.addTransition(tested,unlock,tested); + builder = builder.addTransition(tested,checklock,tested); + builder = builder.addTransition(tested,configBackup,tested); + builder = builder.addTransition(tested,configBackupDelete,tested); + builder = builder.addTransition(tested,configExport,tested); + builder = builder.addTransition(tested,stopApplication,stopping); + + builder = builder.addTransition(running,configure,configuring); + builder = builder.addTransition(running,test,testing); + builder = builder.addTransition(running,start,starting); + builder = builder.addTransition(running,terminate,terminating); + builder = builder.addTransition(running,restart,restarting); + builder = builder.addTransition(running,rebuild,rebuilding); + builder = builder.addTransition(running,stop,stopping); + builder = builder.addTransition(running,configModify,configuring); + builder = builder.addTransition(running,configScaleout,configuring); + builder = builder.addTransition(running,configRestore,configuring); + builder = builder.addTransition(running,healthcheck,testing); + builder = builder.addTransition(running,backup,backingUp); + builder = builder.addTransition(running,snapshot,snapshotting); + builder = builder.addTransition(running,softwareUpload,softwareUploading); + builder = builder.addTransition(running,liveUpgrade,upgrading); + builder = builder.addTransition(running,rollback,rollbacking); + builder = builder.addTransition(running,sync,running); + builder = builder.addTransition(running,audit,running); + builder = builder.addTransition(running,migrate,migrating); + builder = builder.addTransition(running,evacuate,evacuating); + builder = builder.addTransition(running,lock,running); + builder = builder.addTransition(running,unlock,running); + builder = builder.addTransition(running,checklock,running); + builder = builder.addTransition(running,configBackup,running); + builder = builder.addTransition(running,configBackupDelete,running); + builder = builder.addTransition(running,configExport,running); + builder = builder.addTransition(running,stopApplication,stopping); + + builder = builder.addTransition(error,configure,configuring); + builder = builder.addTransition(error,test,testing); + builder = builder.addTransition(error,start,starting); + builder = builder.addTransition(error,terminate,terminating); + builder = builder.addTransition(error,restart,restarting); + builder = builder.addTransition(error,rebuild,rebuilding); + builder = builder.addTransition(error,stop,stopping); + builder = builder.addTransition(error,configModify,configuring); + builder = builder.addTransition(error,configScaleout,configuring); + builder = builder.addTransition(error,configRestore,configuring); + builder = builder.addTransition(error,healthcheck,testing); + builder = builder.addTransition(error,backup,backingUp); + builder = builder.addTransition(error,snapshot,snapshotting); + builder = builder.addTransition(error,softwareUpload,softwareUploading); + builder = builder.addTransition(error,liveUpgrade,upgrading); + builder = builder.addTransition(error,rollback,rollbacking); + builder = builder.addTransition(error,sync,error); + builder = builder.addTransition(error,audit,error); + builder = builder.addTransition(error,migrate,migrating); + builder = builder.addTransition(error,evacuate,evacuating); + builder = builder.addTransition(error,lock,error); + builder = builder.addTransition(error,unlock,error); + builder = builder.addTransition(error,checklock,error); + builder = builder.addTransition(error,configBackup,error); + builder = builder.addTransition(error,configBackupDelete,error); + builder = builder.addTransition(error,configExport,error); + builder = builder.addTransition(error,stopApplication,stopping); + + builder = builder.addTransition(unknown,configure,configuring); + builder = builder.addTransition(unknown,test,testing); + builder = builder.addTransition(unknown,start,starting); + builder = builder.addTransition(unknown,terminate,terminating); + builder = builder.addTransition(unknown,restart,restarting); + builder = builder.addTransition(unknown,rebuild,rebuilding); + builder = builder.addTransition(unknown,stop,stopping); + builder = builder.addTransition(unknown,configModify,configuring); + builder = builder.addTransition(unknown,configScaleout,configuring); + builder = builder.addTransition(unknown,configRestore,configuring); + builder = builder.addTransition(unknown,healthcheck,testing); + builder = builder.addTransition(unknown,backup,backingUp); + builder = builder.addTransition(unknown,snapshot,snapshotting); + builder = builder.addTransition(unknown,softwareUpload,softwareUploading); + builder = builder.addTransition(unknown,liveUpgrade,upgrading); + builder = builder.addTransition(unknown,rollback,rollbacking); + builder = builder.addTransition(unknown,sync,unknown); + builder = builder.addTransition(unknown,audit,unknown); + builder = builder.addTransition(unknown,migrate,migrating); + builder = builder.addTransition(unknown,evacuate,evacuating); + builder = builder.addTransition(unknown,lock,unknown); + builder = builder.addTransition(unknown,unlock,unknown); + builder = builder.addTransition(unknown,checklock,unknown); + builder = builder.addTransition(unknown,configBackup,unknown); + builder = builder.addTransition(unknown,configBackupDelete,unknown); + builder = builder.addTransition(unknown,configExport,unknown); + builder = builder.addTransition(unknown,stopApplication,stopping); + + builder = builder.addTransition(stopped,configure,configuring); + builder = builder.addTransition(stopped,test,testing); + builder = builder.addTransition(stopped,start,starting); + builder = builder.addTransition(stopped,terminate,terminating); + builder = builder.addTransition(stopped,restart,restarting); + builder = builder.addTransition(stopped,rebuild,rebuilding); + builder = builder.addTransition(stopped,configModify,configuring); + builder = builder.addTransition(stopped,configScaleout,configuring); + builder = builder.addTransition(stopped,configRestore,configuring); + builder = builder.addTransition(stopped,healthcheck,testing); + builder = builder.addTransition(stopped,backup,backingUp); + builder = builder.addTransition(stopped,snapshot,snapshotting); + builder = builder.addTransition(stopped,softwareUpload,softwareUploading); + builder = builder.addTransition(stopped,liveUpgrade,upgrading); + builder = builder.addTransition(stopped,rollback,rollbacking); + builder = builder.addTransition(stopped,migrate,migrating); + builder = builder.addTransition(stopped,evacuate,evacuating); + builder = builder.addTransition(stopped,lock,stopped); + builder = builder.addTransition(stopped,unlock,stopped); + builder = builder.addTransition(stopped,checklock,stopped); + + builder = builder.addTransition(configuring,success,configured); + builder = builder.addTransition(configuring,failure,error); + + builder = builder.addTransition(testing,success,tested); + builder = builder.addTransition(testing,failure,error); + + builder = builder.addTransition(restarting,success,running); + builder = builder.addTransition(restarting,failure,error); + + builder = builder.addTransition(starting,success,running); + builder = builder.addTransition(starting,failure,error); + + builder = builder.addTransition(terminating,success,notInstantiated); + builder = builder.addTransition(terminating,failure,error); + + builder = builder.addTransition(rebuilding,success,running); + builder = builder.addTransition(rebuilding,failure,error); + + builder = builder.addTransition(stopping,success,stopped); + builder = builder.addTransition(stopping,failure,error); + + builder = builder.addTransition(backingUp,success,running); + builder = builder.addTransition(backingUp,failure,error); + + builder = builder.addTransition(snapshotting,success,running); + builder = builder.addTransition(snapshotting,failure,error); + + builder = builder.addTransition(softwareUploading,success,running); + builder = builder.addTransition(softwareUploading,failure,error); + + builder = builder.addTransition(upgrading,success,running); + builder = builder.addTransition(upgrading,failure,error); + + builder = builder.addTransition(rollbacking,success,running); + builder = builder.addTransition(rollbacking,failure,error); + + builder = builder.addTransition(migrating,success,running); + builder = builder.addTransition(migrating,failure,error); + + builder = builder.addTransition(evacuating,success,running); + builder = builder.addTransition(evacuating,failure,error); + + + builder = builder.addTransition(configured,startApplication,starting); + builder = builder.addTransition(tested,startApplication,starting); + builder = builder.addTransition(error,startApplication,starting); + builder = builder.addTransition(unknown,startApplication,starting); + builder = builder.addTransition(running,startApplication,starting); + + return builder.build(); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Event.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Event.java new file mode 100644 index 000000000..5e9b7c813 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Event.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +/** + * Event Object + */ +public class Event{ + private final String eventName; + private final int hashCode; + + /** + * Constructor + * @param eventName String of the event name + */ + public Event(String eventName) { + this.eventName = eventName; + this.hashCode = this.eventName.toLowerCase().hashCode(); + } + + @Override + public int hashCode() { + return hashCode; + } + @Override + public boolean equals(Object obj) { + if(obj == null){ + return false; + } + if(!(obj instanceof Event)){ + return false; + } + Event event = (Event)obj; + return this.eventName.equalsIgnoreCase(event.getEventName()); + } + + public String getEventName() { + return eventName; + } + + @Override + public String toString(){ + return this.eventName; + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Response.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Response.java new file mode 100644 index 000000000..49b6c909b --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Response.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +/** + * Response object + */ +public enum Response { + NO_TRANSITION_DEFINED, + NO_STATE_CHANGE, + VALID_TRANSITION; + + @Override + public String toString(){ + return this.name(); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/State.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/State.java new file mode 100644 index 000000000..117cd76c0 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/State.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import java.util.ArrayList; +import java.util.List; + +/** + * State Object + */ +public class State { + private final String stateName; + private final int hashCode; + private final List transitions; + + /** + * Constructor + * @param stateName String of the state name + */ + public State(String stateName) { + this.stateName = stateName; + this.hashCode = stateName.toLowerCase().hashCode(); + this.transitions = new ArrayList<>(); + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof State)) { + return false; + } + State state = (State)obj; + return this.stateName.equalsIgnoreCase(state.getStateName()); + } + + public String getStateName() { + return stateName; + } + + void addTransition(Transition transition) { + this.transitions.add(transition); + } + + public List getTransitions() { + return transitions; + } + + @Override + public String toString() { + return this.stateName; + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineMetadata.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineMetadata.java new file mode 100644 index 000000000..02088b26e --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineMetadata.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import java.util.HashSet; +import java.util.Set; + +public class StateMachineMetadata { + + private Set states; + private Set events; + + private StateMachineMetadata(StateMachineMetadataBuilder builder){ + states = builder.states; + events = builder.events; + } + + public Set getStates() { + return states; + } + + public Set getEvents() { + return events; + } + + public static class StateMachineMetadataBuilder{ + + private Set states; + private Set events; + + public StateMachineMetadataBuilder(){ + states = new HashSet<>(); + events = new HashSet<>(); + } + + public StateMachineMetadataBuilder addState(State state){ + this.states.add(state); + return this; + } + + public StateMachineMetadataBuilder addEvent(Event event){ + this.events.add(event); + return this; + } + + public StateMachineMetadataBuilder addTransition(State currentState,Event event,State nextState){ + Transition transition = new Transition(event,nextState); + currentState.addTransition(transition); + return this; + } + + public StateMachineMetadata build(){ + return new StateMachineMetadata(this); + } + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineResponse.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineResponse.java new file mode 100644 index 000000000..9fc401527 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/StateMachineResponse.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + + +public class StateMachineResponse { + private State nextState; + private Response response; + + public StateMachineResponse(){ + // do nothing + } + + public State getNextState() { + return nextState; + } + + public Response getResponse() { + return response; + } + + public void setNextState(State nextState) { + this.nextState = nextState; + } + + public void setResponse(Response response) { + this.response = response; + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Transition.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Transition.java new file mode 100644 index 000000000..2c6ee6366 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/main/java/org/onap/appc/statemachine/objects/Transition.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +/** + * Transition Object + */ +public class Transition { + private Event event; + private State nextState; + + /** + * Constructor + * @param event which triggers the transition + * @param nextState of State which indicates the transition targeted state + */ + Transition(Event event, State nextState) { + this.event = event; + this.nextState = nextState; + } + + public Event getEvent() { + return event; + } + + public State getNextState() { + return nextState; + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMachine.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMachine.java deleted file mode 100644 index 52350852e..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMachine.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine; - -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineResponse; - -/** - * Interface of the StateMachine - */ -public interface StateMachine { - /** - * Handle event - * @param currentState the current State which the event should be handled from - * @param event the Event that needs to be handled - * @return StateMachineResponse - * @throws InvalidInputException - * when the passed in currentState and event are not predefined or no relevant transition - */ - StateMachineResponse handleEvent(State currentState, Event event) throws InvalidInputException; -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMetaDataReader.java deleted file mode 100644 index fe2b193e1..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/StateMetaDataReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine; - -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -public interface StateMetaDataReader { - StateMachineMetadata readMetadata(); -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineFactory.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineFactory.java deleted file mode 100644 index bfcafeb7d..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl; - -import org.onap.appc.statemachine.StateMachine; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -/** - * Factory of StateMachine - */ -public class StateMachineFactory { - - private StateMachineFactory(){ - throw new IllegalAccessError("StateMachineFactory"); - } - - public static StateMachine getStateMachine(StateMachineMetadata metadata){ - return new StateMachineImpl(metadata); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineImpl.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineImpl.java deleted file mode 100644 index b56250708..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/StateMachineImpl.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl; - -import java.util.HashSet; -import java.util.Set; - -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.statemachine.StateMachine; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.Response; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; -import org.onap.appc.statemachine.objects.StateMachineResponse; -import org.onap.appc.statemachine.objects.Transition; - -/** - * Implementation of StateMachine - */ -public class StateMachineImpl implements StateMachine { - private static final String invalidInputFormat = "VNF State or incoming event is invalid. State = %s event = %s"; - static final String toStringFormat = "StateMachineImpl{states=%s, events=%s}"; - - private final Set states; - private final Set events; - - StateMachineImpl(StateMachineMetadata metadata){ - this.states = new HashSet<>(); - this.states.addAll(metadata.getStates()); - this.events = new HashSet<>(); - this.events.addAll(metadata.getEvents()); - } - - @Override - public StateMachineResponse handleEvent(State inputState, Event event) throws InvalidInputException{ - - if(!validateInputs(inputState,event)){ - throw new InvalidInputException(String.format(invalidInputFormat, inputState, event)); - } - - StateMachineResponse response = new StateMachineResponse(); - State currentState = null; - State nextState = null; - for(State stateInSet:states){ - if(stateInSet.equals(inputState)){ - currentState = stateInSet; - break; - } - } - if (currentState != null) { - for (Transition transition : currentState.getTransitions()) { - if (event.equals(transition.getEvent())) { - nextState = transition.getNextState(); - } - } - } - if(nextState == null){ - response.setResponse(Response.NO_TRANSITION_DEFINED); - } - else if(inputState.equals(nextState)){ - response.setResponse(Response.NO_STATE_CHANGE); - } - else{ - response.setResponse(Response.VALID_TRANSITION); - } - response.setNextState(nextState); - return response; - } - - boolean validateInputs(State state,Event event) { - return state != null - && event != null - && this.states.contains(state) - && this.events.contains(event); - } - - @Override - public String toString() { - return String.format(toStringFormat, states, events); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReader.java deleted file mode 100644 index 7451cf3af..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReader.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.onap.appc.statemachine.StateMetaDataReader; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -/** - * Reader for APPC OAM MetaData - */ -public class AppcOamMetaDataReader implements StateMetaDataReader { - - /** - * APPC Operation Enum - */ - public enum AppcOperation { - MaintenanceMode, - Restart, - Start, - Stop - } - - @Override - public StateMachineMetadata readMetadata() { - State notInstantiated = new State(AppcOamStates.NotInstantiated.toString()); - State instantiated = new State(AppcOamStates.Instantiated.toString()); - State restarting = new State(AppcOamStates.Restarting.toString()); - State starting = new State(AppcOamStates.Starting.toString()); - State started = new State(AppcOamStates.Started.toString()); - State enteringMaintenanceMode = new State(AppcOamStates.EnteringMaintenanceMode.toString()); - State maintenanceMode = new State(AppcOamStates.MaintenanceMode.toString()); - State error = new State(AppcOamStates.Error.toString()); - State unknown = new State(AppcOamStates.Unknown.toString()); - State stopping = new State(AppcOamStates.Stopping.toString()); - State stopped = new State(AppcOamStates.Stopped.toString()); - - Event start = new Event(AppcOperation.Start.toString()); - Event stop = new Event(AppcOperation.Stop.toString()); - Event maintenanceModeEvent = new Event(AppcOperation.MaintenanceMode.toString()); - Event restart = new Event(AppcOperation.Restart.toString()); - - StateMachineMetadata.StateMachineMetadataBuilder builder = new StateMachineMetadata - .StateMachineMetadataBuilder(); - - builder = builder.addState(notInstantiated); - builder = builder.addState(instantiated); - builder = builder.addState(starting); - builder = builder.addState(started); - builder = builder.addState(error); - builder = builder.addState(unknown); - builder = builder.addState(stopping); - builder = builder.addState(stopped); - builder = builder.addState(enteringMaintenanceMode); - builder = builder.addState(maintenanceMode); - builder = builder.addState(restarting); - - builder = builder.addEvent(start); - builder = builder.addEvent(stop); - builder = builder.addEvent(restart); - builder = builder.addEvent(maintenanceModeEvent); - - /* - * for addTransition: - * param 1: current state; param 2: received command/request; param 3: new transition state - */ - // start - builder = builder.addTransition(stopped, start, starting); - builder = builder.addTransition(maintenanceMode, start, starting); - builder = builder.addTransition(error, start, starting); - // stop - builder = builder.addTransition(started, stop, stopping); - builder = builder.addTransition(starting, stop, stopping); - builder = builder.addTransition(enteringMaintenanceMode, stop, stopping); - builder = builder.addTransition(maintenanceMode, stop, stopping); - builder = builder.addTransition(error, stop, stopping); - // maintenance mode - builder = builder.addTransition( - started, maintenanceModeEvent, enteringMaintenanceMode); - // restart - builder = builder.addTransition(stopped, restart, restarting); - builder = builder.addTransition(starting, restart, restarting); - builder = builder.addTransition(started, restart, restarting); - builder = builder.addTransition(enteringMaintenanceMode, restart, restarting); - builder = builder.addTransition(maintenanceMode, restart, restarting); - builder = builder.addTransition(error, restart, restarting); - - return builder.build(); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStates.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStates.java deleted file mode 100644 index 70a044bfa..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStates.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.osgi.framework.Bundle; - -public enum AppcOamStates { - EnteringMaintenanceMode(0), - Error(0), - Instantiated(Bundle.INSTALLED), - MaintenanceMode(0), - NotInstantiated(Bundle.UNINSTALLED), - Restarting(0), - Started(Bundle.ACTIVE), - Starting(Bundle.STARTING), - Stopped(Bundle.RESOLVED), - Stopping(Bundle.STOPPING), - Unknown(0); - - int osgiBundleState; - - AppcOamStates(Integer bundleState) { - osgiBundleState = bundleState; - } - - public static AppcOamStates getOamStateFromBundleState(int bundleState) { - for (AppcOamStates aState : values()) { - if (aState.osgiBundleState == bundleState) { - return aState; - } - } - return Unknown; - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReader.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReader.java deleted file mode 100644 index 2ba949f38..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReader.java +++ /dev/null @@ -1,493 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.onap.appc.statemachine.StateMetaDataReader; -import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -/** - * Reader for VNF MetaData - */ -public class VnfMetaDataReader implements StateMetaDataReader { - - /** - * VNF Operations - */ - public enum VNFOperation { - - Configure, Test, HealthCheck, Start, Terminate, Restart, Rebuild, Stop, ConfigModify, - ConfigScaleOut,ConfigRestore,Backup, Snapshot, - SoftwareUpload, LiveUpgrade, Rollback, Sync, Audit, Test_lic, Migrate, Evacuate, - ConfigBackup, ConfigBackupDelete, ConfigExport, - Lock(true), Unlock(true), CheckLock(true), StartApplication,StopApplication; - - private boolean builtIn; - - VNFOperation(boolean builtIn) { - this.builtIn = builtIn; - } - - VNFOperation() { - this(false); - } - } - - /** - * VNF States - */ - enum VNFStates { - Not_Instantiated, Instantiated, Configuring, Configured, Testing, Tested, - Rebuilding, Restarting, Starting, - Error, Running, Unknown, Terminating, Stopping, Stopped, - Backing_Up, Snapshotting, Software_Uploading, Upgrading, - Rollbacking, Licensing, Migrating, Evacuating, - NOT_ORCHESTRATED("NOT ORCHESTRATED"), Created; - - String stateName; - - VNFStates(String name) { - this.stateName = name; - } - - VNFStates() { - this.stateName = name(); - } - - @Override - public String toString() { - return this.stateName; - } - } - - @Override - public StateMachineMetadata readMetadata() { - State notInstantiated = new State(VNFStates.Not_Instantiated.toString()); - State instantiated = new State(VNFStates.Instantiated.toString()); - State configuring = new State(VNFStates.Configuring.toString()); - State configured = new State(VNFStates.Configured.toString()); - State testing = new State(VNFStates.Testing.toString()); - State tested = new State(VNFStates.Tested.toString()); - State rebuilding = new State(VNFStates.Rebuilding.toString()); - State restarting = new State(VNFStates.Restarting.toString()); - State starting = new State(VNFStates.Starting.toString()); - State error = new State(VNFStates.Error.toString()); - State running = new State(VNFStates.Running.toString()); - State unknown = new State(VNFStates.Unknown.toString()); - State terminating = new State(VNFStates.Terminating.toString()); - State stopping = new State(VNFStates.Stopping.toString()); - State stopped = new State(VNFStates.Stopped.toString()); - State notOrchestrated = new State(VNFStates.NOT_ORCHESTRATED.toString()); - - State backingUp = new State(VNFStates.Backing_Up.toString()); - State snapshotting = new State(VNFStates.Snapshotting.toString()); - State softwareUploading = new State(VNFStates.Software_Uploading.toString()); - State upgrading = new State(VNFStates.Upgrading.toString()); - State rollbacking = new State(VNFStates.Rollbacking.toString()); - - State migrating = new State(VNFStates.Migrating.toString()); - State evacuating = new State(VNFStates.Evacuating.toString()); - State created= new State(VNFStates.Created.toString()); - - Event startApplication = new Event(VNFOperation.StartApplication.toString()); - Event configure = new Event(VNFOperation.Configure.toString()); - Event healthcheck = new Event(VNFOperation.HealthCheck.toString()); - Event test = new Event(VNFOperation.Test.toString()); - Event start = new Event(VNFOperation.Start.toString()); - Event terminate = new Event(VNFOperation.Terminate.toString()); - Event restart = new Event(VNFOperation.Restart.toString()); - Event rebuild = new Event(VNFOperation.Rebuild.toString()); - Event stop = new Event(VNFOperation.Stop.toString()); - Event configModify = new Event(VNFOperation.ConfigModify.toString()); - Event configScaleout = new Event(VNFOperation.ConfigScaleOut.toString()); - Event configRestore = new Event(VNFOperation.ConfigRestore.toString()); - Event backup = new Event(VNFOperation.Backup.toString()); - Event snapshot = new Event(VNFOperation.Snapshot.toString()); - Event softwareUpload = new Event(VNFOperation.SoftwareUpload.toString()); - Event liveUpgrade = new Event(VNFOperation.LiveUpgrade.toString()); - Event rollback = new Event(VNFOperation.Rollback.toString()); - Event sync = new Event(VNFOperation.Sync.toString()); - Event audit = new Event(VNFOperation.Audit.toString()); - Event migrate = new Event(VNFOperation.Migrate.toString()); - Event evacuate = new Event(VNFOperation.Evacuate.toString()); - Event configBackup = new Event(VNFOperation.ConfigBackup.toString()); - Event configBackupDelete = new Event(VNFOperation.ConfigBackupDelete.toString()); - Event configExport = new Event(VNFOperation.ConfigExport.toString()); - Event stopApplication= new Event(VNFOperation.StopApplication.toString()); - - Event lock = new Event(VNFOperation.Lock.toString()); - Event unlock = new Event(VNFOperation.Unlock.toString()); - Event checklock = new Event(VNFOperation.CheckLock.toString()); - - Event success = new Event(VNFOperationOutcome.SUCCESS.toString()); - Event failure = new Event(VNFOperationOutcome.FAILURE.toString()); - - - StateMachineMetadata.StateMachineMetadataBuilder builder = - new StateMachineMetadata.StateMachineMetadataBuilder(); - - builder = builder.addState(notInstantiated); - builder = builder.addState(instantiated); - builder = builder.addState(configuring); - builder = builder.addState(configured); - builder = builder.addState(testing); - builder = builder.addState(tested); - builder = builder.addState(rebuilding); - builder = builder.addState(restarting); - builder = builder.addState(starting); - builder = builder.addState(error); - builder = builder.addState(running); - builder = builder.addState(unknown); - builder = builder.addState(terminating); - builder = builder.addState(stopping); - builder = builder.addState(stopped); - - builder = builder.addState(backingUp); - builder = builder.addState(snapshotting); - builder = builder.addState(softwareUploading); - builder = builder.addState(upgrading); - builder = builder.addState(rollbacking); - builder = builder.addState(migrating); - builder = builder.addState(evacuating); - builder = builder.addState(notOrchestrated); - builder = builder.addState(created); - builder = builder.addEvent(startApplication); - builder = builder.addEvent(configure); - builder = builder.addEvent(test); - builder = builder.addEvent(start); - builder = builder.addEvent(terminate); - builder = builder.addEvent(restart); - builder = builder.addEvent(rebuild); - builder = builder.addEvent(success); - builder = builder.addEvent(failure); - builder = builder.addEvent(stop); - builder = builder.addEvent(configModify); - builder = builder.addEvent(configScaleout); - builder = builder.addEvent(configRestore); - builder = builder.addEvent(healthcheck); - builder = builder.addEvent(backup); - builder = builder.addEvent(snapshot); - builder = builder.addEvent(softwareUpload); - builder = builder.addEvent(liveUpgrade); - builder = builder.addEvent(rollback); - builder = builder.addEvent(sync); - builder = builder.addEvent(audit); - builder = builder.addEvent(migrate); - builder = builder.addEvent(evacuate); - builder = builder.addEvent(lock); - builder = builder.addEvent(unlock); - builder = builder.addEvent(checklock); - builder = builder.addEvent(configBackup); - builder = builder.addEvent(configBackupDelete); - builder = builder.addEvent(configExport); - builder = builder.addEvent(stopApplication); - - builder = builder.addTransition(notOrchestrated,configure,configuring); - builder = builder.addTransition(notOrchestrated,test,testing); - builder = builder.addTransition(notOrchestrated,start,starting); - builder = builder.addTransition(notOrchestrated,terminate,terminating); - builder = builder.addTransition(notOrchestrated,restart,restarting); - builder = builder.addTransition(notOrchestrated,rebuild,rebuilding); - builder = builder.addTransition(notOrchestrated,stop,stopping); - builder = builder.addTransition(notOrchestrated,configModify,configuring); - builder = builder.addTransition(notOrchestrated,configScaleout,configuring); - builder = builder.addTransition(notOrchestrated,configRestore,configuring); - builder = builder.addTransition(notOrchestrated,healthcheck,testing); - builder = builder.addTransition(notOrchestrated,backup,backingUp); - builder = builder.addTransition(notOrchestrated,snapshot,snapshotting); - builder = builder.addTransition(notOrchestrated,softwareUpload,softwareUploading); - builder = builder.addTransition(notOrchestrated,liveUpgrade,upgrading); - builder = builder.addTransition(notOrchestrated,rollback,rollbacking); - builder = builder.addTransition(notOrchestrated,migrate,migrating); - builder = builder.addTransition(notOrchestrated,evacuate,evacuating); - builder = builder.addTransition(notOrchestrated,lock,notOrchestrated); - builder = builder.addTransition(notOrchestrated,unlock,notOrchestrated); - builder = builder.addTransition(notOrchestrated,checklock,notOrchestrated); - builder = builder.addTransition(notOrchestrated,startApplication,starting); - builder = builder.addTransition(notOrchestrated,stopApplication,stopping); - builder = builder.addTransition(notOrchestrated,configBackup,notOrchestrated); - - builder = builder.addTransition(created,configure,configuring); - builder = builder.addTransition(created,test,testing); - builder = builder.addTransition(created,start,starting); - builder = builder.addTransition(created,terminate,terminating); - builder = builder.addTransition(created,restart,restarting); - builder = builder.addTransition(created,rebuild,rebuilding); - builder = builder.addTransition(created,stop,stopping); - builder = builder.addTransition(created,configModify,configuring); - builder = builder.addTransition(created,configScaleout,configuring); - builder = builder.addTransition(created,configRestore,configuring); - builder = builder.addTransition(created,healthcheck,testing); - builder = builder.addTransition(created,backup,backingUp); - builder = builder.addTransition(created,snapshot,snapshotting); - builder = builder.addTransition(created,softwareUpload,softwareUploading); - builder = builder.addTransition(created,liveUpgrade,upgrading); - builder = builder.addTransition(created,rollback,rollbacking); - builder = builder.addTransition(created,migrate,migrating); - builder = builder.addTransition(created,evacuate,evacuating); - builder = builder.addTransition(created,lock,created); - builder = builder.addTransition(created,unlock,created); - builder = builder.addTransition(created,checklock,created); - builder = builder.addTransition(created,startApplication,starting); - builder = builder.addTransition(created,stopApplication,stopping); - builder = builder.addTransition(created,configBackup,created); - - builder = builder.addTransition(instantiated,configure,configuring); - builder = builder.addTransition(instantiated,test,testing); - builder = builder.addTransition(instantiated,start,starting); - builder = builder.addTransition(instantiated,terminate,terminating); - builder = builder.addTransition(instantiated,restart,restarting); - builder = builder.addTransition(instantiated,rebuild,rebuilding); - builder = builder.addTransition(instantiated,stop,stopping); - builder = builder.addTransition(instantiated,configModify,configuring); - builder = builder.addTransition(instantiated,configScaleout,configuring); - builder = builder.addTransition(instantiated,configRestore,configuring); - builder = builder.addTransition(instantiated,healthcheck,testing); - builder = builder.addTransition(instantiated,backup,backingUp); - builder = builder.addTransition(instantiated,snapshot,snapshotting); - builder = builder.addTransition(instantiated,softwareUpload,softwareUploading); - builder = builder.addTransition(instantiated,liveUpgrade,upgrading); - builder = builder.addTransition(instantiated,rollback,rollbacking); - builder = builder.addTransition(instantiated,migrate,migrating); - builder = builder.addTransition(instantiated,evacuate,evacuating); - builder = builder.addTransition(instantiated,lock,instantiated); - builder = builder.addTransition(instantiated,unlock,instantiated); - builder = builder.addTransition(instantiated,checklock,instantiated); - - builder = builder.addTransition(configured,configure,configuring); - builder = builder.addTransition(configured,test,testing); - builder = builder.addTransition(configured,start,starting); - builder = builder.addTransition(configured,terminate,terminating); - builder = builder.addTransition(configured,restart,restarting); - builder = builder.addTransition(configured,rebuild,rebuilding); - builder = builder.addTransition(configured,stop,stopping); - builder = builder.addTransition(configured,configModify,configuring); - builder = builder.addTransition(configured,configScaleout,configuring); - builder = builder.addTransition(configured,configRestore,configuring); - builder = builder.addTransition(configured,healthcheck,testing); - builder = builder.addTransition(configured,backup,backingUp); - builder = builder.addTransition(configured,snapshot,snapshotting); - builder = builder.addTransition(configured,softwareUpload,softwareUploading); - builder = builder.addTransition(configured,liveUpgrade,upgrading); - builder = builder.addTransition(configured,rollback,rollbacking); - builder = builder.addTransition(configured,sync,configured); - builder = builder.addTransition(configured,audit,configured); - builder = builder.addTransition(configured,migrate,migrating); - builder = builder.addTransition(configured,evacuate,evacuating); - builder = builder.addTransition(configured,lock,configured); - builder = builder.addTransition(configured,unlock,configured); - builder = builder.addTransition(configured,checklock,configured); - builder = builder.addTransition(configured,configBackup,configured); - builder = builder.addTransition(configured,configBackupDelete,configured); - builder = builder.addTransition(configured,configExport,configured); - builder = builder.addTransition(configured,stopApplication,stopping); - - builder = builder.addTransition(tested,configure,configuring); - builder = builder.addTransition(tested,test,testing); - builder = builder.addTransition(tested,start,starting); - builder = builder.addTransition(tested,terminate,terminating); - builder = builder.addTransition(tested,restart,restarting); - builder = builder.addTransition(tested,rebuild,rebuilding); - builder = builder.addTransition(tested,stop,stopping); - builder = builder.addTransition(tested,configModify,configuring); - builder = builder.addTransition(tested,configScaleout,configuring); - builder = builder.addTransition(tested,configRestore,configuring); - builder = builder.addTransition(tested,healthcheck,testing); - builder = builder.addTransition(tested,backup,backingUp); - builder = builder.addTransition(tested,snapshot,snapshotting); - builder = builder.addTransition(tested,softwareUpload,softwareUploading); - builder = builder.addTransition(tested,liveUpgrade,upgrading); - builder = builder.addTransition(tested,rollback,rollbacking); - builder = builder.addTransition(tested,sync,tested); - builder = builder.addTransition(tested,audit,tested); - builder = builder.addTransition(tested,migrate,migrating); - builder = builder.addTransition(tested,evacuate,evacuating); - builder = builder.addTransition(tested,lock,tested); - builder = builder.addTransition(tested,unlock,tested); - builder = builder.addTransition(tested,checklock,tested); - builder = builder.addTransition(tested,configBackup,tested); - builder = builder.addTransition(tested,configBackupDelete,tested); - builder = builder.addTransition(tested,configExport,tested); - builder = builder.addTransition(tested,stopApplication,stopping); - - builder = builder.addTransition(running,configure,configuring); - builder = builder.addTransition(running,test,testing); - builder = builder.addTransition(running,start,starting); - builder = builder.addTransition(running,terminate,terminating); - builder = builder.addTransition(running,restart,restarting); - builder = builder.addTransition(running,rebuild,rebuilding); - builder = builder.addTransition(running,stop,stopping); - builder = builder.addTransition(running,configModify,configuring); - builder = builder.addTransition(running,configScaleout,configuring); - builder = builder.addTransition(running,configRestore,configuring); - builder = builder.addTransition(running,healthcheck,testing); - builder = builder.addTransition(running,backup,backingUp); - builder = builder.addTransition(running,snapshot,snapshotting); - builder = builder.addTransition(running,softwareUpload,softwareUploading); - builder = builder.addTransition(running,liveUpgrade,upgrading); - builder = builder.addTransition(running,rollback,rollbacking); - builder = builder.addTransition(running,sync,running); - builder = builder.addTransition(running,audit,running); - builder = builder.addTransition(running,migrate,migrating); - builder = builder.addTransition(running,evacuate,evacuating); - builder = builder.addTransition(running,lock,running); - builder = builder.addTransition(running,unlock,running); - builder = builder.addTransition(running,checklock,running); - builder = builder.addTransition(running,configBackup,running); - builder = builder.addTransition(running,configBackupDelete,running); - builder = builder.addTransition(running,configExport,running); - builder = builder.addTransition(running,stopApplication,stopping); - - builder = builder.addTransition(error,configure,configuring); - builder = builder.addTransition(error,test,testing); - builder = builder.addTransition(error,start,starting); - builder = builder.addTransition(error,terminate,terminating); - builder = builder.addTransition(error,restart,restarting); - builder = builder.addTransition(error,rebuild,rebuilding); - builder = builder.addTransition(error,stop,stopping); - builder = builder.addTransition(error,configModify,configuring); - builder = builder.addTransition(error,configScaleout,configuring); - builder = builder.addTransition(error,configRestore,configuring); - builder = builder.addTransition(error,healthcheck,testing); - builder = builder.addTransition(error,backup,backingUp); - builder = builder.addTransition(error,snapshot,snapshotting); - builder = builder.addTransition(error,softwareUpload,softwareUploading); - builder = builder.addTransition(error,liveUpgrade,upgrading); - builder = builder.addTransition(error,rollback,rollbacking); - builder = builder.addTransition(error,sync,error); - builder = builder.addTransition(error,audit,error); - builder = builder.addTransition(error,migrate,migrating); - builder = builder.addTransition(error,evacuate,evacuating); - builder = builder.addTransition(error,lock,error); - builder = builder.addTransition(error,unlock,error); - builder = builder.addTransition(error,checklock,error); - builder = builder.addTransition(error,configBackup,error); - builder = builder.addTransition(error,configBackupDelete,error); - builder = builder.addTransition(error,configExport,error); - builder = builder.addTransition(error,stopApplication,stopping); - - builder = builder.addTransition(unknown,configure,configuring); - builder = builder.addTransition(unknown,test,testing); - builder = builder.addTransition(unknown,start,starting); - builder = builder.addTransition(unknown,terminate,terminating); - builder = builder.addTransition(unknown,restart,restarting); - builder = builder.addTransition(unknown,rebuild,rebuilding); - builder = builder.addTransition(unknown,stop,stopping); - builder = builder.addTransition(unknown,configModify,configuring); - builder = builder.addTransition(unknown,configScaleout,configuring); - builder = builder.addTransition(unknown,configRestore,configuring); - builder = builder.addTransition(unknown,healthcheck,testing); - builder = builder.addTransition(unknown,backup,backingUp); - builder = builder.addTransition(unknown,snapshot,snapshotting); - builder = builder.addTransition(unknown,softwareUpload,softwareUploading); - builder = builder.addTransition(unknown,liveUpgrade,upgrading); - builder = builder.addTransition(unknown,rollback,rollbacking); - builder = builder.addTransition(unknown,sync,unknown); - builder = builder.addTransition(unknown,audit,unknown); - builder = builder.addTransition(unknown,migrate,migrating); - builder = builder.addTransition(unknown,evacuate,evacuating); - builder = builder.addTransition(unknown,lock,unknown); - builder = builder.addTransition(unknown,unlock,unknown); - builder = builder.addTransition(unknown,checklock,unknown); - builder = builder.addTransition(unknown,configBackup,unknown); - builder = builder.addTransition(unknown,configBackupDelete,unknown); - builder = builder.addTransition(unknown,configExport,unknown); - builder = builder.addTransition(unknown,stopApplication,stopping); - - builder = builder.addTransition(stopped,configure,configuring); - builder = builder.addTransition(stopped,test,testing); - builder = builder.addTransition(stopped,start,starting); - builder = builder.addTransition(stopped,terminate,terminating); - builder = builder.addTransition(stopped,restart,restarting); - builder = builder.addTransition(stopped,rebuild,rebuilding); - builder = builder.addTransition(stopped,configModify,configuring); - builder = builder.addTransition(stopped,configScaleout,configuring); - builder = builder.addTransition(stopped,configRestore,configuring); - builder = builder.addTransition(stopped,healthcheck,testing); - builder = builder.addTransition(stopped,backup,backingUp); - builder = builder.addTransition(stopped,snapshot,snapshotting); - builder = builder.addTransition(stopped,softwareUpload,softwareUploading); - builder = builder.addTransition(stopped,liveUpgrade,upgrading); - builder = builder.addTransition(stopped,rollback,rollbacking); - builder = builder.addTransition(stopped,migrate,migrating); - builder = builder.addTransition(stopped,evacuate,evacuating); - builder = builder.addTransition(stopped,lock,stopped); - builder = builder.addTransition(stopped,unlock,stopped); - builder = builder.addTransition(stopped,checklock,stopped); - - builder = builder.addTransition(configuring,success,configured); - builder = builder.addTransition(configuring,failure,error); - - builder = builder.addTransition(testing,success,tested); - builder = builder.addTransition(testing,failure,error); - - builder = builder.addTransition(restarting,success,running); - builder = builder.addTransition(restarting,failure,error); - - builder = builder.addTransition(starting,success,running); - builder = builder.addTransition(starting,failure,error); - - builder = builder.addTransition(terminating,success,notInstantiated); - builder = builder.addTransition(terminating,failure,error); - - builder = builder.addTransition(rebuilding,success,running); - builder = builder.addTransition(rebuilding,failure,error); - - builder = builder.addTransition(stopping,success,stopped); - builder = builder.addTransition(stopping,failure,error); - - builder = builder.addTransition(backingUp,success,running); - builder = builder.addTransition(backingUp,failure,error); - - builder = builder.addTransition(snapshotting,success,running); - builder = builder.addTransition(snapshotting,failure,error); - - builder = builder.addTransition(softwareUploading,success,running); - builder = builder.addTransition(softwareUploading,failure,error); - - builder = builder.addTransition(upgrading,success,running); - builder = builder.addTransition(upgrading,failure,error); - - builder = builder.addTransition(rollbacking,success,running); - builder = builder.addTransition(rollbacking,failure,error); - - builder = builder.addTransition(migrating,success,running); - builder = builder.addTransition(migrating,failure,error); - - builder = builder.addTransition(evacuating,success,running); - builder = builder.addTransition(evacuating,failure,error); - - - builder = builder.addTransition(configured,startApplication,starting); - builder = builder.addTransition(tested,startApplication,starting); - builder = builder.addTransition(error,startApplication,starting); - builder = builder.addTransition(unknown,startApplication,starting); - builder = builder.addTransition(running,startApplication,starting); - - return builder.build(); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Event.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Event.java deleted file mode 100644 index 5e9b7c813..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Event.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -/** - * Event Object - */ -public class Event{ - private final String eventName; - private final int hashCode; - - /** - * Constructor - * @param eventName String of the event name - */ - public Event(String eventName) { - this.eventName = eventName; - this.hashCode = this.eventName.toLowerCase().hashCode(); - } - - @Override - public int hashCode() { - return hashCode; - } - @Override - public boolean equals(Object obj) { - if(obj == null){ - return false; - } - if(!(obj instanceof Event)){ - return false; - } - Event event = (Event)obj; - return this.eventName.equalsIgnoreCase(event.getEventName()); - } - - public String getEventName() { - return eventName; - } - - @Override - public String toString(){ - return this.eventName; - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Response.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Response.java deleted file mode 100644 index 49b6c909b..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Response.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -/** - * Response object - */ -public enum Response { - NO_TRANSITION_DEFINED, - NO_STATE_CHANGE, - VALID_TRANSITION; - - @Override - public String toString(){ - return this.name(); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/State.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/State.java deleted file mode 100644 index 117cd76c0..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/State.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import java.util.ArrayList; -import java.util.List; - -/** - * State Object - */ -public class State { - private final String stateName; - private final int hashCode; - private final List transitions; - - /** - * Constructor - * @param stateName String of the state name - */ - public State(String stateName) { - this.stateName = stateName; - this.hashCode = stateName.toLowerCase().hashCode(); - this.transitions = new ArrayList<>(); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof State)) { - return false; - } - State state = (State)obj; - return this.stateName.equalsIgnoreCase(state.getStateName()); - } - - public String getStateName() { - return stateName; - } - - void addTransition(Transition transition) { - this.transitions.add(transition); - } - - public List getTransitions() { - return transitions; - } - - @Override - public String toString() { - return this.stateName; - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineMetadata.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineMetadata.java deleted file mode 100644 index 02088b26e..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineMetadata.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import java.util.HashSet; -import java.util.Set; - -public class StateMachineMetadata { - - private Set states; - private Set events; - - private StateMachineMetadata(StateMachineMetadataBuilder builder){ - states = builder.states; - events = builder.events; - } - - public Set getStates() { - return states; - } - - public Set getEvents() { - return events; - } - - public static class StateMachineMetadataBuilder{ - - private Set states; - private Set events; - - public StateMachineMetadataBuilder(){ - states = new HashSet<>(); - events = new HashSet<>(); - } - - public StateMachineMetadataBuilder addState(State state){ - this.states.add(state); - return this; - } - - public StateMachineMetadataBuilder addEvent(Event event){ - this.events.add(event); - return this; - } - - public StateMachineMetadataBuilder addTransition(State currentState,Event event,State nextState){ - Transition transition = new Transition(event,nextState); - currentState.addTransition(transition); - return this; - } - - public StateMachineMetadata build(){ - return new StateMachineMetadata(this); - } - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineResponse.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineResponse.java deleted file mode 100644 index 9fc401527..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/StateMachineResponse.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - - -public class StateMachineResponse { - private State nextState; - private Response response; - - public StateMachineResponse(){ - // do nothing - } - - public State getNextState() { - return nextState; - } - - public Response getResponse() { - return response; - } - - public void setNextState(State nextState) { - this.nextState = nextState; - } - - public void setResponse(Response response) { - this.response = response; - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Transition.java b/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Transition.java deleted file mode 100644 index 2c6ee6366..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/main/java/org/openecomp/appc/statemachine/objects/Transition.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -/** - * Transition Object - */ -public class Transition { - private Event event; - private State nextState; - - /** - * Constructor - * @param event which triggers the transition - * @param nextState of State which indicates the transition targeted state - */ - Transition(Event event, State nextState) { - this.event = event; - this.nextState = nextState; - } - - public Event getEvent() { - return event; - } - - public State getNextState() { - return nextState; - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineFactoryTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineFactoryTest.java new file mode 100644 index 000000000..e35482e45 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineFactoryTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.statemachine.StateMachine; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +public class StateMachineFactoryTest { + private StateMachineMetadata metadata; + + @Before + public void setUp() throws Exception { + StateMachineMetadata.StateMachineMetadataBuilder builder = + new StateMachineMetadata.StateMachineMetadataBuilder(); + builder.addEvent(new Event("TestingEvent1")); + builder.addEvent(new Event("TestingEvent2")); + builder.addState(new State("TestingState1")); + builder.addState(new State("TestingState2")); + builder.addState(new State("TestingState3")); + builder.addTransition( + new State("TestingState1"), new Event("TestingEvent1"), new State("TestingState2")); + + metadata = builder.build(); + } + + @Test + public void testGetStateMachine() throws Exception { + StateMachine stateMachine = StateMachineFactory.getStateMachine(metadata); + Assert.assertTrue("Should return StateMachineImpl", stateMachine instanceof StateMachineImpl); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineImplTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineImplTest.java new file mode 100644 index 000000000..a4a8b9fcc --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/StateMachineImplTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.Response; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; +import org.onap.appc.statemachine.objects.StateMachineResponse; + +public class StateMachineImplTest { + private StateMachineMetadata metadata; + private StateMachineImpl stateMachine; + + private State state1 = new State("TestingState1"); + private State state2 = new State("TestingState2"); + private Event event1 = new Event("TestingEvent1"); + private Event event2 = new Event("TestingEvent2"); + + @Before + public void setUp() throws Exception { + StateMachineMetadata.StateMachineMetadataBuilder builder = + new StateMachineMetadata.StateMachineMetadataBuilder(); + builder.addEvent(event1); + builder.addEvent(event2); + builder.addState(state1); + builder.addState(state2); + builder.addState(new State("TestingState3")); + builder.addTransition(state1, event1, state2); + + metadata = builder.build(); + + stateMachine = new StateMachineImpl(metadata); + } + + @Test + public void testConstructor() throws Exception { + StateMachineImpl stateMachine = new StateMachineImpl(metadata); + Assert.assertEquals("Should have set internal states", + metadata.getStates(), Whitebox.getInternalState(stateMachine, "states")); + Assert.assertEquals("Should have set internal events", + metadata.getEvents(), Whitebox.getInternalState(stateMachine, "events")); + } + + @Test(expected = InvalidInputException.class) + public void testHandleEventThrowsInvalidInputException() throws Exception { + stateMachine.handleEvent(null, null); + } + + @Test + public void testHandleEvent() throws Exception { + StateMachineResponse response = stateMachine.handleEvent(state1, event1); + Assert.assertEquals(Response.VALID_TRANSITION, response.getResponse()); + Assert.assertEquals(state2, response.getNextState()); + + response = stateMachine.handleEvent(state2, event1); + Assert.assertEquals(Response.NO_TRANSITION_DEFINED, response.getResponse()); + Assert.assertTrue(response.getNextState() == null); + } + + @Test + public void testValidateInputs() { + Assert.assertFalse(stateMachine.validateInputs(null, null)); + Assert.assertFalse(stateMachine.validateInputs(new State("state1"), null)); + Assert.assertFalse(stateMachine.validateInputs(null, new Event("event1"))); + Assert.assertFalse(stateMachine.validateInputs(new State("state1"), new Event("event1"))); + Assert.assertFalse(stateMachine.validateInputs(state1, new Event("event1"))); + Assert.assertFalse(stateMachine.validateInputs(new State("state1"), event1)); + Assert.assertTrue(stateMachine.validateInputs(state1, event1)); + + } + + @Test + public void testToString() throws Exception { + Assert.assertEquals( + String.format(stateMachine.toStringFormat, metadata.getStates(), metadata.getEvents()), + stateMachine.toString()); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java new file mode 100644 index 000000000..e8f2a2083 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class AppcOamMetaDataReaderTest { + private List expectedStateNames = new ArrayList<>(); + private List expectedEventNames = new ArrayList<>(); + + private StateMachineMetadata stateMachineMetadata = new AppcOamMetaDataReader().readMetadata(); + + @Before + public void setUp() throws Exception { + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + expectedStateNames.add(appcOamStates.toString()); + } + for (AppcOamMetaDataReader.AppcOperation appcOperation : AppcOamMetaDataReader.AppcOperation.values()) { + expectedEventNames.add(appcOperation.toString()); + } + } + + @Test + public void testReadMetadataForState() throws Exception { + Set stateSet = stateMachineMetadata.getStates(); + for (State state : stateSet) { + String eventName = state.getStateName(); + Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), + expectedStateNames.contains(eventName)); + } + } + + @Test + public void testReadMetadataForEvent() throws Exception { + Set eventSet = stateMachineMetadata.getEvents(); + for (Event event : eventSet) { + String eventName = event.getEventName(); + Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), + expectedEventNames.contains(eventName)); + } + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamStatesTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamStatesTest.java new file mode 100644 index 000000000..014618846 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/AppcOamStatesTest.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.junit.Assert; +import org.junit.Test; +import org.osgi.framework.Bundle; + +import java.util.HashMap; +import java.util.Map; + +public class AppcOamStatesTest { + + @Test + public void testBasicFunctions() { + AppcOamStates aState = AppcOamStates.EnteringMaintenanceMode; + Assert.assertEquals("name() does not match", "EnteringMaintenanceMode", aState.name()); + Assert.assertEquals("toString() does not match", "EnteringMaintenanceMode", aState.toString()); + Assert.assertEquals("osgiBundleState does not match", 0, aState.osgiBundleState); + } + + @Test + public void testGetOamStateFromBundleState() { + Map resultMap = new HashMap() { + { + put(Bundle.UNINSTALLED, AppcOamStates.NotInstantiated); + put(Bundle.INSTALLED, AppcOamStates.Instantiated); + put(Bundle.RESOLVED, AppcOamStates.Stopped); + put(Bundle.STARTING, AppcOamStates.Starting); + put(Bundle.STOPPING, AppcOamStates.Stopping); + put(Bundle.ACTIVE, AppcOamStates.Started); + } + }; + for (Map.Entry aEntry : resultMap.entrySet()) { + Integer bundleState = aEntry.getKey(); + AppcOamStates oamState = aEntry.getValue(); + Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with oamState(%s)", + bundleState, oamState), oamState, AppcOamStates.getOamStateFromBundleState(bundleState)); + } + + int bundleState = Bundle.START_TRANSIENT; + Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with NotInstantiated state.", + bundleState), AppcOamStates.NotInstantiated, AppcOamStates.getOamStateFromBundleState(bundleState)); + + bundleState = Bundle.STOP_TRANSIENT; + Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with NotInstantiated state.", + bundleState), AppcOamStates.NotInstantiated, AppcOamStates.getOamStateFromBundleState(bundleState)); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java new file mode 100644 index 000000000..9b409491e --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.impl.readers; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; +import org.onap.appc.statemachine.objects.Event; +import org.onap.appc.statemachine.objects.State; +import org.onap.appc.statemachine.objects.StateMachineMetadata; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + + +public class VnfMetaDataReaderTest { + private List expectedStateNames = new ArrayList<>(); + private List expectedEventNames = new ArrayList<>(); + + private StateMachineMetadata stateMachineMetadata = new VnfMetaDataReader().readMetadata(); + + @Before + public void setUp() throws Exception { + for (VnfMetaDataReader.VNFStates vnfStates : VnfMetaDataReader.VNFStates.values()) { + expectedStateNames.add(vnfStates.toString()); + } + for (VnfMetaDataReader.VNFOperation vnfOperation : VnfMetaDataReader.VNFOperation.values()) { + expectedEventNames.add(vnfOperation.toString()); + } + for (VNFOperationOutcome vnfOperationOutcome : VNFOperationOutcome.values()) { + expectedEventNames.add(vnfOperationOutcome.toString()); + } + } + + @Test + public void testReadMetadataForState() throws Exception { + Set stateSet = stateMachineMetadata.getStates(); + for (State state : stateSet) { + String eventName = state.getStateName(); + Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), + expectedStateNames.contains(eventName)); + } + } + + @Test + public void testReadMetadataForEvent() throws Exception { + Set eventSet = stateMachineMetadata.getEvents(); + for (Event event : eventSet) { + String eventName = event.getEventName(); + Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), + expectedEventNames.contains(eventName)); + } + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/EventTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/EventTest.java new file mode 100644 index 000000000..961e33ffd --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/EventTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; + +public class EventTest { + private final String EVENT_NAME = "Testing Event"; + private Event event = new Event(EVENT_NAME); + + @Test + public void testConstructor() { + Event event = new Event(EVENT_NAME); + Assert.assertEquals("Should set eventName", + EVENT_NAME, Whitebox.getInternalState(event, "eventName")); + Assert.assertEquals("Should set hash code", + EVENT_NAME.toLowerCase().hashCode(), (int)Whitebox.getInternalState(event, "hashCode")); + } + + @Test + public void testHashCode() throws Exception { + Assert.assertEquals("Should return proper hash code", + EVENT_NAME.toLowerCase().hashCode(), event.hashCode()); + } + + @Test + public void testEquals() throws Exception { + Assert.assertFalse("should return false for null", event.equals(null)); + Assert.assertFalse("should return false for object", event.equals(new State(EVENT_NAME))); + Assert.assertFalse("should return false for different event", + event.equals(new Event("Another"))); + Assert.assertTrue("should return true", event.equals(new Event(EVENT_NAME))); + Assert.assertTrue("should return true (lower case)", event.equals(new Event(EVENT_NAME.toLowerCase()))); + } + + @Test + public void testGetEventName() throws Exception { + Assert.assertEquals("Should return EVENT_NAME", EVENT_NAME, event.getEventName()); + } + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Should return EVENT_NAME", EVENT_NAME, event.toString()); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/ResponseTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/ResponseTest.java new file mode 100644 index 000000000..e85bce65f --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/ResponseTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Test; + +public class ResponseTest { + + @Test + public void testToString() throws Exception { + for (Response response : Response.values()) { + Assert.assertEquals("Should return the same as name", + response.name(), response.toString()); + } + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineMetadataTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineMetadataTest.java new file mode 100644 index 000000000..684225736 --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineMetadataTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; + +public class StateMachineMetadataTest { + private StateMachineMetadata.StateMachineMetadataBuilder builder; + private StateMachineMetadata metadata; + @Before + public void setUp() throws Exception { + builder = new StateMachineMetadata.StateMachineMetadataBuilder(); + builder.addEvent(new Event("TestingEvent1")); + builder.addEvent(new Event("TestingEvent2")); + builder.addState(new State("TestingState1")); + builder.addState(new State("TestingState2")); + builder.addState(new State("TestingState3")); + builder.addTransition( + new State("TestingState1"), new Event("TestingEvent1"), new State("TestingState2")); + + metadata = builder.build(); + } + + @Test + public void getStates() throws Exception { + Assert.assertEquals("Should return proper States", + Whitebox.getInternalState(builder, "states"), metadata.getStates()); + } + + @Test + public void getEvents() throws Exception { + Assert.assertEquals("Should return proper Events", + Whitebox.getInternalState(builder, "events"), metadata.getEvents()); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineResponseTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineResponseTest.java new file mode 100644 index 000000000..183b7f5af --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateMachineResponseTest.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; + +public class StateMachineResponseTest { + private StateMachineResponse stateMachineResponse = new StateMachineResponse(); + + @Test + public void testConstructor() { + StateMachineResponse stateMachineResponse = new StateMachineResponse(); + Assert.assertTrue("Do not: no change to nextState", + Whitebox.getInternalState(stateMachineResponse, "nextState") == null); + Assert.assertTrue("Do not: no change to response", + Whitebox.getInternalState(stateMachineResponse, "response") == null); + } + + @Test + public void testGetAndSetNextState() throws Exception { + stateMachineResponse.setNextState(null); + Assert.assertTrue("internal nextState should be null", + Whitebox.getInternalState(stateMachineResponse, "nextState") == null); + Assert.assertTrue("should return null", stateMachineResponse.getNextState() == null); + + State state = new State("TestingState"); + stateMachineResponse.setNextState(state); + Assert.assertEquals("internal nextState should be the state", + state, Whitebox.getInternalState(stateMachineResponse, "nextState")); + Assert.assertEquals("should return the state", state, stateMachineResponse.getNextState()); + } + + @Test + public void testGetAndSetResponse() throws Exception { + stateMachineResponse.setResponse(null); + Assert.assertTrue("internal response should be null", + Whitebox.getInternalState(stateMachineResponse, "response") == null); + Assert.assertTrue("should return null", stateMachineResponse.getResponse() == null); + + Response response = Response.NO_STATE_CHANGE; + stateMachineResponse.setResponse(response); + Assert.assertEquals("internal response should be the response", + response, Whitebox.getInternalState(stateMachineResponse, "response")); + Assert.assertEquals("should return the response", response, stateMachineResponse.getResponse()); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateTest.java new file mode 100644 index 000000000..601754edf --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/StateTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; + +import java.util.List; + +public class StateTest { + private final String STATE_NAME = "Starting"; + private State state = new State(STATE_NAME); + + @SuppressWarnings("unchecked") + @Test + public void testConstructor() { + State state = new State(STATE_NAME); + Assert.assertEquals("Should set stateName", + STATE_NAME, Whitebox.getInternalState(state, "stateName")); + Assert.assertEquals("Should set hash code", + STATE_NAME.toLowerCase().hashCode(), (int)Whitebox.getInternalState(state, "hashCode")); + List transitions = (List) Whitebox.getInternalState(state, "transitions"); + Assert.assertTrue("Should initialized transtiions", + transitions != null && transitions.isEmpty()); + } + + @Test + public void testHashCode() throws Exception { + Assert.assertEquals("Should return proper hash code", + STATE_NAME.toLowerCase().hashCode(), state.hashCode()); + } + + @Test + public void testEquals() throws Exception { + Assert.assertFalse("should return false for null", state.equals(null)); + Assert.assertFalse("should return false for object", state.equals(new Event(STATE_NAME))); + Assert.assertFalse("should return false for different event", + state.equals(new Event("Another"))); + Assert.assertTrue("should return true", state.equals(new State(STATE_NAME))); + Assert.assertTrue("should return true (lower case)", state.equals(new State(STATE_NAME.toLowerCase()))); + } + + @Test + public void testGetStateName() throws Exception { + Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.getStateName()); + } + + @SuppressWarnings("unchecked") + @Test + public void testAddAndGetTransition() throws Exception { + Transition transition1 = new Transition(new Event("event1"), new State("state2")); + List transitions = (List) Whitebox.getInternalState(state, "transitions"); + Assert.assertFalse("should not have transition1", transitions.contains(transition1)); + state.addTransition(transition1); + transitions = (List) Whitebox.getInternalState(state, "transitions"); + Assert.assertTrue("should have added transition1", transitions.contains(transition1)); + Assert.assertEquals("Should return transitions", transitions, state.getTransitions()); + + state.addTransition(null); + Assert.assertEquals("Should not change transitions", transitions, + Whitebox.getInternalState(state, "transitions")); + } + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.toString()); + } +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/TransitionTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/TransitionTest.java new file mode 100644 index 000000000..da69d723c --- /dev/null +++ b/appc-lifecycle-management/state-machine-lib/src/test/java/org/onap/appc/statemachine/objects/TransitionTest.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.statemachine.objects; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.internal.util.reflection.Whitebox; + +public class TransitionTest { + private final State state = new State("TestingState"); + private final Event event = new Event("TestingEvent"); + private Transition transition = new Transition(event, state); + + @Test + public void testConstructor() { + transition = new Transition(event, state); + Assert.assertEquals("Should set event", + event, Whitebox.getInternalState(transition, "event")); + Assert.assertEquals("Should set nextState", + state, Whitebox.getInternalState(transition, "nextState")); + } + + @Test + public void testGetEvent() throws Exception { + Assert.assertEquals("Should return internal event", + Whitebox.getInternalState(transition, "event"), transition.getEvent()); + } + + @Test + public void testGetNextState() throws Exception { + Assert.assertEquals("Should return internal nextState", + Whitebox.getInternalState(transition, "nextState"), transition.getNextState()); + } + +} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineFactoryTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineFactoryTest.java deleted file mode 100644 index e35482e45..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineFactoryTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.statemachine.StateMachine; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -public class StateMachineFactoryTest { - private StateMachineMetadata metadata; - - @Before - public void setUp() throws Exception { - StateMachineMetadata.StateMachineMetadataBuilder builder = - new StateMachineMetadata.StateMachineMetadataBuilder(); - builder.addEvent(new Event("TestingEvent1")); - builder.addEvent(new Event("TestingEvent2")); - builder.addState(new State("TestingState1")); - builder.addState(new State("TestingState2")); - builder.addState(new State("TestingState3")); - builder.addTransition( - new State("TestingState1"), new Event("TestingEvent1"), new State("TestingState2")); - - metadata = builder.build(); - } - - @Test - public void testGetStateMachine() throws Exception { - StateMachine stateMachine = StateMachineFactory.getStateMachine(metadata); - Assert.assertTrue("Should return StateMachineImpl", stateMachine instanceof StateMachineImpl); - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineImplTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineImplTest.java deleted file mode 100644 index a4a8b9fcc..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/StateMachineImplTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.Response; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; -import org.onap.appc.statemachine.objects.StateMachineResponse; - -public class StateMachineImplTest { - private StateMachineMetadata metadata; - private StateMachineImpl stateMachine; - - private State state1 = new State("TestingState1"); - private State state2 = new State("TestingState2"); - private Event event1 = new Event("TestingEvent1"); - private Event event2 = new Event("TestingEvent2"); - - @Before - public void setUp() throws Exception { - StateMachineMetadata.StateMachineMetadataBuilder builder = - new StateMachineMetadata.StateMachineMetadataBuilder(); - builder.addEvent(event1); - builder.addEvent(event2); - builder.addState(state1); - builder.addState(state2); - builder.addState(new State("TestingState3")); - builder.addTransition(state1, event1, state2); - - metadata = builder.build(); - - stateMachine = new StateMachineImpl(metadata); - } - - @Test - public void testConstructor() throws Exception { - StateMachineImpl stateMachine = new StateMachineImpl(metadata); - Assert.assertEquals("Should have set internal states", - metadata.getStates(), Whitebox.getInternalState(stateMachine, "states")); - Assert.assertEquals("Should have set internal events", - metadata.getEvents(), Whitebox.getInternalState(stateMachine, "events")); - } - - @Test(expected = InvalidInputException.class) - public void testHandleEventThrowsInvalidInputException() throws Exception { - stateMachine.handleEvent(null, null); - } - - @Test - public void testHandleEvent() throws Exception { - StateMachineResponse response = stateMachine.handleEvent(state1, event1); - Assert.assertEquals(Response.VALID_TRANSITION, response.getResponse()); - Assert.assertEquals(state2, response.getNextState()); - - response = stateMachine.handleEvent(state2, event1); - Assert.assertEquals(Response.NO_TRANSITION_DEFINED, response.getResponse()); - Assert.assertTrue(response.getNextState() == null); - } - - @Test - public void testValidateInputs() { - Assert.assertFalse(stateMachine.validateInputs(null, null)); - Assert.assertFalse(stateMachine.validateInputs(new State("state1"), null)); - Assert.assertFalse(stateMachine.validateInputs(null, new Event("event1"))); - Assert.assertFalse(stateMachine.validateInputs(new State("state1"), new Event("event1"))); - Assert.assertFalse(stateMachine.validateInputs(state1, new Event("event1"))); - Assert.assertFalse(stateMachine.validateInputs(new State("state1"), event1)); - Assert.assertTrue(stateMachine.validateInputs(state1, event1)); - - } - - @Test - public void testToString() throws Exception { - Assert.assertEquals( - String.format(stateMachine.toStringFormat, metadata.getStates(), metadata.getEvents()), - stateMachine.toString()); - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java deleted file mode 100644 index e8f2a2083..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamMetaDataReaderTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -public class AppcOamMetaDataReaderTest { - private List expectedStateNames = new ArrayList<>(); - private List expectedEventNames = new ArrayList<>(); - - private StateMachineMetadata stateMachineMetadata = new AppcOamMetaDataReader().readMetadata(); - - @Before - public void setUp() throws Exception { - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - expectedStateNames.add(appcOamStates.toString()); - } - for (AppcOamMetaDataReader.AppcOperation appcOperation : AppcOamMetaDataReader.AppcOperation.values()) { - expectedEventNames.add(appcOperation.toString()); - } - } - - @Test - public void testReadMetadataForState() throws Exception { - Set stateSet = stateMachineMetadata.getStates(); - for (State state : stateSet) { - String eventName = state.getStateName(); - Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), - expectedStateNames.contains(eventName)); - } - } - - @Test - public void testReadMetadataForEvent() throws Exception { - Set eventSet = stateMachineMetadata.getEvents(); - for (Event event : eventSet) { - String eventName = event.getEventName(); - Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), - expectedEventNames.contains(eventName)); - } - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStatesTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStatesTest.java deleted file mode 100644 index 014618846..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/AppcOamStatesTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.junit.Assert; -import org.junit.Test; -import org.osgi.framework.Bundle; - -import java.util.HashMap; -import java.util.Map; - -public class AppcOamStatesTest { - - @Test - public void testBasicFunctions() { - AppcOamStates aState = AppcOamStates.EnteringMaintenanceMode; - Assert.assertEquals("name() does not match", "EnteringMaintenanceMode", aState.name()); - Assert.assertEquals("toString() does not match", "EnteringMaintenanceMode", aState.toString()); - Assert.assertEquals("osgiBundleState does not match", 0, aState.osgiBundleState); - } - - @Test - public void testGetOamStateFromBundleState() { - Map resultMap = new HashMap() { - { - put(Bundle.UNINSTALLED, AppcOamStates.NotInstantiated); - put(Bundle.INSTALLED, AppcOamStates.Instantiated); - put(Bundle.RESOLVED, AppcOamStates.Stopped); - put(Bundle.STARTING, AppcOamStates.Starting); - put(Bundle.STOPPING, AppcOamStates.Stopping); - put(Bundle.ACTIVE, AppcOamStates.Started); - } - }; - for (Map.Entry aEntry : resultMap.entrySet()) { - Integer bundleState = aEntry.getKey(); - AppcOamStates oamState = aEntry.getValue(); - Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with oamState(%s)", - bundleState, oamState), oamState, AppcOamStates.getOamStateFromBundleState(bundleState)); - } - - int bundleState = Bundle.START_TRANSIENT; - Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with NotInstantiated state.", - bundleState), AppcOamStates.NotInstantiated, AppcOamStates.getOamStateFromBundleState(bundleState)); - - bundleState = Bundle.STOP_TRANSIENT; - Assert.assertEquals(String.format("OSGI bundle state(%d) shoule associate with NotInstantiated state.", - bundleState), AppcOamStates.NotInstantiated, AppcOamStates.getOamStateFromBundleState(bundleState)); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java deleted file mode 100644 index 9b409491e..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/impl/readers/VnfMetaDataReaderTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.impl.readers; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.lifecyclemanager.objects.VNFOperationOutcome; -import org.onap.appc.statemachine.objects.Event; -import org.onap.appc.statemachine.objects.State; -import org.onap.appc.statemachine.objects.StateMachineMetadata; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - - -public class VnfMetaDataReaderTest { - private List expectedStateNames = new ArrayList<>(); - private List expectedEventNames = new ArrayList<>(); - - private StateMachineMetadata stateMachineMetadata = new VnfMetaDataReader().readMetadata(); - - @Before - public void setUp() throws Exception { - for (VnfMetaDataReader.VNFStates vnfStates : VnfMetaDataReader.VNFStates.values()) { - expectedStateNames.add(vnfStates.toString()); - } - for (VnfMetaDataReader.VNFOperation vnfOperation : VnfMetaDataReader.VNFOperation.values()) { - expectedEventNames.add(vnfOperation.toString()); - } - for (VNFOperationOutcome vnfOperationOutcome : VNFOperationOutcome.values()) { - expectedEventNames.add(vnfOperationOutcome.toString()); - } - } - - @Test - public void testReadMetadataForState() throws Exception { - Set stateSet = stateMachineMetadata.getStates(); - for (State state : stateSet) { - String eventName = state.getStateName(); - Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), - expectedStateNames.contains(eventName)); - } - } - - @Test - public void testReadMetadataForEvent() throws Exception { - Set eventSet = stateMachineMetadata.getEvents(); - for (Event event : eventSet) { - String eventName = event.getEventName(); - Assert.assertTrue(String.format("Event(%s) should exist in expectedEventNames", eventName), - expectedEventNames.contains(eventName)); - } - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/EventTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/EventTest.java deleted file mode 100644 index 961e33ffd..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/EventTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; - -public class EventTest { - private final String EVENT_NAME = "Testing Event"; - private Event event = new Event(EVENT_NAME); - - @Test - public void testConstructor() { - Event event = new Event(EVENT_NAME); - Assert.assertEquals("Should set eventName", - EVENT_NAME, Whitebox.getInternalState(event, "eventName")); - Assert.assertEquals("Should set hash code", - EVENT_NAME.toLowerCase().hashCode(), (int)Whitebox.getInternalState(event, "hashCode")); - } - - @Test - public void testHashCode() throws Exception { - Assert.assertEquals("Should return proper hash code", - EVENT_NAME.toLowerCase().hashCode(), event.hashCode()); - } - - @Test - public void testEquals() throws Exception { - Assert.assertFalse("should return false for null", event.equals(null)); - Assert.assertFalse("should return false for object", event.equals(new State(EVENT_NAME))); - Assert.assertFalse("should return false for different event", - event.equals(new Event("Another"))); - Assert.assertTrue("should return true", event.equals(new Event(EVENT_NAME))); - Assert.assertTrue("should return true (lower case)", event.equals(new Event(EVENT_NAME.toLowerCase()))); - } - - @Test - public void testGetEventName() throws Exception { - Assert.assertEquals("Should return EVENT_NAME", EVENT_NAME, event.getEventName()); - } - - @Test - public void testToString() throws Exception { - Assert.assertEquals("Should return EVENT_NAME", EVENT_NAME, event.toString()); - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/ResponseTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/ResponseTest.java deleted file mode 100644 index e85bce65f..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/ResponseTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Test; - -public class ResponseTest { - - @Test - public void testToString() throws Exception { - for (Response response : Response.values()) { - Assert.assertEquals("Should return the same as name", - response.name(), response.toString()); - } - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineMetadataTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineMetadataTest.java deleted file mode 100644 index 684225736..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineMetadataTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; - -public class StateMachineMetadataTest { - private StateMachineMetadata.StateMachineMetadataBuilder builder; - private StateMachineMetadata metadata; - @Before - public void setUp() throws Exception { - builder = new StateMachineMetadata.StateMachineMetadataBuilder(); - builder.addEvent(new Event("TestingEvent1")); - builder.addEvent(new Event("TestingEvent2")); - builder.addState(new State("TestingState1")); - builder.addState(new State("TestingState2")); - builder.addState(new State("TestingState3")); - builder.addTransition( - new State("TestingState1"), new Event("TestingEvent1"), new State("TestingState2")); - - metadata = builder.build(); - } - - @Test - public void getStates() throws Exception { - Assert.assertEquals("Should return proper States", - Whitebox.getInternalState(builder, "states"), metadata.getStates()); - } - - @Test - public void getEvents() throws Exception { - Assert.assertEquals("Should return proper Events", - Whitebox.getInternalState(builder, "events"), metadata.getEvents()); - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineResponseTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineResponseTest.java deleted file mode 100644 index 183b7f5af..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateMachineResponseTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; - -public class StateMachineResponseTest { - private StateMachineResponse stateMachineResponse = new StateMachineResponse(); - - @Test - public void testConstructor() { - StateMachineResponse stateMachineResponse = new StateMachineResponse(); - Assert.assertTrue("Do not: no change to nextState", - Whitebox.getInternalState(stateMachineResponse, "nextState") == null); - Assert.assertTrue("Do not: no change to response", - Whitebox.getInternalState(stateMachineResponse, "response") == null); - } - - @Test - public void testGetAndSetNextState() throws Exception { - stateMachineResponse.setNextState(null); - Assert.assertTrue("internal nextState should be null", - Whitebox.getInternalState(stateMachineResponse, "nextState") == null); - Assert.assertTrue("should return null", stateMachineResponse.getNextState() == null); - - State state = new State("TestingState"); - stateMachineResponse.setNextState(state); - Assert.assertEquals("internal nextState should be the state", - state, Whitebox.getInternalState(stateMachineResponse, "nextState")); - Assert.assertEquals("should return the state", state, stateMachineResponse.getNextState()); - } - - @Test - public void testGetAndSetResponse() throws Exception { - stateMachineResponse.setResponse(null); - Assert.assertTrue("internal response should be null", - Whitebox.getInternalState(stateMachineResponse, "response") == null); - Assert.assertTrue("should return null", stateMachineResponse.getResponse() == null); - - Response response = Response.NO_STATE_CHANGE; - stateMachineResponse.setResponse(response); - Assert.assertEquals("internal response should be the response", - response, Whitebox.getInternalState(stateMachineResponse, "response")); - Assert.assertEquals("should return the response", response, stateMachineResponse.getResponse()); - } - -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateTest.java deleted file mode 100644 index 601754edf..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/StateTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; - -import java.util.List; - -public class StateTest { - private final String STATE_NAME = "Starting"; - private State state = new State(STATE_NAME); - - @SuppressWarnings("unchecked") - @Test - public void testConstructor() { - State state = new State(STATE_NAME); - Assert.assertEquals("Should set stateName", - STATE_NAME, Whitebox.getInternalState(state, "stateName")); - Assert.assertEquals("Should set hash code", - STATE_NAME.toLowerCase().hashCode(), (int)Whitebox.getInternalState(state, "hashCode")); - List transitions = (List) Whitebox.getInternalState(state, "transitions"); - Assert.assertTrue("Should initialized transtiions", - transitions != null && transitions.isEmpty()); - } - - @Test - public void testHashCode() throws Exception { - Assert.assertEquals("Should return proper hash code", - STATE_NAME.toLowerCase().hashCode(), state.hashCode()); - } - - @Test - public void testEquals() throws Exception { - Assert.assertFalse("should return false for null", state.equals(null)); - Assert.assertFalse("should return false for object", state.equals(new Event(STATE_NAME))); - Assert.assertFalse("should return false for different event", - state.equals(new Event("Another"))); - Assert.assertTrue("should return true", state.equals(new State(STATE_NAME))); - Assert.assertTrue("should return true (lower case)", state.equals(new State(STATE_NAME.toLowerCase()))); - } - - @Test - public void testGetStateName() throws Exception { - Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.getStateName()); - } - - @SuppressWarnings("unchecked") - @Test - public void testAddAndGetTransition() throws Exception { - Transition transition1 = new Transition(new Event("event1"), new State("state2")); - List transitions = (List) Whitebox.getInternalState(state, "transitions"); - Assert.assertFalse("should not have transition1", transitions.contains(transition1)); - state.addTransition(transition1); - transitions = (List) Whitebox.getInternalState(state, "transitions"); - Assert.assertTrue("should have added transition1", transitions.contains(transition1)); - Assert.assertEquals("Should return transitions", transitions, state.getTransitions()); - - state.addTransition(null); - Assert.assertEquals("Should not change transitions", transitions, - Whitebox.getInternalState(state, "transitions")); - } - - @Test - public void testToString() throws Exception { - Assert.assertEquals("Should return STATE_NAME", STATE_NAME, state.toString()); - } -} diff --git a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/TransitionTest.java b/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/TransitionTest.java deleted file mode 100644 index da69d723c..000000000 --- a/appc-lifecycle-management/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/objects/TransitionTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.statemachine.objects; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; - -public class TransitionTest { - private final State state = new State("TestingState"); - private final Event event = new Event("TestingEvent"); - private Transition transition = new Transition(event, state); - - @Test - public void testConstructor() { - transition = new Transition(event, state); - Assert.assertEquals("Should set event", - event, Whitebox.getInternalState(transition, "event")); - Assert.assertEquals("Should set nextState", - state, Whitebox.getInternalState(transition, "nextState")); - } - - @Test - public void testGetEvent() throws Exception { - Assert.assertEquals("Should return internal event", - Whitebox.getInternalState(transition, "event"), transition.getEvent()); - } - - @Test - public void testGetNextState() throws Exception { - Assert.assertEquals("Should return internal nextState", - Whitebox.getInternalState(transition, "nextState"), transition.getNextState()); - } - -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/MetricActivator.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/MetricActivator.java new file mode 100644 index 000000000..40ff14827 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/MetricActivator.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.impl.MetricServiceImpl; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + + +public class MetricActivator implements BundleActivator { + + private ServiceRegistration registration = null; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MetricActivator.class); + + @Override + public void start(BundleContext bundleContext) throws Exception { + logger.debug("Starting Metric service " ); + MetricService impl = new MetricServiceImpl(); + String regName = MetricService.class.getName(); + logger.debug("Registering Metric service " + regName); + registration = bundleContext.registerService(regName, impl, null); + logger.debug("Registered Metric service " + regName); + } + + @Override + public void stop(BundleContext bundleContext) throws Exception { + + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricRegistry.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricRegistry.java new file mode 100644 index 000000000..6e658ae47 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricRegistry.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice; + +import org.onap.appc.metricservice.metric.Counter; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricBuilderFactory; +import org.onap.appc.metricservice.policy.PolicyBuilderFactory; +import org.onap.appc.metricservice.policy.PublishingPolicy; + +/** + * + * A named group of metrics which might be related to a specific domain. The service doesn't limit number of metric registries per instance. + * It's up to application to decide on domain scope. The registry instances are independent. + * + */ +public interface MetricRegistry { + boolean register(Metric metric); + void attach (PublishingPolicy publishPolicy); + MetricBuilderFactory metricBuilderFactory(); + PolicyBuilderFactory policyBuilderFactory(); + Counter counter(String value); + Counter[] counters(); + Metric[] metrics(); + Metric metric(String metricName); + void dispose(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricService.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricService.java new file mode 100644 index 000000000..65ff72d97 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/MetricService.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice; + + +import java.util.Map; + +public interface MetricService { + MetricRegistry registry(String name); + MetricRegistry createRegistry(String name); + void dispose(); + + /** + * This API will be used to get the Map of all the registered Registry for the Metric Service + * @return Map where String will be the name of the Metric Registry + * and MetricRegistry will be the actual object for that Registry + */ + Map getAllRegistry(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/Publisher.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/Publisher.java new file mode 100644 index 000000000..1d38e44c3 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/Publisher.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice; + +import org.onap.appc.metricservice.metric.Metric; + +/** + * Low-level logic of exposing metric values in certain way. There might be plenty of options such as logging, JMX, etc. + * API to be supported by any logic that is going to be plugged into metric service. + * The publisher is considered as low-level technical unit which, potentially, can be reused to expose metrics from different registries + * + */ +public interface Publisher { + void publish(MetricRegistry metricRegistry,Metric[] metrics); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricRegistryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricRegistryImpl.java new file mode 100644 index 000000000..ac2054151 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricRegistryImpl.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.metric.Counter; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricBuilderFactory; +import org.onap.appc.metricservice.metric.impl.MetricBuilderFactoryImpl; +import org.onap.appc.metricservice.policy.PolicyBuilderFactory; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.policy.impl.PolicyBuilderFactoryImpl; + + +public class MetricRegistryImpl implements MetricRegistry { + private String name; + private Map concurrentMetricMap=new ConcurrentHashMap(); + + public MetricRegistryImpl(String name) { + this.name = name; + } + + @Override + public boolean register(Metric metric) { + if(concurrentMetricMap.get(metric.name())==null){ + concurrentMetricMap.put(metric.name(),metric); + return true; + } + return false; + } + + @Override + public void attach(PublishingPolicy publishPolicy) { +//TODO + } + + @Override + public MetricBuilderFactory metricBuilderFactory() { + return new MetricBuilderFactoryImpl(); + } + + @Override + public PolicyBuilderFactory policyBuilderFactory() { + return new PolicyBuilderFactoryImpl() ; + } + + @Override + public Counter counter(String value) { + if(concurrentMetricMap.get(value)!=null ) + return (Counter)concurrentMetricMap.get(value) ; + else + return null; + + } + + @Override + public Counter[] counters() { + return (Counter[])concurrentMetricMap.values().toArray(); + } + + @Override + public Metric[] metrics() { + java.util.Collection var = concurrentMetricMap.values(); + return var.toArray(new Metric[var.size()]); + } + + @Override + public Metric metric(String metricName) { + return concurrentMetricMap.get(metricName); + } + + @Override + public void dispose() { + concurrentMetricMap.clear(); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricServiceImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricServiceImpl.java new file mode 100644 index 000000000..20f2d8d2e --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/impl/MetricServiceImpl.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.impl; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; + + +public class MetricServiceImpl implements MetricService { + private Map concurrentRegistryMap=new ConcurrentHashMap<>(); + @Override + public MetricRegistry registry(String name) { + return concurrentRegistryMap.get(name); + } + + @Override + public MetricRegistry createRegistry(String name) { + if(concurrentRegistryMap.get(name)==null) + concurrentRegistryMap.put(name,new MetricRegistryImpl(name)); + return concurrentRegistryMap.get(name); + } + + @Override + public Map getAllRegistry(){ + return Collections.unmodifiableMap(concurrentRegistryMap); + + } + + @Override + public void dispose() { +//TODO + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Counter.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Counter.java new file mode 100644 index 000000000..0b4d3e2d3 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Counter.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface Counter extends Metric { + long value(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java new file mode 100644 index 000000000..bff07f627 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface DispatchingFunctionCounterBuilder { + DispatchingFunctionCounterBuilder withName(String name); + DispatchingFunctionCounterBuilder withAcceptRequestValue(long value); + DispatchingFunctionCounterBuilder withRejectRequestValue(long value); + DispatchingFunctionCounterBuilder withType(MetricType type); + DispatchingFuntionMetric build(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFuntionMetric.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFuntionMetric.java new file mode 100644 index 000000000..384875e9b --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DispatchingFuntionMetric.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface DispatchingFuntionMetric extends Metric { + void incrementAcceptedRequest(); + void incrementRejectedRequest(); + String value(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterBuilder.java new file mode 100644 index 000000000..efb23963f --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterBuilder.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface DmaapRequestCounterBuilder { + DmaapRequestCounterBuilder withName(String name); + DmaapRequestCounterBuilder withRecievedMessage(long value); + DmaapRequestCounterBuilder withPublishedMessage(long value); + DmaapRequestCounterBuilder withType(MetricType type); + DmaapRequestCounterMetric build(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterMetric.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterMetric.java new file mode 100644 index 000000000..522432631 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/DmaapRequestCounterMetric.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface DmaapRequestCounterMetric extends Metric { + void incrementRecievedMessage(); + void incrementPublishedMessage(); + String value(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Metric.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Metric.java new file mode 100644 index 000000000..ce4297c88 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/Metric.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + +import java.util.HashMap; + +/** + * + * a measure of system parameter at the current moment. Each metric is identified by name. + * In general case, a metric just reflects its (almost) real-time value and is not responsible for maintaining its historical data. + * One that needs to build series of a metric values for statistical/analytic purposes should query the value and store it for further processing. + * Metrics can be of different types - counters, timers etc. + * The initial service implementation supports simple (flat) counters only. + * + */ +public interface Metric { + String name(); + void reset(); + MetricType type(); + /** + * This API will be used to get all the running Metrics Output. + * @return HashMap in which + * the First String(Key) will be the name of the KPI property + * and another String(Value of the Key) will be the Value of + * that property for that KPI + */ + HashMap getMetricsOutput(); + /** + * Return last modified date for KPI in string format + * @return - last modified date for KPI + */ + String getLastModified(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricBuilderFactory.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricBuilderFactory.java new file mode 100644 index 000000000..5a35247d3 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricBuilderFactory.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + + +public interface MetricBuilderFactory { + + PrimitiveCounterBuilder primitiveCounterBuilder(); + DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder(); + DmaapRequestCounterBuilder dmaapRequestCounterBuilder(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricType.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricType.java new file mode 100644 index 000000000..3f8ec30a8 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/MetricType.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + +/** + * + * Auxiliary enumeration that lists all the supported metric types. + * Can be used for generic processing of metrics rather than using Java reflection mechanisms to determine metric kind. + * + */ +public enum MetricType { +COUNTER +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounter.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounter.java new file mode 100644 index 000000000..a3fc2191f --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounter.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + +/** + * + * The simplest metric of type counter which mutable value. + */ +public interface PrimitiveCounter extends Counter{ + void increment(); + void increment(long value); + void decrement(); + void decrement(long value); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounterBuilder.java new file mode 100644 index 000000000..ded5ecf47 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/PrimitiveCounterBuilder.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric; + +/** + * + * Builder interface which can be used to instantiate and initialize a new primitive counter instance. + */ +public interface PrimitiveCounterBuilder { + PrimitiveCounterBuilder withName(String name); + PrimitiveCounterBuilder withValue(long value); + PrimitiveCounterBuilder withType(MetricType type); + PrimitiveCounter build(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java new file mode 100644 index 000000000..4b1992986 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.PrimitiveCounter; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicLong; + + +public class DefaultPrimitiveCounter implements PrimitiveCounter { + private String name; + private MetricType metricType; + private AtomicLong counter = new AtomicLong(); + + private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); + private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); + + public DefaultPrimitiveCounter(String name, MetricType metricType, long counter) { + this.name = name; + this.metricType = metricType; + this.counter.set(counter); + } + + public DefaultPrimitiveCounter(String name, MetricType metricType) { + this.counter.set(0); + this.name = name; + this.metricType = metricType; + } + + @Override + public void increment() { + increment(1); + } + + @Override + public void increment(long value) { + this.counter.incrementAndGet(); + } + + @Override + public void decrement() { + decrement(1); + } + + @Override + public void decrement(long value) { + this.counter.decrementAndGet(); + } + + @Override + public long value() { + return this.counter.get(); + } + + @Override + public String name() { + return this.name; + } + + @Override + public void reset() { + this.counter.set(0); + Calendar cal = Calendar.getInstance(); + lastResetTime = dateTimeFormat.format(cal.getTime()); + } + + @Override + public String toString() { + return "DefaultPrimitiveCounter{" + "name='" + name + '\'' + ", metricType=" + metricType + ", counter=" + + counter.get() + '}'; + } + + @Override + public MetricType type() { + return this.metricType; + } + + @Override + public HashMap getMetricsOutput() { + return new HashMap<>(); + } + + @Override + public String getLastModified() { + return lastResetTime; + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java new file mode 100644 index 000000000..fd3b05ef7 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import org.onap.appc.metricservice.metric.DispatchingFunctionCounterBuilder; +import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; +import org.onap.appc.metricservice.metric.MetricType; + + +public class DispatchingFunctionCounterBuilderImpl implements DispatchingFunctionCounterBuilder { + private String name; + private MetricType metricType; + private long acceptedRequested; + private long rejectedRequest; + + @Override + public DispatchingFunctionCounterBuilder withName(String name) { + this.name=name; + return this; + } + + @Override + public DispatchingFunctionCounterBuilder withAcceptRequestValue(long value) { + this.acceptedRequested=value; + return this; + } + @Override + public DispatchingFunctionCounterBuilder withRejectRequestValue(long value) { + this.rejectedRequest=value; + return this; + } + @Override + public DispatchingFunctionCounterBuilder withType(MetricType type) { + this.metricType=type; + return this; + } + + @Override + public DispatchingFuntionMetric build() { + return new DispatchingFuntionMetricImpl(this.name,this.metricType,this.acceptedRequested,this.rejectedRequest); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java new file mode 100644 index 000000000..a6487957f --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.TimeZone; +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; +import org.onap.appc.metricservice.metric.MetricType; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class DispatchingFuntionMetricImpl implements DispatchingFuntionMetric { + private String name; + private MetricType metricType; + private AtomicLong acceptedRequested = new AtomicLong(); + private AtomicLong rejectedRequest = new AtomicLong(); + + private final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); + private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); + + private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DispatchingFuntionMetricImpl.class); + + public DispatchingFuntionMetricImpl(String name, MetricType metricType, long acceptedRequested, + long rejectedRequest) { + this.name = name; + this.metricType = metricType; + this.acceptedRequested.set(acceptedRequested); + this.rejectedRequest.set(rejectedRequest); + } + + @Override + public void incrementAcceptedRequest() { + this.acceptedRequested.incrementAndGet(); + } + + @Override + public void incrementRejectedRequest() { + this.rejectedRequest.incrementAndGet(); + } + + @Override + public String value() { + logger.debug("Value is getting calculated for metric :" + this.name); + try { + Calendar cal = Calendar.getInstance(); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + String date = dateFormat.format(cal.getTime()); + String value = date + "[" + acceptedRequested.get() + "," + rejectedRequest.get() + "]" + "@" + + (acceptedRequested.get() + rejectedRequest.get()); + logger.debug("Current value of the metric " + this.name + " :" + value); + return value; + + } catch (Exception e) { + logger.debug("Cant format the date.",e); + } + return null; + + } + + @Override + public String name() { + return this.name; + } + + @Override + public void reset() { + this.acceptedRequested.set(0); + this.rejectedRequest.set(0); + Calendar cal = Calendar.getInstance(); + lastResetTime = dateTimeFormat.format(cal.getTime()); + } + + @Override + public MetricType type() { + return this.metricType; + } + + @Override + public HashMap getMetricsOutput() { + HashMap dispatcherMetricResult = new HashMap<>(); + dispatcherMetricResult.put("Total Received messages", + Long.toString(acceptedRequested.get() + rejectedRequest.get())); + dispatcherMetricResult.put("Total Rejected messages", Long.toString(rejectedRequest.get())); + return dispatcherMetricResult; + } + + @Override + public String toString() { + return this.value(); + } + + @Override + public String getLastModified() { + return lastResetTime; + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java new file mode 100644 index 000000000..b5b53a810 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.DmaapRequestCounterBuilder; +import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; + + +public class DmaapRequestCounterBuilderImpl implements DmaapRequestCounterBuilder { + private String name; + private MetricType metricType; + private long recievedMessage; + private long publishedMessage; + + @Override + public DmaapRequestCounterBuilder withName(String name) { + this.name=name; + return this; + } + + @Override + public DmaapRequestCounterBuilder withRecievedMessage(long value) { + + this.recievedMessage=value; + return this; + } + + @Override + public DmaapRequestCounterBuilder withPublishedMessage(long value) { + this.publishedMessage=value; + return this; + } + + @Override + public DmaapRequestCounterBuilder withType(MetricType type) { + this.metricType=type; + return this; + } + + @Override + public DmaapRequestCounterMetric build() { + return new DmaapRequestCounterMetricImpl(this.name,this.metricType,this.recievedMessage,this.publishedMessage); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java new file mode 100644 index 000000000..dd1a6fc08 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.TimeZone; +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class DmaapRequestCounterMetricImpl implements DmaapRequestCounterMetric { + + private String name; + private MetricType metricType; + private AtomicLong recievedMessage = new AtomicLong(); + private AtomicLong publishedMessage = new AtomicLong(); + + private final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); + private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); + + private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DmaapRequestCounterMetricImpl.class); + + public DmaapRequestCounterMetricImpl(String name, MetricType metricType, long recievedMessage, + long publishedMessage) { + this.name = name; + this.metricType = metricType; + this.recievedMessage.set(recievedMessage); + this.publishedMessage.set(publishedMessage); + } + + @Override + public void incrementRecievedMessage() { + this.recievedMessage.incrementAndGet(); + } + + @Override + public void incrementPublishedMessage() { + this.publishedMessage.incrementAndGet(); + } + + @Override + public String value() { + logger.debug("Value is getting calculated for metric :" + this.name); + try { + Calendar cal = Calendar.getInstance(); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + String date = dateFormat.format(cal.getTime()); + String value = date + "[" + recievedMessage.get() + "],[" + publishedMessage.get() + "]"; + logger.debug("Current value of the metric " + this.name + " :" + value); + return value; + } catch (Exception e) { + logger.debug("Cant format the date.",e); + } + return null; + } + + @Override + public String name() { + return this.name; + } + + @Override + public void reset() { + this.recievedMessage.set(0); + this.publishedMessage.set(0); + Calendar cal = Calendar.getInstance(); + lastResetTime = dateTimeFormat.format(cal.getTime()); + } + + @Override + public MetricType type() { + return this.metricType; + } + + @Override + public HashMap getMetricsOutput() { + HashMap dmaapMetricResult = new HashMap<>(); + dmaapMetricResult.put("Total Received messages", Long.toString(recievedMessage.get())); + dmaapMetricResult.put("Total Published messages", Long.toString(publishedMessage.get())); + return dmaapMetricResult; + } + + @Override + public String toString() { + return this.value(); + } + + @Override + public String getLastModified() { + return lastResetTime; + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java new file mode 100644 index 000000000..0a45941d1 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import org.onap.appc.metricservice.metric.DispatchingFunctionCounterBuilder; +import org.onap.appc.metricservice.metric.MetricBuilderFactory; +import org.onap.appc.metricservice.metric.PrimitiveCounterBuilder; +import org.onap.appc.metricservice.metric.DmaapRequestCounterBuilder; + + +public class MetricBuilderFactoryImpl implements MetricBuilderFactory { + @Override + public PrimitiveCounterBuilder primitiveCounterBuilder() { + return new PrimitiveCounterBuilderImpl(); + } + + @Override + public DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder() { + return new DispatchingFunctionCounterBuilderImpl() ; + } + + @Override + public DmaapRequestCounterBuilder dmaapRequestCounterBuilder() { + return new DmaapRequestCounterBuilderImpl(); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java new file mode 100644 index 000000000..c95f89e75 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.metric.impl; + +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.PrimitiveCounter; +import org.onap.appc.metricservice.metric.PrimitiveCounterBuilder; + + +public class PrimitiveCounterBuilderImpl implements PrimitiveCounterBuilder { + private String name; + private MetricType metricType; + private long counter; + + @Override + public PrimitiveCounterBuilder withName(String name) { + this.name=name; + return this; + } + + @Override + public PrimitiveCounterBuilder withValue(long value) { + this.counter=value; + return this; + } + + @Override + public PrimitiveCounterBuilder withType(MetricType type) { + this.metricType=type; + return this; + } + + @Override + public PrimitiveCounter build() { + return new DefaultPrimitiveCounter(this.name,this.metricType,this.counter); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PolicyBuilderFactory.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PolicyBuilderFactory.java new file mode 100644 index 000000000..fbdd04979 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PolicyBuilderFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy; + + +public interface PolicyBuilderFactory { + ScheduledPolicyBuilder scheduledPolicyBuilder(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PublishingPolicy.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PublishingPolicy.java new file mode 100644 index 000000000..44a05f994 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/PublishingPolicy.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.metricservice.metric.Metric; + +/** + * + * A custom logic that determines strategy of exposing metric values. + * Policy is associated with a specific registry and its implementation can very from the simplest options, such as 'real-time' behavior (upon each value change) to more sophisticated approaches such as thresholds or recurrent scheduling rules. + * The policy can also decide whether or not to publish the entire metric registry or just a subset of the it (e.g. changed ones). + * Policy supports execution of one or more Publishers. + * + */ +public interface PublishingPolicy { + void onMetricChange(Metric meric) throws APPCException; + Metric[] metrics(); + + void init(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPolicyBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPolicyBuilder.java new file mode 100644 index 000000000..d67031d03 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPolicyBuilder.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy; + +import org.onap.appc.metricservice.Publisher; +import org.onap.appc.metricservice.metric.Metric; + +/** + * + * An auxiliary class to instantiate scheduler-based policy delivered along with the initial release of the service. + * + */ +public interface ScheduledPolicyBuilder { + ScheduledPolicyBuilder withStartTime(long time); + ScheduledPolicyBuilder withPeriod(long period); + ScheduledPolicyBuilder withPublishers(Publisher[] publishers); + ScheduledPolicyBuilder withMetrics(Metric[] metrics); + PublishingPolicy build(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPublishingPolicy.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPublishingPolicy.java new file mode 100644 index 000000000..697ef3ff7 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/ScheduledPublishingPolicy.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy; + +import org.onap.appc.metricservice.Publisher; + + +public interface ScheduledPublishingPolicy extends PublishingPolicy{ + + long getStartTime(); + long getPeriod(); + Publisher[] getPublishers(); + void reset(); +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java new file mode 100644 index 000000000..d9c4cf024 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy.impl; + +import org.onap.appc.metricservice.policy.PolicyBuilderFactory; +import org.onap.appc.metricservice.policy.ScheduledPolicyBuilder; + + +public class PolicyBuilderFactoryImpl implements PolicyBuilderFactory { + @Override + public ScheduledPolicyBuilder scheduledPolicyBuilder() { + return new ScheduledPolicyBuilderImpl(); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java new file mode 100644 index 000000000..65ce62435 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy.impl; + +import org.onap.appc.metricservice.Publisher; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.policy.ScheduledPolicyBuilder; + + +public class ScheduledPolicyBuilderImpl implements ScheduledPolicyBuilder { + + private long startTime; + private long period; + private Publisher[] publishers; + private Metric[] metrics; + + @Override + public ScheduledPolicyBuilder withStartTime(long time) { + this.startTime=time; + return this; + } + + @Override + public ScheduledPolicyBuilder withPeriod(long period) { + this.period=period; + return this; + } + + @Override + public ScheduledPolicyBuilder withPublishers(Publisher[] publishers) { + this.publishers=publishers; + return this; + } + + @Override + public ScheduledPolicyBuilder withMetrics(Metric[] metrics) { + this.metrics=metrics; + return this; + } + + @Override + public PublishingPolicy build() { + return new ScheduledPublishingPolicyImpl(this.publishers,this.metrics); + } +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java new file mode 100644 index 000000000..8933150f3 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.policy.impl; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.Publisher; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.policy.ScheduledPublishingPolicy; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class ScheduledPublishingPolicyImpl implements ScheduledPublishingPolicy { + private long startTime; + private long period; + private Publisher[] publishers; + private Metric[] metrics; + private MetricRegistry metricRegistry; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ScheduledPublishingPolicyImpl.class); + private ScheduledExecutorService scheduleExecutor; + private Configuration configuration; + + public ScheduledPublishingPolicyImpl(long startTime, long period, Publisher[] publishers, Metric[] metrics) { + this.startTime = startTime; + this.period = period; + this.publishers = publishers; + this.metrics = metrics; + this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true)); + } + + public ScheduledPublishingPolicyImpl( Publisher[] publishers, Metric[] metrics) { + configuration = ConfigurationFactory.getConfiguration(); + Properties properties=configuration.getProperties(); + if(properties!=null){ + if(properties.getProperty("schedule.policy.metric.period")!=null && properties.getProperty("schedule.policy.metric.start.time")!=null){ + this.startTime = getConfigStartTime(properties); + this.period = getConfigPeriod(properties); + logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); + }else if(properties.getProperty("schedule.policy.metric.period")!=null){ + this.startTime=1; + this.period=getConfigPeriod(properties); + logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); + + }else if(properties.getProperty("schedule.policy.metric.period")==null && properties.getProperty("schedule.policy.metric.start.time")!=null){ + this.startTime=getConfigStartTime("00:00:00",properties); + this.period=(24*60*60*1000)-1; + logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); + + }else{ + logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms"); + this.startTime = 1; + this.period = 100000; + logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); + + } + } else { + logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms"); + this.startTime = 1; + this.period = 100000; + logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); + } + this.publishers = publishers; + this.metrics = metrics; + this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true)); + } + + private long getConfigPeriod(Properties properties) { + String period=properties.getProperty("schedule.policy.metric.period"); + logger.info("Metric period : " +period); + long periodInMs=Integer.parseInt(period)*1000; + logger.info("Metric period in long : " +periodInMs); + return periodInMs; + } + + private long getTimeInMs(String time) { + String[] strings=time.split(":"); + if(strings.length==3) { + long hour = Integer.parseInt(strings[0]) * 60 * 60 * 1000; + long min = Integer.parseInt(strings[1]) * 60 * 1000; + long sec = Integer.parseInt(strings[2]) * 1000; + return hour+min+sec; + }else{ + return 0; + } + + } + + + + private long getConfigStartTime(Properties properties) { + String startTime=properties.getProperty("schedule.policy.metric.start.time"); + if(startTime!=null){ + long timeDiff=(getTimeInMs(startTime))-(getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date()))); + long period=getConfigPeriod(properties); + if(timeDiff>=0){ + return timeDiff; + }else{ + return period-((timeDiff*-1)%period); + } + } + return 0; + } + + private long getConfigStartTime(String startTime,Properties properties) { + if(startTime!=null){ + long timeDiff=(getTimeInMs(startTime))-(getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date()))); + long period=getConfigPeriod(properties); + if(timeDiff>=0){ + return timeDiff%period; + }else{ + return period-((timeDiff*-1)%period); + } + } + return 0; + } + @Override + public void onMetricChange(Metric metric) throws APPCException { + //TODO + } + + @Override + public Metric[] metrics() { + return metrics; + } + + @Override + public void init() { + Properties properties=configuration.getProperties(); + boolean isMetricEnabled=false; + if(properties!=null){ + String metricProperty=properties.getProperty("metric.enabled"); + if(metricProperty!=null){ + isMetricEnabled=Boolean.valueOf(metricProperty); + } + } + if(isMetricEnabled){ + logger.info("Metric Service is enabled, hence policies getting scheduled"); + for(final Publisher publisher:this.getPublishers()){ + scheduleExecutor.scheduleWithFixedDelay(new Runnable() + { + public void run() { + try { + publisher.publish(metricRegistry, metrics); + reset(); + } catch (RuntimeException ex) { + logger.error("RuntimeException thrown from {}#report. Exception was suppressed.", publisher.getClass().getSimpleName(), ex); + } + } + } + , startTime, period, TimeUnit.MILLISECONDS); + } + }else{ + logger.info("Metric Service is not enabled, hence policies not getting scheduled"); + + } + } + + @Override + public long getStartTime() { + return this.startTime; + } + + @Override + public long getPeriod() { + return this.period; + } + + @Override + public Publisher[] getPublishers() { + return this.publishers; + } + + @Override + public void reset() { + for(Metric metric:this.metrics){ + metric.reset();} + } + + + private ThreadFactory getThreadFactory(final boolean isDaemon){ + return new ThreadFactory() { + public Thread newThread(Runnable r) { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setDaemon(isDaemon); + return t; + } + }; + } + +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/publisher/LogPublisher.java b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/publisher/LogPublisher.java new file mode 100644 index 000000000..e4f160d40 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/java/org/onap/appc/metricservice/publisher/LogPublisher.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice.publisher; + +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.Publisher; +import org.onap.appc.metricservice.metric.Metric; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class LogPublisher implements Publisher { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LogPublisher.class); + private MetricRegistry metricRegistry; + private Metric[] metrics; + + public LogPublisher(MetricRegistry metricRegistry, Metric[] metrics) { + this.metricRegistry = metricRegistry; + this.metrics = metrics; + } + + @Override + public void publish(MetricRegistry metricRegistry, Metric[] metrics) { + for(Metric metric:metrics){ + logger.debug("LOG PUBLISHER:"+metric.name()+":"+metric.toString()); + } + } + + +} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/MetricActivator.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/MetricActivator.java deleted file mode 100644 index 40ff14827..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/MetricActivator.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc; - -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.impl.MetricServiceImpl; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - - -public class MetricActivator implements BundleActivator { - - private ServiceRegistration registration = null; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MetricActivator.class); - - @Override - public void start(BundleContext bundleContext) throws Exception { - logger.debug("Starting Metric service " ); - MetricService impl = new MetricServiceImpl(); - String regName = MetricService.class.getName(); - logger.debug("Registering Metric service " + regName); - registration = bundleContext.registerService(regName, impl, null); - logger.debug("Registered Metric service " + regName); - } - - @Override - public void stop(BundleContext bundleContext) throws Exception { - - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricRegistry.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricRegistry.java deleted file mode 100644 index 6e658ae47..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricRegistry.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice; - -import org.onap.appc.metricservice.metric.Counter; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricBuilderFactory; -import org.onap.appc.metricservice.policy.PolicyBuilderFactory; -import org.onap.appc.metricservice.policy.PublishingPolicy; - -/** - * - * A named group of metrics which might be related to a specific domain. The service doesn't limit number of metric registries per instance. - * It's up to application to decide on domain scope. The registry instances are independent. - * - */ -public interface MetricRegistry { - boolean register(Metric metric); - void attach (PublishingPolicy publishPolicy); - MetricBuilderFactory metricBuilderFactory(); - PolicyBuilderFactory policyBuilderFactory(); - Counter counter(String value); - Counter[] counters(); - Metric[] metrics(); - Metric metric(String metricName); - void dispose(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricService.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricService.java deleted file mode 100644 index 65ff72d97..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/MetricService.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice; - - -import java.util.Map; - -public interface MetricService { - MetricRegistry registry(String name); - MetricRegistry createRegistry(String name); - void dispose(); - - /** - * This API will be used to get the Map of all the registered Registry for the Metric Service - * @return Map where String will be the name of the Metric Registry - * and MetricRegistry will be the actual object for that Registry - */ - Map getAllRegistry(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/Publisher.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/Publisher.java deleted file mode 100644 index 1d38e44c3..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/Publisher.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice; - -import org.onap.appc.metricservice.metric.Metric; - -/** - * Low-level logic of exposing metric values in certain way. There might be plenty of options such as logging, JMX, etc. - * API to be supported by any logic that is going to be plugged into metric service. - * The publisher is considered as low-level technical unit which, potentially, can be reused to expose metrics from different registries - * - */ -public interface Publisher { - void publish(MetricRegistry metricRegistry,Metric[] metrics); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricRegistryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricRegistryImpl.java deleted file mode 100644 index ac2054151..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricRegistryImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.impl; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.metric.Counter; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricBuilderFactory; -import org.onap.appc.metricservice.metric.impl.MetricBuilderFactoryImpl; -import org.onap.appc.metricservice.policy.PolicyBuilderFactory; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.policy.impl.PolicyBuilderFactoryImpl; - - -public class MetricRegistryImpl implements MetricRegistry { - private String name; - private Map concurrentMetricMap=new ConcurrentHashMap(); - - public MetricRegistryImpl(String name) { - this.name = name; - } - - @Override - public boolean register(Metric metric) { - if(concurrentMetricMap.get(metric.name())==null){ - concurrentMetricMap.put(metric.name(),metric); - return true; - } - return false; - } - - @Override - public void attach(PublishingPolicy publishPolicy) { -//TODO - } - - @Override - public MetricBuilderFactory metricBuilderFactory() { - return new MetricBuilderFactoryImpl(); - } - - @Override - public PolicyBuilderFactory policyBuilderFactory() { - return new PolicyBuilderFactoryImpl() ; - } - - @Override - public Counter counter(String value) { - if(concurrentMetricMap.get(value)!=null ) - return (Counter)concurrentMetricMap.get(value) ; - else - return null; - - } - - @Override - public Counter[] counters() { - return (Counter[])concurrentMetricMap.values().toArray(); - } - - @Override - public Metric[] metrics() { - java.util.Collection var = concurrentMetricMap.values(); - return var.toArray(new Metric[var.size()]); - } - - @Override - public Metric metric(String metricName) { - return concurrentMetricMap.get(metricName); - } - - @Override - public void dispose() { - concurrentMetricMap.clear(); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricServiceImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricServiceImpl.java deleted file mode 100644 index 20f2d8d2e..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/impl/MetricServiceImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.impl; - -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; - - -public class MetricServiceImpl implements MetricService { - private Map concurrentRegistryMap=new ConcurrentHashMap<>(); - @Override - public MetricRegistry registry(String name) { - return concurrentRegistryMap.get(name); - } - - @Override - public MetricRegistry createRegistry(String name) { - if(concurrentRegistryMap.get(name)==null) - concurrentRegistryMap.put(name,new MetricRegistryImpl(name)); - return concurrentRegistryMap.get(name); - } - - @Override - public Map getAllRegistry(){ - return Collections.unmodifiableMap(concurrentRegistryMap); - - } - - @Override - public void dispose() { -//TODO - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Counter.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Counter.java deleted file mode 100644 index 0b4d3e2d3..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Counter.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface Counter extends Metric { - long value(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java deleted file mode 100644 index bff07f627..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFunctionCounterBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface DispatchingFunctionCounterBuilder { - DispatchingFunctionCounterBuilder withName(String name); - DispatchingFunctionCounterBuilder withAcceptRequestValue(long value); - DispatchingFunctionCounterBuilder withRejectRequestValue(long value); - DispatchingFunctionCounterBuilder withType(MetricType type); - DispatchingFuntionMetric build(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFuntionMetric.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFuntionMetric.java deleted file mode 100644 index 384875e9b..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DispatchingFuntionMetric.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface DispatchingFuntionMetric extends Metric { - void incrementAcceptedRequest(); - void incrementRejectedRequest(); - String value(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterBuilder.java deleted file mode 100644 index efb23963f..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface DmaapRequestCounterBuilder { - DmaapRequestCounterBuilder withName(String name); - DmaapRequestCounterBuilder withRecievedMessage(long value); - DmaapRequestCounterBuilder withPublishedMessage(long value); - DmaapRequestCounterBuilder withType(MetricType type); - DmaapRequestCounterMetric build(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterMetric.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterMetric.java deleted file mode 100644 index 522432631..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/DmaapRequestCounterMetric.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface DmaapRequestCounterMetric extends Metric { - void incrementRecievedMessage(); - void incrementPublishedMessage(); - String value(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Metric.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Metric.java deleted file mode 100644 index ce4297c88..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/Metric.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - -import java.util.HashMap; - -/** - * - * a measure of system parameter at the current moment. Each metric is identified by name. - * In general case, a metric just reflects its (almost) real-time value and is not responsible for maintaining its historical data. - * One that needs to build series of a metric values for statistical/analytic purposes should query the value and store it for further processing. - * Metrics can be of different types - counters, timers etc. - * The initial service implementation supports simple (flat) counters only. - * - */ -public interface Metric { - String name(); - void reset(); - MetricType type(); - /** - * This API will be used to get all the running Metrics Output. - * @return HashMap in which - * the First String(Key) will be the name of the KPI property - * and another String(Value of the Key) will be the Value of - * that property for that KPI - */ - HashMap getMetricsOutput(); - /** - * Return last modified date for KPI in string format - * @return - last modified date for KPI - */ - String getLastModified(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricBuilderFactory.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricBuilderFactory.java deleted file mode 100644 index 5a35247d3..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricBuilderFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - - -public interface MetricBuilderFactory { - - PrimitiveCounterBuilder primitiveCounterBuilder(); - DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder(); - DmaapRequestCounterBuilder dmaapRequestCounterBuilder(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricType.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricType.java deleted file mode 100644 index 3f8ec30a8..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/MetricType.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - -/** - * - * Auxiliary enumeration that lists all the supported metric types. - * Can be used for generic processing of metrics rather than using Java reflection mechanisms to determine metric kind. - * - */ -public enum MetricType { -COUNTER -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounter.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounter.java deleted file mode 100644 index a3fc2191f..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounter.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - -/** - * - * The simplest metric of type counter which mutable value. - */ -public interface PrimitiveCounter extends Counter{ - void increment(); - void increment(long value); - void decrement(); - void decrement(long value); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounterBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounterBuilder.java deleted file mode 100644 index ded5ecf47..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/PrimitiveCounterBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric; - -/** - * - * Builder interface which can be used to instantiate and initialize a new primitive counter instance. - */ -public interface PrimitiveCounterBuilder { - PrimitiveCounterBuilder withName(String name); - PrimitiveCounterBuilder withValue(long value); - PrimitiveCounterBuilder withType(MetricType type); - PrimitiveCounter build(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java deleted file mode 100644 index 4b1992986..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DefaultPrimitiveCounter.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.PrimitiveCounter; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicLong; - - -public class DefaultPrimitiveCounter implements PrimitiveCounter { - private String name; - private MetricType metricType; - private AtomicLong counter = new AtomicLong(); - - private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); - private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); - - public DefaultPrimitiveCounter(String name, MetricType metricType, long counter) { - this.name = name; - this.metricType = metricType; - this.counter.set(counter); - } - - public DefaultPrimitiveCounter(String name, MetricType metricType) { - this.counter.set(0); - this.name = name; - this.metricType = metricType; - } - - @Override - public void increment() { - increment(1); - } - - @Override - public void increment(long value) { - this.counter.incrementAndGet(); - } - - @Override - public void decrement() { - decrement(1); - } - - @Override - public void decrement(long value) { - this.counter.decrementAndGet(); - } - - @Override - public long value() { - return this.counter.get(); - } - - @Override - public String name() { - return this.name; - } - - @Override - public void reset() { - this.counter.set(0); - Calendar cal = Calendar.getInstance(); - lastResetTime = dateTimeFormat.format(cal.getTime()); - } - - @Override - public String toString() { - return "DefaultPrimitiveCounter{" + "name='" + name + '\'' + ", metricType=" + metricType + ", counter=" - + counter.get() + '}'; - } - - @Override - public MetricType type() { - return this.metricType; - } - - @Override - public HashMap getMetricsOutput() { - return new HashMap<>(); - } - - @Override - public String getLastModified() { - return lastResetTime; - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java deleted file mode 100644 index fd3b05ef7..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFunctionCounterBuilderImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import org.onap.appc.metricservice.metric.DispatchingFunctionCounterBuilder; -import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; -import org.onap.appc.metricservice.metric.MetricType; - - -public class DispatchingFunctionCounterBuilderImpl implements DispatchingFunctionCounterBuilder { - private String name; - private MetricType metricType; - private long acceptedRequested; - private long rejectedRequest; - - @Override - public DispatchingFunctionCounterBuilder withName(String name) { - this.name=name; - return this; - } - - @Override - public DispatchingFunctionCounterBuilder withAcceptRequestValue(long value) { - this.acceptedRequested=value; - return this; - } - @Override - public DispatchingFunctionCounterBuilder withRejectRequestValue(long value) { - this.rejectedRequest=value; - return this; - } - @Override - public DispatchingFunctionCounterBuilder withType(MetricType type) { - this.metricType=type; - return this; - } - - @Override - public DispatchingFuntionMetric build() { - return new DispatchingFuntionMetricImpl(this.name,this.metricType,this.acceptedRequested,this.rejectedRequest); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java deleted file mode 100644 index a6487957f..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DispatchingFuntionMetricImpl.java +++ /dev/null @@ -1,124 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashMap; -import java.util.TimeZone; -import java.util.concurrent.atomic.AtomicLong; - -import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; -import org.onap.appc.metricservice.metric.MetricType; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class DispatchingFuntionMetricImpl implements DispatchingFuntionMetric { - private String name; - private MetricType metricType; - private AtomicLong acceptedRequested = new AtomicLong(); - private AtomicLong rejectedRequest = new AtomicLong(); - - private final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); - private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); - - private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DispatchingFuntionMetricImpl.class); - - public DispatchingFuntionMetricImpl(String name, MetricType metricType, long acceptedRequested, - long rejectedRequest) { - this.name = name; - this.metricType = metricType; - this.acceptedRequested.set(acceptedRequested); - this.rejectedRequest.set(rejectedRequest); - } - - @Override - public void incrementAcceptedRequest() { - this.acceptedRequested.incrementAndGet(); - } - - @Override - public void incrementRejectedRequest() { - this.rejectedRequest.incrementAndGet(); - } - - @Override - public String value() { - logger.debug("Value is getting calculated for metric :" + this.name); - try { - Calendar cal = Calendar.getInstance(); - cal.setTimeZone(TimeZone.getTimeZone("UTC")); - String date = dateFormat.format(cal.getTime()); - String value = date + "[" + acceptedRequested.get() + "," + rejectedRequest.get() + "]" + "@" - + (acceptedRequested.get() + rejectedRequest.get()); - logger.debug("Current value of the metric " + this.name + " :" + value); - return value; - - } catch (Exception e) { - logger.debug("Cant format the date.",e); - } - return null; - - } - - @Override - public String name() { - return this.name; - } - - @Override - public void reset() { - this.acceptedRequested.set(0); - this.rejectedRequest.set(0); - Calendar cal = Calendar.getInstance(); - lastResetTime = dateTimeFormat.format(cal.getTime()); - } - - @Override - public MetricType type() { - return this.metricType; - } - - @Override - public HashMap getMetricsOutput() { - HashMap dispatcherMetricResult = new HashMap<>(); - dispatcherMetricResult.put("Total Received messages", - Long.toString(acceptedRequested.get() + rejectedRequest.get())); - dispatcherMetricResult.put("Total Rejected messages", Long.toString(rejectedRequest.get())); - return dispatcherMetricResult; - } - - @Override - public String toString() { - return this.value(); - } - - @Override - public String getLastModified() { - return lastResetTime; - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java deleted file mode 100644 index b5b53a810..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterBuilderImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.DmaapRequestCounterBuilder; -import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; - - -public class DmaapRequestCounterBuilderImpl implements DmaapRequestCounterBuilder { - private String name; - private MetricType metricType; - private long recievedMessage; - private long publishedMessage; - - @Override - public DmaapRequestCounterBuilder withName(String name) { - this.name=name; - return this; - } - - @Override - public DmaapRequestCounterBuilder withRecievedMessage(long value) { - - this.recievedMessage=value; - return this; - } - - @Override - public DmaapRequestCounterBuilder withPublishedMessage(long value) { - this.publishedMessage=value; - return this; - } - - @Override - public DmaapRequestCounterBuilder withType(MetricType type) { - this.metricType=type; - return this; - } - - @Override - public DmaapRequestCounterMetric build() { - return new DmaapRequestCounterMetricImpl(this.name,this.metricType,this.recievedMessage,this.publishedMessage); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java deleted file mode 100644 index dd1a6fc08..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/DmaapRequestCounterMetricImpl.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashMap; -import java.util.TimeZone; -import java.util.concurrent.atomic.AtomicLong; - -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class DmaapRequestCounterMetricImpl implements DmaapRequestCounterMetric { - - private String name; - private MetricType metricType; - private AtomicLong recievedMessage = new AtomicLong(); - private AtomicLong publishedMessage = new AtomicLong(); - - private final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); - private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("YYYY-MM-dd:HH:mm:ss"); - - private String lastResetTime = dateTimeFormat.format(Calendar.getInstance().getTime()); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DmaapRequestCounterMetricImpl.class); - - public DmaapRequestCounterMetricImpl(String name, MetricType metricType, long recievedMessage, - long publishedMessage) { - this.name = name; - this.metricType = metricType; - this.recievedMessage.set(recievedMessage); - this.publishedMessage.set(publishedMessage); - } - - @Override - public void incrementRecievedMessage() { - this.recievedMessage.incrementAndGet(); - } - - @Override - public void incrementPublishedMessage() { - this.publishedMessage.incrementAndGet(); - } - - @Override - public String value() { - logger.debug("Value is getting calculated for metric :" + this.name); - try { - Calendar cal = Calendar.getInstance(); - cal.setTimeZone(TimeZone.getTimeZone("UTC")); - String date = dateFormat.format(cal.getTime()); - String value = date + "[" + recievedMessage.get() + "],[" + publishedMessage.get() + "]"; - logger.debug("Current value of the metric " + this.name + " :" + value); - return value; - } catch (Exception e) { - logger.debug("Cant format the date.",e); - } - return null; - } - - @Override - public String name() { - return this.name; - } - - @Override - public void reset() { - this.recievedMessage.set(0); - this.publishedMessage.set(0); - Calendar cal = Calendar.getInstance(); - lastResetTime = dateTimeFormat.format(cal.getTime()); - } - - @Override - public MetricType type() { - return this.metricType; - } - - @Override - public HashMap getMetricsOutput() { - HashMap dmaapMetricResult = new HashMap<>(); - dmaapMetricResult.put("Total Received messages", Long.toString(recievedMessage.get())); - dmaapMetricResult.put("Total Published messages", Long.toString(publishedMessage.get())); - return dmaapMetricResult; - } - - @Override - public String toString() { - return this.value(); - } - - @Override - public String getLastModified() { - return lastResetTime; - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java deleted file mode 100644 index 0a45941d1..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/MetricBuilderFactoryImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import org.onap.appc.metricservice.metric.DispatchingFunctionCounterBuilder; -import org.onap.appc.metricservice.metric.MetricBuilderFactory; -import org.onap.appc.metricservice.metric.PrimitiveCounterBuilder; -import org.onap.appc.metricservice.metric.DmaapRequestCounterBuilder; - - -public class MetricBuilderFactoryImpl implements MetricBuilderFactory { - @Override - public PrimitiveCounterBuilder primitiveCounterBuilder() { - return new PrimitiveCounterBuilderImpl(); - } - - @Override - public DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder() { - return new DispatchingFunctionCounterBuilderImpl() ; - } - - @Override - public DmaapRequestCounterBuilder dmaapRequestCounterBuilder() { - return new DmaapRequestCounterBuilderImpl(); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java deleted file mode 100644 index c95f89e75..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/metric/impl/PrimitiveCounterBuilderImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.metric.impl; - -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.PrimitiveCounter; -import org.onap.appc.metricservice.metric.PrimitiveCounterBuilder; - - -public class PrimitiveCounterBuilderImpl implements PrimitiveCounterBuilder { - private String name; - private MetricType metricType; - private long counter; - - @Override - public PrimitiveCounterBuilder withName(String name) { - this.name=name; - return this; - } - - @Override - public PrimitiveCounterBuilder withValue(long value) { - this.counter=value; - return this; - } - - @Override - public PrimitiveCounterBuilder withType(MetricType type) { - this.metricType=type; - return this; - } - - @Override - public PrimitiveCounter build() { - return new DefaultPrimitiveCounter(this.name,this.metricType,this.counter); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PolicyBuilderFactory.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PolicyBuilderFactory.java deleted file mode 100644 index fbdd04979..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PolicyBuilderFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy; - - -public interface PolicyBuilderFactory { - ScheduledPolicyBuilder scheduledPolicyBuilder(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PublishingPolicy.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PublishingPolicy.java deleted file mode 100644 index 44a05f994..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/PublishingPolicy.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.metricservice.metric.Metric; - -/** - * - * A custom logic that determines strategy of exposing metric values. - * Policy is associated with a specific registry and its implementation can very from the simplest options, such as 'real-time' behavior (upon each value change) to more sophisticated approaches such as thresholds or recurrent scheduling rules. - * The policy can also decide whether or not to publish the entire metric registry or just a subset of the it (e.g. changed ones). - * Policy supports execution of one or more Publishers. - * - */ -public interface PublishingPolicy { - void onMetricChange(Metric meric) throws APPCException; - Metric[] metrics(); - - void init(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPolicyBuilder.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPolicyBuilder.java deleted file mode 100644 index d67031d03..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPolicyBuilder.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy; - -import org.onap.appc.metricservice.Publisher; -import org.onap.appc.metricservice.metric.Metric; - -/** - * - * An auxiliary class to instantiate scheduler-based policy delivered along with the initial release of the service. - * - */ -public interface ScheduledPolicyBuilder { - ScheduledPolicyBuilder withStartTime(long time); - ScheduledPolicyBuilder withPeriod(long period); - ScheduledPolicyBuilder withPublishers(Publisher[] publishers); - ScheduledPolicyBuilder withMetrics(Metric[] metrics); - PublishingPolicy build(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPublishingPolicy.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPublishingPolicy.java deleted file mode 100644 index 697ef3ff7..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/ScheduledPublishingPolicy.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy; - -import org.onap.appc.metricservice.Publisher; - - -public interface ScheduledPublishingPolicy extends PublishingPolicy{ - - long getStartTime(); - long getPeriod(); - Publisher[] getPublishers(); - void reset(); -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java deleted file mode 100644 index d9c4cf024..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/PolicyBuilderFactoryImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy.impl; - -import org.onap.appc.metricservice.policy.PolicyBuilderFactory; -import org.onap.appc.metricservice.policy.ScheduledPolicyBuilder; - - -public class PolicyBuilderFactoryImpl implements PolicyBuilderFactory { - @Override - public ScheduledPolicyBuilder scheduledPolicyBuilder() { - return new ScheduledPolicyBuilderImpl(); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java deleted file mode 100644 index 65ce62435..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPolicyBuilderImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy.impl; - -import org.onap.appc.metricservice.Publisher; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.policy.ScheduledPolicyBuilder; - - -public class ScheduledPolicyBuilderImpl implements ScheduledPolicyBuilder { - - private long startTime; - private long period; - private Publisher[] publishers; - private Metric[] metrics; - - @Override - public ScheduledPolicyBuilder withStartTime(long time) { - this.startTime=time; - return this; - } - - @Override - public ScheduledPolicyBuilder withPeriod(long period) { - this.period=period; - return this; - } - - @Override - public ScheduledPolicyBuilder withPublishers(Publisher[] publishers) { - this.publishers=publishers; - return this; - } - - @Override - public ScheduledPolicyBuilder withMetrics(Metric[] metrics) { - this.metrics=metrics; - return this; - } - - @Override - public PublishingPolicy build() { - return new ScheduledPublishingPolicyImpl(this.publishers,this.metrics); - } -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java deleted file mode 100644 index 8933150f3..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/policy/impl/ScheduledPublishingPolicyImpl.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.policy.impl; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.Publisher; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.policy.ScheduledPublishingPolicy; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class ScheduledPublishingPolicyImpl implements ScheduledPublishingPolicy { - private long startTime; - private long period; - private Publisher[] publishers; - private Metric[] metrics; - private MetricRegistry metricRegistry; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ScheduledPublishingPolicyImpl.class); - private ScheduledExecutorService scheduleExecutor; - private Configuration configuration; - - public ScheduledPublishingPolicyImpl(long startTime, long period, Publisher[] publishers, Metric[] metrics) { - this.startTime = startTime; - this.period = period; - this.publishers = publishers; - this.metrics = metrics; - this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true)); - } - - public ScheduledPublishingPolicyImpl( Publisher[] publishers, Metric[] metrics) { - configuration = ConfigurationFactory.getConfiguration(); - Properties properties=configuration.getProperties(); - if(properties!=null){ - if(properties.getProperty("schedule.policy.metric.period")!=null && properties.getProperty("schedule.policy.metric.start.time")!=null){ - this.startTime = getConfigStartTime(properties); - this.period = getConfigPeriod(properties); - logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); - }else if(properties.getProperty("schedule.policy.metric.period")!=null){ - this.startTime=1; - this.period=getConfigPeriod(properties); - logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); - - }else if(properties.getProperty("schedule.policy.metric.period")==null && properties.getProperty("schedule.policy.metric.start.time")!=null){ - this.startTime=getConfigStartTime("00:00:00",properties); - this.period=(24*60*60*1000)-1; - logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); - - }else{ - logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms"); - this.startTime = 1; - this.period = 100000; - logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); - - } - } else { - logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms"); - this.startTime = 1; - this.period = 100000; - logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :"+this.period); - } - this.publishers = publishers; - this.metrics = metrics; - this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true)); - } - - private long getConfigPeriod(Properties properties) { - String period=properties.getProperty("schedule.policy.metric.period"); - logger.info("Metric period : " +period); - long periodInMs=Integer.parseInt(period)*1000; - logger.info("Metric period in long : " +periodInMs); - return periodInMs; - } - - private long getTimeInMs(String time) { - String[] strings=time.split(":"); - if(strings.length==3) { - long hour = Integer.parseInt(strings[0]) * 60 * 60 * 1000; - long min = Integer.parseInt(strings[1]) * 60 * 1000; - long sec = Integer.parseInt(strings[2]) * 1000; - return hour+min+sec; - }else{ - return 0; - } - - } - - - - private long getConfigStartTime(Properties properties) { - String startTime=properties.getProperty("schedule.policy.metric.start.time"); - if(startTime!=null){ - long timeDiff=(getTimeInMs(startTime))-(getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date()))); - long period=getConfigPeriod(properties); - if(timeDiff>=0){ - return timeDiff; - }else{ - return period-((timeDiff*-1)%period); - } - } - return 0; - } - - private long getConfigStartTime(String startTime,Properties properties) { - if(startTime!=null){ - long timeDiff=(getTimeInMs(startTime))-(getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date()))); - long period=getConfigPeriod(properties); - if(timeDiff>=0){ - return timeDiff%period; - }else{ - return period-((timeDiff*-1)%period); - } - } - return 0; - } - @Override - public void onMetricChange(Metric metric) throws APPCException { - //TODO - } - - @Override - public Metric[] metrics() { - return metrics; - } - - @Override - public void init() { - Properties properties=configuration.getProperties(); - boolean isMetricEnabled=false; - if(properties!=null){ - String metricProperty=properties.getProperty("metric.enabled"); - if(metricProperty!=null){ - isMetricEnabled=Boolean.valueOf(metricProperty); - } - } - if(isMetricEnabled){ - logger.info("Metric Service is enabled, hence policies getting scheduled"); - for(final Publisher publisher:this.getPublishers()){ - scheduleExecutor.scheduleWithFixedDelay(new Runnable() - { - public void run() { - try { - publisher.publish(metricRegistry, metrics); - reset(); - } catch (RuntimeException ex) { - logger.error("RuntimeException thrown from {}#report. Exception was suppressed.", publisher.getClass().getSimpleName(), ex); - } - } - } - , startTime, period, TimeUnit.MILLISECONDS); - } - }else{ - logger.info("Metric Service is not enabled, hence policies not getting scheduled"); - - } - } - - @Override - public long getStartTime() { - return this.startTime; - } - - @Override - public long getPeriod() { - return this.period; - } - - @Override - public Publisher[] getPublishers() { - return this.publishers; - } - - @Override - public void reset() { - for(Metric metric:this.metrics){ - metric.reset();} - } - - - private ThreadFactory getThreadFactory(final boolean isDaemon){ - return new ThreadFactory() { - public Thread newThread(Runnable r) { - Thread t = Executors.defaultThreadFactory().newThread(r); - t.setDaemon(isDaemon); - return t; - } - }; - } - -} diff --git a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/publisher/LogPublisher.java b/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/publisher/LogPublisher.java deleted file mode 100644 index e4f160d40..000000000 --- a/appc-metric/appc-metric-bundle/src/main/java/org/openecomp/appc/metricservice/publisher/LogPublisher.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice.publisher; - -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.Publisher; -import org.onap.appc.metricservice.metric.Metric; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class LogPublisher implements Publisher { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LogPublisher.class); - private MetricRegistry metricRegistry; - private Metric[] metrics; - - public LogPublisher(MetricRegistry metricRegistry, Metric[] metrics) { - this.metricRegistry = metricRegistry; - this.metrics = metrics; - } - - @Override - public void publish(MetricRegistry metricRegistry, Metric[] metrics) { - for(Metric metric:metrics){ - logger.debug("LOG PUBLISHER:"+metric.name()+":"+metric.toString()); - } - } - - -} diff --git a/appc-metric/appc-metric-bundle/src/main/resources/org/onap/appc/default.properties b/appc-metric/appc-metric-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..f7eae381e --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,31 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + + + diff --git a/appc-metric/appc-metric-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-metric/appc-metric-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index f7eae381e..000000000 --- a/appc-metric/appc-metric-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,31 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - - - diff --git a/appc-metric/appc-metric-bundle/src/test/java/org/onap/appc/metricservice/TestMetricServiceImpl.java b/appc-metric/appc-metric-bundle/src/test/java/org/onap/appc/metricservice/TestMetricServiceImpl.java new file mode 100644 index 000000000..7c8011e81 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/test/java/org/onap/appc/metricservice/TestMetricServiceImpl.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metricservice; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.metricservice.impl.MetricServiceImpl; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.PrimitiveCounter; +import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; +import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; +import org.onap.appc.metricservice.metric.impl.DefaultPrimitiveCounter; +import org.onap.appc.metricservice.metric.impl.DmaapRequestCounterMetricImpl; +import org.onap.appc.metricservice.metric.impl.DispatchingFuntionMetricImpl; +import org.onap.appc.metricservice.metric.impl.DispatchingFunctionCounterBuilderImpl; +import org.onap.appc.metricservice.metric.impl.DmaapRequestCounterBuilderImpl; +import org.onap.appc.metricservice.metric.impl.PrimitiveCounterBuilderImpl; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.TimeZone; + + +public class TestMetricServiceImpl { + @Test + public void createRegistryTest() { + MetricServiceImpl metricServiceImpl = new MetricServiceImpl(); + metricServiceImpl.createRegistry("anyName"); + MetricRegistry metricRegistry = metricServiceImpl.registry("anyName"); + Assert.assertNotNull(metricRegistry); + Assert.assertTrue(metricServiceImpl.getAllRegistry().keySet().contains("anyName")); + } + + @Test + public void testDefaultPrimitiveCounter(){ + DefaultPrimitiveCounter df= new DefaultPrimitiveCounter("TEST", MetricType.COUNTER); + df.increment(); + Assert.assertEquals(1, df.value()); + df.increment(25); + Assert.assertEquals(2, df.value()); + df.decrement(); + Assert.assertEquals(1, df.value()); + Assert.assertNotNull(df.getLastModified()); + Assert.assertEquals("TEST",df.name()); + Assert.assertEquals(MetricType.COUNTER,df.type()); + df.reset(); + Assert.assertEquals(0,df.value()); + Assert.assertNotNull(df.getMetricsOutput()); + + } + + @Test + public void testDefaultPrimitiveCounterWithThreeArgsConstructor(){ + DefaultPrimitiveCounter obj= new DefaultPrimitiveCounter("TEST", MetricType.COUNTER,3); + obj.increment(); + Assert.assertEquals(4, obj.value()); + obj.increment(25); + Assert.assertEquals(5, obj.value()); + obj.decrement(); + Assert.assertEquals(4, obj.value()); + Assert.assertNotNull(obj.getLastModified()); + Assert.assertEquals("TEST",obj.name()); + Assert.assertEquals(MetricType.COUNTER,obj.type()); + obj.reset(); + Assert.assertEquals(0,obj.value()); + Assert.assertNotNull(obj.getMetricsOutput()); + } + + @Test + public void testDmaapRequestCounterMetricImpl() { + + DmaapRequestCounterMetricImpl obj =new DmaapRequestCounterMetricImpl("TEST",MetricType.COUNTER,7,1); + String date = getCurrentDate(); + + obj.incrementPublishedMessage(); + obj.incrementRecievedMessage(); + Assert.assertEquals(2,Integer.parseInt(obj.getMetricsOutput().get("Total Published messages"))); + Assert.assertEquals(8,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); + Assert.assertEquals(date+"[8],[2]",obj.value()); + Assert.assertNotNull(obj.getLastModified()); + Assert.assertEquals("TEST",obj.name()); + Assert.assertEquals(MetricType.COUNTER,obj.type()); + obj.reset(); + Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Published messages"))); + Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); + + } + + @Test + public void testDispatchingFuntionMetricImpl() { + + DispatchingFuntionMetricImpl obj= new DispatchingFuntionMetricImpl("TEST",MetricType.COUNTER,7,1); + String date = getCurrentDate(); + + obj.incrementAcceptedRequest(); + obj.incrementRejectedRequest(); + Assert.assertEquals(10,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); + Assert.assertEquals(2,Integer.parseInt(obj.getMetricsOutput().get("Total Rejected messages"))); + Assert.assertEquals(date+"[8,2]@10",obj.value()); + Assert.assertNotNull(obj.getLastModified()); + Assert.assertEquals("TEST",obj.name()); + Assert.assertEquals(MetricType.COUNTER,obj.type()); + obj.reset(); + Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); + Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Rejected messages"))); + + + } + + @Test + public void testDispatchingFunctionCounterBuilderImpl(){ + DispatchingFunctionCounterBuilderImpl obj=new DispatchingFunctionCounterBuilderImpl(); + String date = getCurrentDate(); + DispatchingFuntionMetric metric=obj.withName("TEST").withType(MetricType.COUNTER).withAcceptRequestValue(7).withRejectRequestValue(2).build(); + metric.incrementAcceptedRequest(); + metric.incrementRejectedRequest(); + Assert.assertEquals(date+"[8,3]@11",metric.value()); + } + + @Test + public void testDmaapRequestCounterBuilderImpl(){ + DmaapRequestCounterBuilderImpl obj=new DmaapRequestCounterBuilderImpl(); + DmaapRequestCounterMetric metric =obj.withName("TEST").withPublishedMessage(1).withRecievedMessage(21).withType(MetricType.COUNTER).build(); + metric.incrementPublishedMessage(); + metric.incrementRecievedMessage(); + Assert.assertEquals(2,Integer.parseInt(metric.getMetricsOutput().get("Total Published messages"))); + Assert.assertEquals(22,Integer.parseInt(metric.getMetricsOutput().get("Total Received messages"))); + } + + @Test + public void testPrimitiveCounterBuilderImpl(){ + PrimitiveCounterBuilderImpl obj=new PrimitiveCounterBuilderImpl(); + PrimitiveCounter counter=obj.withName("TEST").withType(MetricType.COUNTER).withValue(1).build(); + counter.increment(); + Assert.assertEquals(2, counter.value()); + counter.decrement(); + Assert.assertEquals(1, counter.value()); + } + + private String getCurrentDate() { + Calendar cal = Calendar.getInstance(); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); + return dateFormat.format(cal.getTime()); + + } + +} diff --git a/appc-metric/appc-metric-bundle/src/test/java/org/openecomp/appc/metricservice/TestMetricServiceImpl.java b/appc-metric/appc-metric-bundle/src/test/java/org/openecomp/appc/metricservice/TestMetricServiceImpl.java deleted file mode 100644 index 7c8011e81..000000000 --- a/appc-metric/appc-metric-bundle/src/test/java/org/openecomp/appc/metricservice/TestMetricServiceImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.metricservice; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.metricservice.impl.MetricServiceImpl; -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.PrimitiveCounter; -import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; -import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; -import org.onap.appc.metricservice.metric.impl.DefaultPrimitiveCounter; -import org.onap.appc.metricservice.metric.impl.DmaapRequestCounterMetricImpl; -import org.onap.appc.metricservice.metric.impl.DispatchingFuntionMetricImpl; -import org.onap.appc.metricservice.metric.impl.DispatchingFunctionCounterBuilderImpl; -import org.onap.appc.metricservice.metric.impl.DmaapRequestCounterBuilderImpl; -import org.onap.appc.metricservice.metric.impl.PrimitiveCounterBuilderImpl; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.TimeZone; - - -public class TestMetricServiceImpl { - @Test - public void createRegistryTest() { - MetricServiceImpl metricServiceImpl = new MetricServiceImpl(); - metricServiceImpl.createRegistry("anyName"); - MetricRegistry metricRegistry = metricServiceImpl.registry("anyName"); - Assert.assertNotNull(metricRegistry); - Assert.assertTrue(metricServiceImpl.getAllRegistry().keySet().contains("anyName")); - } - - @Test - public void testDefaultPrimitiveCounter(){ - DefaultPrimitiveCounter df= new DefaultPrimitiveCounter("TEST", MetricType.COUNTER); - df.increment(); - Assert.assertEquals(1, df.value()); - df.increment(25); - Assert.assertEquals(2, df.value()); - df.decrement(); - Assert.assertEquals(1, df.value()); - Assert.assertNotNull(df.getLastModified()); - Assert.assertEquals("TEST",df.name()); - Assert.assertEquals(MetricType.COUNTER,df.type()); - df.reset(); - Assert.assertEquals(0,df.value()); - Assert.assertNotNull(df.getMetricsOutput()); - - } - - @Test - public void testDefaultPrimitiveCounterWithThreeArgsConstructor(){ - DefaultPrimitiveCounter obj= new DefaultPrimitiveCounter("TEST", MetricType.COUNTER,3); - obj.increment(); - Assert.assertEquals(4, obj.value()); - obj.increment(25); - Assert.assertEquals(5, obj.value()); - obj.decrement(); - Assert.assertEquals(4, obj.value()); - Assert.assertNotNull(obj.getLastModified()); - Assert.assertEquals("TEST",obj.name()); - Assert.assertEquals(MetricType.COUNTER,obj.type()); - obj.reset(); - Assert.assertEquals(0,obj.value()); - Assert.assertNotNull(obj.getMetricsOutput()); - } - - @Test - public void testDmaapRequestCounterMetricImpl() { - - DmaapRequestCounterMetricImpl obj =new DmaapRequestCounterMetricImpl("TEST",MetricType.COUNTER,7,1); - String date = getCurrentDate(); - - obj.incrementPublishedMessage(); - obj.incrementRecievedMessage(); - Assert.assertEquals(2,Integer.parseInt(obj.getMetricsOutput().get("Total Published messages"))); - Assert.assertEquals(8,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); - Assert.assertEquals(date+"[8],[2]",obj.value()); - Assert.assertNotNull(obj.getLastModified()); - Assert.assertEquals("TEST",obj.name()); - Assert.assertEquals(MetricType.COUNTER,obj.type()); - obj.reset(); - Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Published messages"))); - Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); - - } - - @Test - public void testDispatchingFuntionMetricImpl() { - - DispatchingFuntionMetricImpl obj= new DispatchingFuntionMetricImpl("TEST",MetricType.COUNTER,7,1); - String date = getCurrentDate(); - - obj.incrementAcceptedRequest(); - obj.incrementRejectedRequest(); - Assert.assertEquals(10,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); - Assert.assertEquals(2,Integer.parseInt(obj.getMetricsOutput().get("Total Rejected messages"))); - Assert.assertEquals(date+"[8,2]@10",obj.value()); - Assert.assertNotNull(obj.getLastModified()); - Assert.assertEquals("TEST",obj.name()); - Assert.assertEquals(MetricType.COUNTER,obj.type()); - obj.reset(); - Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Received messages"))); - Assert.assertEquals(0,Integer.parseInt(obj.getMetricsOutput().get("Total Rejected messages"))); - - - } - - @Test - public void testDispatchingFunctionCounterBuilderImpl(){ - DispatchingFunctionCounterBuilderImpl obj=new DispatchingFunctionCounterBuilderImpl(); - String date = getCurrentDate(); - DispatchingFuntionMetric metric=obj.withName("TEST").withType(MetricType.COUNTER).withAcceptRequestValue(7).withRejectRequestValue(2).build(); - metric.incrementAcceptedRequest(); - metric.incrementRejectedRequest(); - Assert.assertEquals(date+"[8,3]@11",metric.value()); - } - - @Test - public void testDmaapRequestCounterBuilderImpl(){ - DmaapRequestCounterBuilderImpl obj=new DmaapRequestCounterBuilderImpl(); - DmaapRequestCounterMetric metric =obj.withName("TEST").withPublishedMessage(1).withRecievedMessage(21).withType(MetricType.COUNTER).build(); - metric.incrementPublishedMessage(); - metric.incrementRecievedMessage(); - Assert.assertEquals(2,Integer.parseInt(metric.getMetricsOutput().get("Total Published messages"))); - Assert.assertEquals(22,Integer.parseInt(metric.getMetricsOutput().get("Total Received messages"))); - } - - @Test - public void testPrimitiveCounterBuilderImpl(){ - PrimitiveCounterBuilderImpl obj=new PrimitiveCounterBuilderImpl(); - PrimitiveCounter counter=obj.withName("TEST").withType(MetricType.COUNTER).withValue(1).build(); - counter.increment(); - Assert.assertEquals(2, counter.value()); - counter.decrement(); - Assert.assertEquals(1, counter.value()); - } - - private String getCurrentDate() { - Calendar cal = Calendar.getInstance(); - cal.setTimeZone(TimeZone.getTimeZone("UTC")); - SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd"); - return dateFormat.format(cal.getTime()); - - } - -} diff --git a/appc-metric/appc-metric-bundle/src/test/resources/org/onap/appc/default.properties b/appc-metric/appc-metric-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..596705820 --- /dev/null +++ b/appc-metric/appc-metric-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,29 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +#org.onap.appc.bootstrap.file=executor-test.properties +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + diff --git a/appc-metric/appc-metric-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-metric/appc-metric-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 596705820..000000000 --- a/appc-metric/appc-metric-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,29 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -#org.onap.appc.bootstrap.file=executor-test.properties -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/AppcOam.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/AppcOam.java new file mode 100644 index 000000000..97938339c --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/AppcOam.java @@ -0,0 +1,339 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.util.concurrent.Futures; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcOamService; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.Metrics; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.MetricsBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValues; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValuesBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.opendaylight.yangtools.yang.common.RpcError; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.oam.processor.OamMmodeProcessor; +import org.onap.appc.oam.processor.OamRestartProcessor; +import org.onap.appc.oam.processor.OamStartProcessor; +import org.onap.appc.oam.processor.OamStopProcessor; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader.AppcOperation; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Future; + +/** + * RPC class of APP-C OAM API. + *

Implement all the RPCs defined in AppcOamService through yang model definition. + *

All RPC methods' JAVADOC are using "inheritDoc" to use the description from the yang model file. + */ +public class AppcOam implements AutoCloseable, AppcOamService { + /** + * Invalid state message format with fliexible operation, appc name and state values + */ + public final static String INVALID_STATE_MESSAGE_FORMAT = "%s API is not allowed when %s is in the %s state."; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcOam.class); + + private boolean isMetricEnabled = false; + + /** + * Represents our RPC implementation registration + */ + private BindingAwareBroker.RpcRegistration rpcRegistration; + + + /** + * The yang rpc names with value mapping to AppcOperation + */ + public enum RPC { + maintenance_mode(AppcOperation.MaintenanceMode), + start(AppcOperation.Start), + stop(AppcOperation.Stop), + restart(AppcOperation.Restart); + + AppcOperation appcOperation; + + RPC(AppcOperation appcOperation) { + this.appcOperation = appcOperation; + } + + public AppcOperation getAppcOperation() { + return appcOperation; + } + } + + private AsyncTaskHelper asyncTaskHelper; + private ConfigurationHelper configurationHelper; + private OperationHelper operationHelper; + private StateHelper stateHelper; + + /** + * APP-C OAM contructor + * + * @param dataBroker object of The ODL data store broker. Provides access to a conceptual data + * tree store + * and also provides the ability to subscribe for changes to data under a + * given branch + * of the tree. Not used in this class. + * @param notificationProviderService object of ODL Notification Service that provides publish/subscribe + * capabilities for YANG modeled notifications. Not used in this class. + * @param rpcProviderRegistry object of RpcProviderResigstry. Used to register our RPCs. + */ + @SuppressWarnings({"unused", "nls"}) + public AppcOam(DataBroker dataBroker, + NotificationProviderService notificationProviderService, + RpcProviderRegistry rpcProviderRegistry) { + + configurationHelper = new ConfigurationHelper(logger); + String appName = configurationHelper.getAppcName(); + logger.info(Msg.COMPONENT_INITIALIZING, appName, "oam"); + + if (rpcProviderRegistry != null) { + rpcRegistration = rpcProviderRegistry.addRpcImplementation(AppcOamService.class, this); + } + + isMetricEnabled = configurationHelper.isMetricEnabled(); + + initHelpers(); + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "oam"); + } + + /** + * Initialize helper classes. + *

Note: ConfigurationHelper initializetion is in included here + * because it is needed for extracting the AppName used in the debug logs within the constructor. + */ + private void initHelpers() { + operationHelper = new OperationHelper(); + asyncTaskHelper = new AsyncTaskHelper(logger); + stateHelper = new StateHelper(logger, configurationHelper); + } + + /** + * Implements the close of the service + * + * @see AutoCloseable#close() + */ + @SuppressWarnings("nls") + @Override + public void close() throws Exception { + String appName = configurationHelper.getAppcName(); + logger.info(Msg.COMPONENT_TERMINATING, appName, "oam"); + + asyncTaskHelper.close(); + + if (rpcRegistration != null) { + rpcRegistration.close(); + } + logger.info(Msg.COMPONENT_TERMINATED, appName, "oam"); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> getMetrics() { + + if (!isMetricEnabled) { + logger.error("Metric Service not enabled returning failure"); + RpcResult result = RpcResultBuilder. + status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not enabled").build(); + return Futures.immediateFuture(result); + } + + MetricService metricService; + try { + metricService = operationHelper.getService(MetricService.class); + } catch (APPCException e) { + logger.error("MetricService not found", e); + RpcResult result = RpcResultBuilder. + status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not found").build(); + return Futures.immediateFuture(result); + } + + Map allMetricRegitry = metricService.getAllRegistry(); + if (allMetricRegitry == null || allMetricRegitry.isEmpty()) { + logger.error("No metrics registered returning failure"); + RpcResult result = RpcResultBuilder. + status(false).withError(RpcError.ErrorType.APPLICATION, "No metrics Registered").build(); + return Futures.immediateFuture(result); + } + + List metricsList = new ArrayList<>(); + + logger.debug("Iterating metric registry list"); + for (MetricRegistry metricRegistry : allMetricRegitry.values()) { + logger.debug("Iterating metric registry :" + metricRegistry.toString()); + Metric[] metrics = metricRegistry.metrics(); + if (metrics != null && metrics.length > 0) { + logger.debug("Iterating though metrics in registry"); + for (Metric metric : metrics) { + logger.debug("Iterating though metrics: " + metric.name()); + MetricsBuilder metricsBuilder = new MetricsBuilder(); + metricsBuilder.setKpiName(metric.name()); + metricsBuilder.setLastResetTime(metric.getLastModified()); + List kpiList = new ArrayList<>(); + Map metricsOutput = metric.getMetricsOutput(); + for (Map.Entry kpi : metricsOutput.entrySet()) { + KpiValuesBuilder kpiValuesBuilder = new KpiValuesBuilder(); + kpiValuesBuilder.setName(kpi.getKey()); + kpiValuesBuilder.setValue(kpi.getValue()); + kpiList.add(kpiValuesBuilder.build()); + } + metricsBuilder.setKpiValues(kpiList); + metricsList.add(metricsBuilder.build()); + } + } + } + + GetMetricsOutputBuilder outputBuilder = new GetMetricsOutputBuilder(); + outputBuilder.setMetrics(metricsList); + RpcResult result = RpcResultBuilder. + status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> stop(StopInput stopInput) { + logger.debug("Entering Stop with Input : " + stopInput); + final CommonHeader commonHeader = stopInput.getCommonHeader(); + + OamStopProcessor oamStopProcessor = + new OamStopProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + Status status = oamStopProcessor.processRequest(stopInput); + + StopOutputBuilder stopOutputBuilder = new StopOutputBuilder(); + stopOutputBuilder.setStatus(status); + stopOutputBuilder.setCommonHeader(commonHeader); + return RpcResultBuilder.success(stopOutputBuilder.build()).buildFuture(); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> restart(RestartInput input) { + logger.debug("Entering restart with Input : " + input); + final CommonHeader commonHeader = input.getCommonHeader(); + + OamRestartProcessor oamRestartProcessor = + new OamRestartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + Status status = oamRestartProcessor.processRequest(input); + + RestartOutputBuilder restartOutputBuilder = new RestartOutputBuilder(); + restartOutputBuilder.setStatus(status); + restartOutputBuilder.setCommonHeader(commonHeader); + + return RpcResultBuilder.success(restartOutputBuilder.build()).buildFuture(); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> maintenanceMode(MaintenanceModeInput maintenanceModeInput) { + logger.debug("Entering MaintenanceMode with Input : " + maintenanceModeInput); + final CommonHeader commonHeader = maintenanceModeInput.getCommonHeader(); + + OamMmodeProcessor oamMmodeProcessor = + new OamMmodeProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + Status status = oamMmodeProcessor.processRequest(maintenanceModeInput); + + MaintenanceModeOutputBuilder maintenanceModeOutputBuilder = new MaintenanceModeOutputBuilder(); + maintenanceModeOutputBuilder.setStatus(status); + maintenanceModeOutputBuilder.setCommonHeader(commonHeader); + return RpcResultBuilder.success(maintenanceModeOutputBuilder.build()).buildFuture(); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> getAppcState() { + AppcState appcState = stateHelper.getCurrentOamYangState(); + + GetAppcStateOutputBuilder builder = new GetAppcStateOutputBuilder(); + builder.setState(appcState); + return RpcResultBuilder.success(builder.build()).buildFuture(); + } + + /** + * {@inheritDoc} + */ + @Override + public Future> start(StartInput startInput) { + logger.debug("Input received : " + startInput); + final CommonHeader commonHeader = startInput.getCommonHeader(); + + OamStartProcessor oamStartProcessor = + new OamStartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + Status status = oamStartProcessor.processRequest(startInput); + + StartOutputBuilder startOutputBuilder = new StartOutputBuilder(); + startOutputBuilder.setStatus(status); + startOutputBuilder.setCommonHeader(commonHeader); + StartOutput startOutput = startOutputBuilder.build(); + return RpcResultBuilder.success(startOutput).buildFuture(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/OAMCommandStatus.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/OAMCommandStatus.java new file mode 100644 index 000000000..294b9d2cf --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/OAMCommandStatus.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam; + +import org.onap.appc.executor.objects.Params; +import org.onap.appc.util.MessageFormatter; + +import java.util.Map; + +public enum OAMCommandStatus { + + ACCEPTED(100, "ACCEPTED - request accepted"), + UNEXPECTED_ERROR(200, "UNEXPECTED ERROR - ${errorMsg}"), + REJECTED(300, "REJECTED - ${errorMsg}"), + INVALID_PARAMETER(302, "INVALID PARAMETER - ${errorMsg}" ), + TIMEOUT(303, "OPERATION TIMEOUT REACHED - ${errorMsg}"), + ABORT(304, "OPERATION ABORT - ${errorMsg}"), + SUCCESS(400, "SUCCESS - request has been processed successfully"); + + final String TO_STRING_FORMAT = "OAMCommandStatus{responseCode=%d, responseMessage='%s'}"; + + private int responseCode; + private String responseMessage; + + OAMCommandStatus(int responseCode, String responseMessage) { + this.responseCode = responseCode; + this.responseMessage = responseMessage; + } + + public String getResponseMessage() { + return responseMessage; + } + + public int getResponseCode() { + return responseCode; + } + + /** + * Get formated message of passed in params + * + * @param params of Params object with name value pairs for message + * @return message string + */ + public String getFormattedMessage(Params params) { + Map paramsMap = params != null ? params.getParams() : null; + return MessageFormatter.format(getResponseMessage(), paramsMap); + } + + @Override + public String toString() { + return String.format(TO_STRING_FORMAT, responseCode, responseMessage); + }} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/Converter.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/Converter.java new file mode 100644 index 000000000..152ffc9cc --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/Converter.java @@ -0,0 +1,156 @@ +/*-/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.messageadapter; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataContainer; +import org.onap.appc.oam.AppcOam; + +import java.text.SimpleDateFormat; +import java.util.TimeZone; + +public class Converter { + private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); + + static { + isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + + private static Builder convAsyncResponseToBuilder1(AppcOam.RPC rpcName, + CommonHeader commonHeader, + Status status) { + Builder outObj; + if (rpcName == null) { + throw new IllegalArgumentException("empty asyncResponse.rpcName"); + } + if (commonHeader == null) { + throw new IllegalArgumentException("empty asyncResponse.commonHeader"); + } + if (status == null) { + throw new IllegalArgumentException("empty asyncResponse.status"); + } + switch (rpcName) { + case maintenance_mode: + outObj = new MaintenanceModeOutputBuilder(); + ((MaintenanceModeOutputBuilder) outObj).setCommonHeader(commonHeader); + ((MaintenanceModeOutputBuilder) outObj).setStatus(status); + return outObj; + + case start: + outObj = new StartOutputBuilder(); + ((StartOutputBuilder) outObj).setCommonHeader(commonHeader); + ((StartOutputBuilder) outObj).setStatus(status); + return outObj; + + case stop: + outObj = new StopOutputBuilder(); + ((StopOutputBuilder) outObj).setCommonHeader(commonHeader); + ((StopOutputBuilder) outObj).setStatus(status); + return outObj; + + case restart: + outObj = new RestartOutputBuilder(); + ((RestartOutputBuilder) outObj).setCommonHeader(commonHeader); + ((RestartOutputBuilder) outObj).setStatus(status); + return outObj; + + default: + throw new IllegalArgumentException(rpcName + " action is not supported"); + } + } + + static String convAsyncResponseToUebOutgoingMessageJsonString(OAMContext oamContext) throws + JsonProcessingException { + AppcOam.RPC rpcName = oamContext.getRpcName(); + CommonHeader commonHeader = oamContext.getCommonHeader(); + Status status = oamContext.getStatus(); + + DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToUebOutgoingMessage(rpcName, commonHeader, + status); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), + MixInFlagsMessage.class); + objectMapper.addMixInAnnotations(Status.class, MixIn.class); + objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure + (MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true).writer(); + return writer.writeValueAsString(dmaapOutgoingMessage); + } + + private static DmaapOutgoingMessage convAsyncResponseToUebOutgoingMessage(AppcOam.RPC rpcName, CommonHeader + commonHeader, Status status) throws JsonProcessingException { + DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); + String correlationID = commonHeader.getRequestId(); + outObj.setCorrelationID(correlationID); + outObj.setType("response"); + outObj.setRpcName(rpcName.name()); + Builder builder = Converter.convAsyncResponseToBuilder1(rpcName, commonHeader, status); + Object messageBody = builder.build(); + + DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); + outObj.setBody(body); + return outObj; + } + + + abstract class MixIn { + // to be removed during serialization + @JsonIgnore + abstract Class getImplementedInterface(); + + @JsonValue + abstract java.lang.String getValue(); + } + + abstract class MixInCommonHeader extends MixIn { + @JsonProperty("request-id") + abstract java.lang.String getRequestId(); + + @JsonProperty("originator-id") + abstract java.lang.String getOriginatorId(); + + } + + abstract class MixInFlagsMessage extends MixIn { + @JsonProperty("common-header") + abstract CommonHeader getCommonHeader(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/DmaapOutgoingMessage.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/DmaapOutgoingMessage.java new file mode 100644 index 000000000..25bf0cf8b --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/DmaapOutgoingMessage.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.messageadapter; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * This class represents a message being sent out to DMaaP by APPC as async response. + * note the structure of this class must be adapted to the sync message sent to DMaaP represented in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapOutgoingMessage { + + @JsonProperty("type") + private String type; + + @JsonProperty("correlation-id") + private String correlationID; + + private final static String defaultCambriaPartition = "MSO"; + @JsonProperty("cambria.partition") + private String cambriaPartition = defaultCambriaPartition; + + @JsonProperty("rpc-name") + private String rpcName; + + @JsonProperty("body") + private Body body; + + public DmaapOutgoingMessage() { + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCorrelationID() { + return correlationID; + } + + public void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + public String getCambriaPartition() { + return cambriaPartition; + } + + public void setCambriaPartition(String cambriaPartition) { + this.cambriaPartition = cambriaPartition; + } + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public Body getBody() { + return body; + } + + public void setBody(Body body) { + this.body = body; + } + + @Override + public String toString() { + return "DmaapOutgoingMessage{" + + "cambriaPartition='" + cambriaPartition + '\'' + + ", rpcName='" + rpcName + '\'' + + ", body=" + body + + '}'; + } + + @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Body { + public Body() { + } + + public Body(Object output) { + this.output = output; + } + + @JsonProperty("output") + private Object output; + + public Object getOutput() { + return output; + } + + public void setOutput(Object body) { + this.output = body; + } + + @Override + public String toString() { + return "Body{" + + "output=" + output + + '}'; + } + } +} + diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/MessageAdapter.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/MessageAdapter.java new file mode 100644 index 000000000..91836cb40 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/MessageAdapter.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.messageadapter; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashSet; +import java.util.Properties; + +public class MessageAdapter { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapter.class); + + private final String PROP_APPC_OAM_DISABLED = "appc.OAM.disabled"; + private final String PROP_APPC_OAM_TOPIC_WRITE = "appc.OAM.topic.write"; + private String PROP_APPC_OAM_CLIENT_KEY = "appc.OAM.client.key"; + private String PROP_APPC_OAM_CLIENT_SECRET = "appc.OAM.client.secret"; + private String PROP_APPC_OAM_POOLMEMBERS = "appc.OAM.poolMembers"; + + private Producer producer; + private String partition; + private Configuration configuration; + private HashSet pool; + private String writeTopic; + private String apiKey; + private String apiSecret; + private boolean isDisabled; + + /** + * Initialize producer client to post messages using configuration properties. + */ + public void init() { + configuration = ConfigurationFactory.getConfiguration(); + Properties properties = configuration.getProperties(); + updateProperties(properties); + + if (isAppcOamPropsListenerEnabled()) { + createProducer(); + } else { + logger.warn(String.format("The listener %s is disabled and will not be run", "appc.OAM")); + } + } + + /** + * Create producer using MessageAdapterFactory which is found through bundle context. + */ + void createProducer() { + BundleContext ctx = FrameworkUtil.getBundle(MessageAdapter.class).getBundleContext(); + if (ctx == null) { + logger.warn("MessageAdapter cannot create producer due to no bundle context."); + return; + } + + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef == null) { + logger.warn("MessageAdapter cannot create producer due to no MessageAdapterFactory service reference."); + return; + } + + Producer localProducer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic, + apiKey, apiSecret); + + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + localProducer.useHttps(true); + break; + } + } + + producer = localProducer; + + logger.debug("MessageAdapter created producer."); + } + + /** + * Read property value to set writeTopic, apiKey, apiSecret and pool. + * + * @param props of configuration + */ + private void updateProperties(Properties props) { + logger.trace("Entering to updateProperties with Properties = " + ObjectUtils.toString(props)); + + pool = new HashSet<>(); + if (props != null) { + isDisabled = Boolean.parseBoolean(props.getProperty(PROP_APPC_OAM_DISABLED)); + writeTopic = props.getProperty(PROP_APPC_OAM_TOPIC_WRITE); + apiKey = props.getProperty(PROP_APPC_OAM_CLIENT_KEY); + apiSecret = props.getProperty(PROP_APPC_OAM_CLIENT_SECRET); + String hostnames = props.getProperty(PROP_APPC_OAM_POOLMEMBERS); + if (hostnames != null && !hostnames.isEmpty()) { + for (String name : hostnames.split(",")) { + pool.add(name); + } + } + } + } + + /** + * Get producer. If it is null, call createProducer to create it again. + * + * @return Producer + */ + Producer getProducer() { + if (producer == null) { + // In case, producer was not properly set yet, set it again. + logger.info("Calling createProducer as producer is null."); + createProducer(); + } + + return producer; + } + + /** + * Posts message to UEB. As UEB accepts only json messages this method first convert uebMessage to json format + * and post it to UEB. + * + * @param oamContext response data that based on it a message will be send to UEB (the format of the message that + * will be sent to UEB based on the action and its YANG domainmodel). + */ + public void post(OAMContext oamContext) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(oamContext)); + } + + boolean success; + String jsonMessage; + try { + jsonMessage = Converter.convAsyncResponseToUebOutgoingMessageJsonString(oamContext); + if (logger.isDebugEnabled()) { + logger.debug("UEB Response = " + jsonMessage); + } + + Producer myProducer = getProducer(); + success = myProducer != null && myProducer.post(this.partition, jsonMessage); + } catch (JsonProcessingException e1) { + logger.error("Error generating Json from UEB message " + e1.getMessage()); + success = false; + } catch (Exception e) { + logger.error("Error sending message to UEB " + e.getMessage(), e); + success = false; + } + + if (logger.isTraceEnabled()) { + logger.trace("Exiting from post with (success = " + ObjectUtils.toString(success) + ")"); + } + } + + private boolean isAppcOamPropsListenerEnabled() { + return !isDisabled; + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/OAMContext.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/OAMContext.java new file mode 100644 index 000000000..3af395923 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/messageadapter/OAMContext.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.messageadapter; + + + + +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.*; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeaderBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status;import org.onap.appc.oam.AppcOam; + +public class OAMContext { + + private AppcOam.RPC rpcName; + private CommonHeader commonHeader; + private Status status; + + + public AppcOam.RPC getRpcName() { + return rpcName; + } + + public void setRpcName(AppcOam.RPC rpcName) { + this.rpcName = rpcName; + } + + public CommonHeader getCommonHeader() { + return commonHeader; + } + + public void setCommonHeader(CommonHeader commonHeader) { + this.commonHeader = commonHeader; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + + @Override + public String toString() { + return "OAMContext {" + + "rpcName=" + rpcName + + ", commonHeader=" + commonHeader + + ", status=" + status + + '}'; + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseActionRunnable.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseActionRunnable.java new file mode 100644 index 000000000..927334670 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseActionRunnable.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Future; + +/** + * Base runnable actions for OAM APIs, such as maintenance mode, restart, start and stop API. + * + *

This class holds the general action async handling methods for all OAM APIs. + *

Specific API action runnable will overwrite the general methods to add specific behaviors. + * + *

Subclass constructor must set the following class variables: + *
- actionName + *
- auditMsg + *
- finalState + */ +public abstract class BaseActionRunnable extends BaseCommon implements Runnable { + /** Abort due to rejection message format with flexible operation name */ + final String ABORT_MESSAGE_FORMAT = "Aborting %s operation due to %s."; + /** Timeout message format with flexible operation name */ + final String TIMEOUT_MESSAGE_FORMAT = "%s operation has reached timeout %d milliseconds."; + /** Failure message format with flexible number of bundles */ + final String BUNDLE_OPERATION_FAILED_FORMAT = "%d bundle(s) failed, see logs for details."; + final String NEW_RPC_OPERATION_REQUEST = "new %s operation request"; + final String DUE_TO_EXECUTION_ERROR = "due to execution error."; + + private boolean isWaiting = false; + long startTimeMs = 0; + long timeoutMs = 0; + boolean doTimeoutChecking = false; + + String actionName = "Need to be reset"; + Msg auditMsg; + AppcOamStates finalState; + + BaseProcessor myParent; + Map> bundleNameToFuture = new HashMap<>(); + + /** + * Constructor + * + * @param parent BaseProcessor who has called this constructor. + */ + BaseActionRunnable(BaseProcessor parent) { + super(parent.logger, parent.configurationHelper, parent.stateHelper, parent.operationHelper); + + rpc = parent.rpc; + commonHeader = parent.commonHeader; + myParent = parent; + setTimeoutValues(); + } + + /** + * Collect the timeout value for this {@link BaseActionRunnable} + */ + void setTimeoutValues() { + startTime = myParent.startTime; + timeoutMs = myParent.getTimeoutMilliseconds(); + doTimeoutChecking = timeoutMs != 0; + if (doTimeoutChecking) { + startTimeMs = startTime.getTime(); + } + logDebug("%s action runnable check timeout (%s) with timeout (%d)ms, and startMs (%d)", + rpc.name(), Boolean.toString(doTimeoutChecking), timeoutMs, startTimeMs); + } + + + /** + * Abort operation handling due to outside interruption, does
+ * - set ABORT status
+ * - send notification message
+ * - add audit log + * + * @param newRpc of the new AppcOam.RPC operation. + */ + void abortRunnable(final AppcOam.RPC newRpc) { + resetLogProperties(false); + + String additionalMsg = String.format(NEW_RPC_OPERATION_REQUEST, newRpc); + logDebug("%s action aborted due to %s", rpc.name(), additionalMsg); + setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), additionalMsg)); + operationHelper.sendNotificationMessage(rpc, commonHeader, status); + auditInfoLog(auditMsg); + + resetLogProperties(true); + } + + @Override + public void run() { + try { + setInitialLogProperties(); + logDebug(String.format("===========in %s run (waiting: %s)=======", + actionName, Boolean.toString(isWaiting))); + + if (isWaiting) { + if (!checkState()) { + keepWaiting(); + } + } else { + if (doAction()) { + isWaiting = !checkState(); + } else { + postDoAction(false); + } + } + } catch (Exception e) { + logDebug(String.format("%s got exception %s", actionName, e.getMessage())); + logger.error(actionName + " exception", e); + + } finally { + clearRequestLogProperties(); + } + } + + /** + * Keep waiting to be override by children classes for different behaviors. + * Timeout is validated here. + */ + void keepWaiting() { + logDebug(String.format("%s runnable waiting, current state is %s.", + actionName, stateHelper.getCurrentOamState())); + + isTimeout("keepWaiting"); + } + + /** + * Check if the timeout milliseconds has reached. + * + * @param parentName String of the caller, for logging purpose. + * @return true if the timeout has reached, otherwise false. + */ + boolean isTimeout(String parentName) { + logDebug(String.format("%s task isTimeout called from %s", actionName, parentName)); + if (doTimeoutChecking + && System.currentTimeMillis() - startTimeMs > timeoutMs) { + logger.error(String.format("%s operation timeout (%d) ms has reached, abort with error state.", + actionName, timeoutMs)); + + setStatus(OAMCommandStatus.TIMEOUT, String.format(TIMEOUT_MESSAGE_FORMAT, rpc.name(), timeoutMs)); + postAction(AppcOamStates.Error); + return true; + } + return false; + } + + /** + * Check if all bundle operations are successful through BundleHelper. + * If there's failed bundler operation, set error status and trigger postAction with Error state. + * + * @return true if bundler operations have failure, otherwise false. + */ + boolean hasBundleOperationFailure() { + long failedTask = myParent.bundleHelper.getFailedMetrics(bundleNameToFuture); + if (failedTask == 0) { + return false; + } + + setStatus(OAMCommandStatus.UNEXPECTED_ERROR, String.format(BUNDLE_OPERATION_FAILED_FORMAT, failedTask)); + postAction(AppcOamStates.Error); + return true; + } + + /** + * Set class status to ABORT with abort message. + */ + void setAbortStatus() { + setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), DUE_TO_EXECUTION_ERROR)); + } + + /** + * Final handling. The thread is cancelled. + * + * @param setState boolean to indicate if set OAM state or not + */ + void postDoAction(boolean setState) { + logDebug(String.format("Finished %s task", actionName)); + } + + /** + * Handling for after doAction. does post notification, issue audit log and set OAM state based on input. + * + * @param state of AppcOamState to be set as OAM state when it is not null. + */ + void postAction(AppcOamStates state) { + operationHelper.sendNotificationMessage(rpc, commonHeader, status); + + if (state != null) { + stateHelper.setState(state); + } + + auditInfoLog(auditMsg); + + myParent.cancelAsyncTask(); + } + + /** + * Check state + * + * @return true if final state reached, otherwise return false + */ + boolean checkState() { + if (isTimeout("checkState")) { + myParent.bundleHelper.cancelUnfinished(bundleNameToFuture); + return true; + } + + if (!myParent.bundleHelper.isAllTaskDone(bundleNameToFuture)) { + return false; + } + + if (hasBundleOperationFailure()) { + return true; + } + + if (stateHelper.getBundlesState() == finalState) { + setStatus(OAMCommandStatus.SUCCESS); + postDoAction(true); + return true; + } + return false; + } + + abstract boolean doAction(); +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseCommon.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseCommon.java new file mode 100644 index 000000000..93e79dd2f --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseCommon.java @@ -0,0 +1,265 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.i18n.EELFResourceManager; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.StatusBuilder; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.i18n.Msg; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.time.Instant; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeoutException; + +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +/** + * Common handling methods of
+ * - BaseProcessor (for REST sync handling)
+ * - BaseActionRunnable (for REST async handling) + */ +public abstract class BaseCommon { + final EELFLogger logger; + final ConfigurationHelper configurationHelper; + final StateHelper stateHelper; + final OperationHelper operationHelper; + + Status status; + Date startTime; + + AppcOam.RPC rpc; + CommonHeader commonHeader; + + private final List MDC_KEYS = Arrays.asList( + LoggingConstants.MDCKeys.PARTNER_NAME, + LoggingConstants.MDCKeys.SERVER_NAME, + MDC_INSTANCE_UUID, + MDC_KEY_REQUEST_ID, + MDC_SERVER_FQDN, + MDC_SERVER_IP_ADDRESS, + MDC_SERVICE_NAME + ); + private Map oldMdcContent = new HashMap<>(); + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param operationHelperIn for operational helper + */ + BaseCommon(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + OperationHelper operationHelperIn) { + logger = eelfLogger; + configurationHelper = configurationHelperIn; + stateHelper = stateHelperIn; + operationHelper = operationHelperIn; + } + + /** + * Audit log the passed in message at INFO level. + * @param msg the Msg to be audit logged. + */ + void auditInfoLog(Msg msg) { + LoggingUtils.auditInfo(startTime.toInstant(), + Instant.now(), + String.valueOf(status.getCode()), + status.getMessage(), + getClass().getCanonicalName(), + msg, + configurationHelper.getAppcName(), + stateHelper.getCurrentOamState().toString() + ); + } + + /** + * Set MDC properties. + */ + public final void setInitialLogProperties() { + MDC.put(MDC_KEY_REQUEST_ID, commonHeader.getRequestId()); + MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, commonHeader.getOriginatorId()); + MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future + MDC.put(MDC_SERVICE_NAME, rpc.name()); + try { + //!!!Don't change the following to a .getHostName() again please. It's wrong!MDC.put(MDC_SERVER_FQDN, + // InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); + } catch (Exception e) { + logger.error("MDC constant error", e); + } + } + + /** + * Clear MDC properties. + */ + public final void clearRequestLogProperties() { + for (String key : MDC_KEYS) { + try { + MDC.remove(key); + } catch (Exception e) { + logger.error( + String.format("Unable to clear the Log properties (%s) due to exception: %s", key, e.getMessage())); + } + } + } + + /** + * Reset MDC log properties based on passed in condition. does:
+ * - persist existing MDC setting and set my MDC log properties
+ * - or re-apply persisted MDC log properties + * @param useMdcMap boolean to indicate whether to persist the existing MDC setting and set my MDC log properties, + * or to re-apply the persisted MDC log properties. + */ + void resetLogProperties(boolean useMdcMap) { + if (useMdcMap) { + for (Map.Entry aEntry : oldMdcContent.entrySet()) { + MDC.put(aEntry.getKey(), aEntry.getValue()); + } + return; + } + + // persist existing log properties and set my log properties + oldMdcContent.clear(); + for (String key : MDC_KEYS) { + String value = MDC.get(key); + if (value != null) { + oldMdcContent.put(key, value); + } + } + setInitialLogProperties(); + } + + /** + * Set class status by calling setStatus(OAMCommandStatus, Params) with null paramter. + * @see #setStatus(OAMCommandStatus, String) + * + * @param oamCommandStatus of the to be set new state + */ + void setStatus(OAMCommandStatus oamCommandStatus) { + setStatus(oamCommandStatus, null); + } + + /** + * Create Status based on the passed in parameter, then set the class status with it. + * + * @param oamCommandStatus of the current OAM command status + * @param message to be set in the new status + */ + void setStatus(OAMCommandStatus oamCommandStatus, String message) { + Params params = new Params().addParam("errorMsg", message); + + StatusBuilder statusBuilder = new StatusBuilder(); + statusBuilder.setCode(oamCommandStatus.getResponseCode()); + if (params != null) { + statusBuilder.setMessage(oamCommandStatus.getFormattedMessage(params)); + } else { + statusBuilder.setMessage(oamCommandStatus.getResponseMessage()); + } + + status = statusBuilder.build(); + } + + /** + * Set class status with error status calculated from the passed in paremeter + * and audit log the error message. + * @param t of the error Throwable. + */ + void setErrorStatus(Throwable t) { + resetLogProperties(false); + + final String appName = configurationHelper.getAppcName(); + String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString(); + + OAMCommandStatus oamCommandStatus; + String errorMessage; + if (t instanceof InvalidInputException) { + oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER; + errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_INVALID_INPUT, t.getMessage()); + } else if (t instanceof InvalidStateException) { + exceptionMessage = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, + rpc.getAppcOperation(), appName, stateHelper.getCurrentOamState()); + oamCommandStatus = OAMCommandStatus.REJECTED; + errorMessage = EELFResourceManager.format(Msg.INVALID_STATE_TRANSITION, exceptionMessage); + } else if (t instanceof TimeoutException) { + oamCommandStatus = OAMCommandStatus.TIMEOUT; + errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t, + appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage); + } else { + oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; + errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t, + appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage); + } + + setStatus(oamCommandStatus, exceptionMessage); + + LoggingUtils.logErrorMessage( + String.valueOf(status.getCode()), + status.getMessage(), + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.APPC_OAM_PROVIDER, + errorMessage, + AppcOam.class.getCanonicalName()); + + resetLogProperties(true); + } + + /** + * Genral debug log when debug logging level is enabled. + * @param message of the log message format + * @param args of the objects listed in the message format + */ + void logDebug(String message, Object... args) { + if (logger.isDebugEnabled()) { + logger.debug(String.format(message, args)); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseProcessor.java new file mode 100644 index 000000000..414b94605 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/BaseProcessor.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.BundleHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +import java.util.Date; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Base processor for OAM APIs, such as maintenance mode, restart, start and stop API. + * + *

This class holds the general API request sync handling methods for all OAM APIs. + *

Specific API processor will overwrite the general methods to add specific behaviors. + */ +public abstract class BaseProcessor extends BaseCommon { + /** lock to serialize incoming OAM operations. */ + private static final Object LOCK = new Object(); + + final AsyncTaskHelper asyncTaskHelper; + final BundleHelper bundleHelper; + + /** the requestTimeoutSeconds to use for this OAM operation */ + private Integer requestTimeoutSeconds; + Msg auditMsg; + BaseActionRunnable runnable; + private Future scheduledRunnable = null; + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param asyncTaskHelperIn for scheduling async task + * @param operationHelperIn for operational helper + */ + BaseProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + AsyncTaskHelper asyncTaskHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, operationHelperIn); + + asyncTaskHelper = asyncTaskHelperIn; + bundleHelper = new BundleHelper(eelfLogger, configurationHelper, stateHelper); + } + + /** + * Process synch handling and schedule asynch task + * + * @param requestInput of REST API request + * @return Status of new APP-C OAM state + */ + public Status processRequest(final Object requestInput) { + startTime = new Date(); + commonHeader = operationHelper.getCommonHeader(requestInput); + setStatus(OAMCommandStatus.ACCEPTED); + + try { + preProcess(requestInput); + scheduleAsyncTask(); + } catch (Exception e) { + setErrorStatus(e); + } finally { + postProcess(); + } + + return status; + } + + /** + * Preprocess before actual handling of the REST API call. Does: + *

- commonHeader validation + *

- get NextState as well as validate if next state is valid + *

- set logging properties + *

- set appcCurrentState to next state + * + * @throws InvalidInputException when commonHeader validation failed + * @throws APPCException when state validation failed + */ + protected void preProcess(final Object requestInput) + throws InvalidInputException, APPCException, InvalidStateException,InterruptedException,TimeoutException { + setInitialLogProperties(); + operationHelper.isInputValid(requestInput); + + //The OAM request may specify timeout value + requestTimeoutSeconds = operationHelper.getParamRequestTimeout(requestInput); + + //All OAM operation pass through here first to validate if an OAM state change is allowed. + //If a state change is allowed cancel the occurring OAM (if any) before starting this one. + //we will synchronized so that only one can do this at any given time. + synchronized(LOCK) { + AppcOamStates currentOamState = stateHelper.getCurrentOamState(); + + //make sure this OAM operation can transition to the desired OAM operation + AppcOamStates nextState = operationHelper.getNextState( + rpc.getAppcOperation(), currentOamState); + + stateHelper.setState(nextState); + + + try { + //cancel the BaseActionRunnable currently executing + //it got to be completely terminated before proceeding + asyncTaskHelper.cancelBaseActionRunnable( + rpc, + currentOamState, + getTimeoutMilliseconds(), + TimeUnit.MILLISECONDS + ); + } catch (TimeoutException e) { + stateHelper.setState(AppcOamStates.Error); + throw e; + } + + + } + } + + /** + * Post process includes audit logging as well as clear MDC properties. + */ + private void postProcess() { + auditInfoLog(auditMsg); + clearRequestLogProperties(); + } + + /** + * Schedule async task through AsyncTaskHelper. + */ + protected void scheduleAsyncTask() { + if (runnable == null) { + logger.error(String.format( + "Skipped schedule async task for rpc(%s) due to runnable is null", rpc.name())); + return; + } + + scheduledRunnable = asyncTaskHelper.scheduleBaseRunnable( + runnable, runnable::abortRunnable, getInitialDelayMillis(), getDelayMillis()); + } + + + /** + * The timeout for this OAM operation. The timeout source is chosen in the following order: + * request, config file, default value + * @return - the timeout for this OAM operation. + */ + long getTimeoutMilliseconds() { + return configurationHelper.getOAMOperationTimeoutValue(this.requestTimeoutSeconds); + } + + + /** + * @return initialDelayMillis - the time to delay first execution of {@link BaseActionRunnable} + */ + protected long getInitialDelayMillis(){ + return 0L; + } + + /** + * @return delayMillis the delay between the consecutive executions of {@link BaseActionRunnable} + */ + private long getDelayMillis(){ + return 1000L; + } + + /** + * Cancel the scheduled {@link BaseActionRunnable} through AsyncTaskHelper + */ + void cancelAsyncTask() { + if (scheduledRunnable == null) { + logger.error(String.format( + "Skipped cancel schedule async task for rpc(%s) due to scheduledRunnable is null", rpc.name())); + return; + } + scheduledRunnable.cancel(true); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamMmodeProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamMmodeProcessor.java new file mode 100644 index 000000000..23f9fd130 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamMmodeProcessor.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +import java.util.concurrent.TimeoutException; + +/** + * Processor to handle maintenance mode OAM API. + */ +public class OamMmodeProcessor extends BaseProcessor { + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelper for property reading + * @param stateHelper for APP-C OAM state checking + * @param asyncTaskHelper for scheduling async task + * @param operationHelper for operational helper + */ + public OamMmodeProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelper, + StateHelper stateHelper, + AsyncTaskHelper asyncTaskHelper, + OperationHelper operationHelper) { + super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + + rpc = AppcOam.RPC.maintenance_mode; + auditMsg = Msg.OAM_OPERATION_ENTERING_MAINTENANCE_MODE; + } + + @Override + protected void preProcess(final Object requestInput) + throws InvalidInputException, InvalidStateException, APPCException, InterruptedException, TimeoutException { + super.preProcess(requestInput); + + //Close the gate so that no more new LCM request will be excepted. + LCMStateManager lcmStateManager = operationHelper.getService(LCMStateManager.class); + lcmStateManager.disableLCMOperations(); + } + + @Override + protected void scheduleAsyncTask() { + runnable = new MyRunnable(this); + super.scheduleAsyncTask(); + } + + /** + * {@inheritDoc} + * For maintenance mode we want a longer delay before initial execution of {@link BaseActionRunnable} + * so that any accepted LCM actions have time to git scheduled in the Dispatcher. + */ + @Override + protected long getInitialDelayMillis(){ + //wait ten seconds before + return 10000L; + } + + /** + * This runnable does the async handling for the maintenance mode REST API, and will be scheduled to run + * until terminating condition reaches. + * + *

The runnable will continue run if:
+ * - the runnable is not canceled outside
+ * - the in progress LCM request count is not zero
+ *

When LCM request count reaches to zero, this runnable will:
+ * - post message through operationHelper
+ * - set APP-C OAM state to maintenance mode
+ * - audit log the state
+ * - terminate this runnable itself
+ */ + class MyRunnable extends BaseActionRunnable { + private int inprogressRequestCount; + + MyRunnable(BaseProcessor parent) { + super(parent); + + actionName = "OAM Maintenance mode"; + auditMsg = Msg.OAM_OPERATION_MAINTENANCE_MODE; + finalState = AppcOamStates.MaintenanceMode; + } + + @Override + boolean doAction() { + // always return true, so that we can check the LCM request count + return true; + } + + @Override + boolean checkState() { + logDebug(String.format("Executing %s task", actionName)); + + + boolean hasError = false; + try { + inprogressRequestCount = getInprogressLCMRequestCount(); + if (inprogressRequestCount > 0) { + // if there are still LCM request in progress, keep waiting + return false; + } + + setStatus(OAMCommandStatus.SUCCESS); + } catch (Exception e) { + setErrorStatus(e); + hasError = true; + } + + postAction(hasError ? AppcOamStates.Error : finalState); + return true; + } + + /** + * Get in progress LCM request count through RequestHandler. + * @return thecount of in progress LCM request + * @throws APPCException if RequestHandler throws it. + */ + private int getInprogressLCMRequestCount() throws APPCException { + RequestHandler requestHandler = operationHelper.getService(RequestHandler.class); + + if (requestHandler == null) { + return 0; + } + + return requestHandler.getInprogressRequestCount(); + } + + @Override + void keepWaiting() { + logDebug("The application '%s' has '%s' outstanding LCM request to complete" + + " before coming to a complete maintenance_mode.", + configurationHelper.getAppcName(), inprogressRequestCount); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamRestartProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamRestartProcessor.java new file mode 100644 index 000000000..b23b4d2aa --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamRestartProcessor.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +/** + * Processor to handle restart OAM API. + */ +public class OamRestartProcessor extends BaseProcessor { + /** + * Action phases: + *
-ToStop: call bundles stop + *
-Stopped: check if all bundle state reached stopped + *
-ToStart: call bundles start + *
-Started: action is full completed + *
-Error: indication of error, such as timeout reached, bundler operation failure and etc. + */ + private enum ActionPhases { + ToStop, + Stopped, + ToStart, + Started, + Error + } + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelper for property reading + * @param stateHelper for APP-C OAM state checking + * @param asyncTaskHelper for scheduling async task + * @param operationHelper for operational helper + */ + public OamRestartProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelper, + StateHelper stateHelper, + AsyncTaskHelper asyncTaskHelper, + OperationHelper operationHelper) { + super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + + rpc = AppcOam.RPC.restart; + auditMsg = Msg.OAM_OPERATION_RESTARTING; + } + + @Override + protected void scheduleAsyncTask() { + runnable = new MyRunnable(this); + super.scheduleAsyncTask(); + } + + /** + * This runnable does the async handling for the restart REST API. And it will be scheduled to run one time. + * + *

This runnable will the following operations:
+ * - do APP-C OAM bundle stop and then start through BundlerHelper
+ * - and always enable LCM operation handling (which can be disabled through maintenance mode API).
+ *

Once above operations are done, the runnale will
+ * - post message through operatonHelper
+ * - set APP-C OAM state to started
+ * - audit log the state
+ */ + class MyRunnable extends BaseActionRunnable { + + ActionPhases currentPhase = ActionPhases.ToStop; + private LCMStateManager lcmStateManager; + + MyRunnable(BaseProcessor parent) { + super(parent); + + actionName = "OAM Restart"; + auditMsg = Msg.OAM_OPERATION_RESTARTED; + finalState = AppcOamStates.Started; + } + + /** + * Do restart action, include stop then start and always enable LCM operation. + * @return true if action is successful, false when aciton is failed or aborted + */ + @Override + boolean doAction() { + logDebug(String.format("Executing %s task at phase (%s)", + actionName, currentPhase == null ? "null" : currentPhase.name())); + + boolean isBundleOperationCompleted = true; + try { + switch (currentPhase) { + case ToStop: + isBundleOperationCompleted = bundleHelper.bundleOperations( + AppcOam.RPC.stop, bundleNameToFuture, myParent.asyncTaskHelper, this); + currentPhase = ActionPhases.Stopped; + break; + case Stopped: + // check state + AppcOamStates currentState = stateHelper.getBundlesState(); + if (currentState == AppcOamStates.Stopped) { + currentPhase = ActionPhases.ToStart; + } else { + logDebug(String.format("%s task is waiting in stopped phase, current state is %s", + actionName, currentState)); + } + break; + case ToStart: + isBundleOperationCompleted = bundleHelper.bundleOperations( + AppcOam.RPC.start, bundleNameToFuture, myParent.asyncTaskHelper, this); + currentPhase = ActionPhases.Started; + break; + case Error: + // do nothing + break; + default: + // Should not reach log it and return false; + logger.error("%s task doAction reached %s phase. not supported. return false.", + actionName, currentPhase.name()); + stateHelper.setState(AppcOamStates.Error); + return false; + } + + if (isTimeout("restart doAction") + || hasBundleOperationFailure()) { + currentPhase = ActionPhases.Error; + return true; + } + if (isBundleOperationCompleted) { + return true; + } + + setAbortStatus(); + } catch (APPCException e) { + setErrorStatus(e); + stateHelper.setState(AppcOamStates.Error); + } + + return false; + } + + /** + * With additional to get the LCMStateManager service + * @see BaseActionRunnable#checkState() + */ + @Override + boolean checkState() { + switch (currentPhase) { + case Started: + try { + lcmStateManager = operationHelper.getService(LCMStateManager.class); + return super.checkState(); + } catch (APPCException e) { + logDebug("LCMStateManager is not available."); + } + break; + default: + // in all the other ActionPhase, we want the run go back to doAction + return true; + } + return false; + } + + /** + * Final handling. The thread is cancelled. + * @param setState boolean to indicate if set OAM state or not + */ + @Override + void postDoAction(boolean setState) { + AppcOamStates newState = null; + if (setState) { + logDebug("Always enable LCM operation"); + lcmStateManager.enableLCMOperations(); + newState = finalState; + } + postAction(newState); + super.postDoAction(setState); + } + + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStartProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStartProcessor.java new file mode 100644 index 000000000..2ca353244 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStartProcessor.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +/** + * Processor to handle start OAM API. + */ +public class OamStartProcessor extends BaseProcessor { + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelper for property reading + * @param stateHelper for APP-C OAM state checking + * @param asyncTaskHelper for scheduling async task + * @param operationHelper for operational helper + */ + public OamStartProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelper, + StateHelper stateHelper, + AsyncTaskHelper asyncTaskHelper, + OperationHelper operationHelper) { + super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + + rpc = AppcOam.RPC.start; + auditMsg = Msg.OAM_OPERATION_STARTING; + } + + @Override + protected void scheduleAsyncTask() { + runnable = new MyRunnable(this); + super.scheduleAsyncTask(); + } + + /** + * This runnable does the async handling for the start REST API. And it will be scheduled to run one time. + * + *

This runnable will the following operations:
+ * - do APP-C OAM bundle start through BundlerHelper
+ * - and always enable LCM operation handling (which can be disabled through maintenance mode API).
+ *

Once above operations are done, the runnale will
+ * - post message through operatonHelper
+ * - set APP-C OAM state to started
+ * - audit log the state
+ */ + class MyRunnable extends BaseActionRunnable { + + private LCMStateManager lcmStateManager; + + MyRunnable(BaseProcessor parent) { + super(parent); + actionName = "OAM Start"; + auditMsg = Msg.OAM_OPERATION_STARTED; + finalState = AppcOamStates.Started; + } + + /** + * Do start action, include start bundle if needed and always enable LCM operation. + * @return true if action is successful, false when aciton is failed or aborted + */ + @Override + boolean doAction() { + logDebug(String.format("Executing %s task", actionName)); + + boolean isBundleOperationCompleted = true; + try { + if (stateHelper.getState() != AppcOamStates.Started) { + logDebug("Start - APPC OAM state is not started, start the bundles"); + isBundleOperationCompleted = bundleHelper.bundleOperations( + rpc, bundleNameToFuture, myParent.asyncTaskHelper, this); + } + + if (isBundleOperationCompleted) { + return true; + } + + setAbortStatus(); + } catch (APPCException e) { + setErrorStatus(e); + stateHelper.setState(AppcOamStates.Error); + } + + return false; + } + + /** + * With additional to get the LCMStateManager service + * @see BaseActionRunnable#checkState() + */ + @Override + boolean checkState() { + try { + lcmStateManager = operationHelper.getService(LCMStateManager.class); + return super.checkState(); + } catch (APPCException e) { + logDebug("LCMStateManager is not available."); + return false; + } + } + + /** + * Final handling + * @param setState boolean to indicate if set OAM state or not + */ + @Override + void postDoAction(boolean setState) { + AppcOamStates newState = null; + if (setState) { + logDebug("Always enable LCM operation"); + lcmStateManager.enableLCMOperations(); + newState = finalState; + } + postAction(newState); + super.postDoAction(setState); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStopProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStopProcessor.java new file mode 100644 index 000000000..8710e0f08 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/processor/OamStopProcessor.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; + +/** + * Processor to handle stop OAM API. + */ +public class OamStopProcessor extends BaseProcessor { + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelper for property reading + * @param stateHelper for APP-C OAM state checking + * @param asyncTaskHelper for scheduling async task + * @param operationHelper for operational helper + */ + public OamStopProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelper, + StateHelper stateHelper, + AsyncTaskHelper asyncTaskHelper, + OperationHelper operationHelper) { + super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); + + rpc = AppcOam.RPC.stop; + auditMsg = Msg.OAM_OPERATION_STOPPING; + } + + + @Override + protected void scheduleAsyncTask() { + runnable = new MyRunnable(this); + super.scheduleAsyncTask(); + } + + /** + * This runnable does the async handling for the stop REST API. And it will be scheduled to run one time. + * + *

This runnable will the following operations:
+ * - do APP-C OAM bundle stop and then refresh through BundlerHelper
+ *

Once above operations are done, the runnale will
+ * - post message through operatonHelper
+ * - set APP-C OAM state to started
+ * - audit log the state
+ */ + class MyRunnable extends BaseActionRunnable { + + MyRunnable(BaseProcessor parent) { + super(parent); + actionName = "OAM Stop"; + auditMsg = Msg.OAM_OPERATION_STOPPED; + finalState = AppcOamStates.Stopped; + } + + /** + * Do stop action, include stop bundle . + * @return true if action is successful, false when aciton is failed. + */ + @Override + boolean doAction() { + logDebug(String.format("Executing %s task", actionName)); + + try { + boolean isBundleOperationCompleted = bundleHelper.bundleOperations( + rpc, bundleNameToFuture, myParent.asyncTaskHelper, this); + if (isBundleOperationCompleted) { + return true; + } + + setAbortStatus(); + } catch (APPCException e) { + setErrorStatus(e); + stateHelper.setState(AppcOamStates.Error); + } + return false; + } + + /** + * Final handling + * @param setState boolean to indicate if set OAM state or not + */ + @Override + void postDoAction(boolean setState) { + postAction(setState ? finalState : null); + super.postDoAction(setState); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/AsyncTaskHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/AsyncTaskHelper.java new file mode 100644 index 000000000..2f74bf5a9 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/AsyncTaskHelper.java @@ -0,0 +1,394 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.processor.BaseActionRunnable; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.FrameworkUtil; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; + +/** + * The AsyncTaskHelper class manages an internal parent child data structure. The parent is a transient singleton, + * meaning only one can exist at any given time. The parent is scheduled with the + * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and is executed at configured interval. It can be + * terminated by using the {@link Future#cancel(boolean)} or the {@link Future#cancel(boolean)} returned from \ + * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)}. + *

+ * The children are scheduled using {@link #submitBaseSubCallable(Callable)}} and can only be scheduled if a parent + * is scheduled. Children only execute once, but can be terminated preemptively by the {@link Future#cancel(boolean)} + * returned from {@link #submitBaseSubCallable(Callable)} or indirectly by terminating the parent via the method + * described above. + *

+ * This class augments the meaning of {@link Future#isDone()} in that it guarantees that this method only returns true + * if the scheduled {@link Runnable} or {@link Callable} is not currently executing and is not going to execute in the + * future. This is different than the Java core implementation of {@link Future#isDone()} in which it will return + * true immediately after the {@link Future#cancel(boolean)} is called. Even if a Thread is actively executing the + * {@link Runnable} or {@link Callable} and has not return yet. See Java BUG JDK-8073704 + *

+ * The parent {@link Future#isDone()} has an additional augmentation in that it will not return true until all of its + * children's {@link Future#isDone()} also return true. + * + */ +@SuppressWarnings("unchecked") +public class AsyncTaskHelper { + + private final EELFLogger logger; + private final ScheduledExecutorService scheduledExecutorService; + private final ThreadPoolExecutor bundleOperationService; + + /** Reference to {@link MyFuture} return from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} */ + private MyFuture backgroundBaseRunnableFuture; + + /** The cancel Callback from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} */ + private Consumer cancelCallBackForBaseRunnable; + + /** All Futures created by thus calls which have not completed -- {@link Future#isDone()} equals false */ + private Set myFutureSet = new HashSet<>(); + + /** + * Constructor + * @param eelfLogger of the logger + */ + public AsyncTaskHelper(EELFLogger eelfLogger) { + logger = eelfLogger; + + scheduledExecutorService = Executors.newSingleThreadScheduledExecutor( + (runnable) -> { + Bundle bundle = FrameworkUtil.getBundle(AppcOam.class); + return new Thread(runnable, bundle.getSymbolicName() + " scheduledExecutor"); + } + ); + + bundleOperationService = new ThreadPoolExecutor( + 0, + 10, + 10, + TimeUnit.SECONDS, + new LinkedBlockingQueue(), //BlockingQueue workQueue + (runnable) -> { + Bundle bundle = FrameworkUtil.getBundle(AppcOam.class); + return new Thread(runnable, bundle.getSymbolicName() + " bundle operation executor"); + } + ); + } + + /** + * Terminate the class ScheduledExecutorService + */ + public void close() { + logDebug("Start shutdown scheduleExcutorService."); + bundleOperationService.shutdownNow(); + scheduledExecutorService.shutdownNow(); + logDebug("Completed shutdown scheduleExcutorService."); + } + + + /** + * Cancel currently executing {@link BaseActionRunnable} if any. + * This method returns immediately if there is currently no {@link BaseActionRunnable} actively executing. + * @param rpcCausingAbort - The RPC causing the abort + * @param stateBeingAbborted - The current state being canceled + * @param timeout - The amount of time to wait for a cancel to complete + * @param timeUnit - The unit of time of timeout + * @throws TimeoutException - If {@link BaseActionRunnable} has not completely cancelled within the timeout period + * @throws InterruptedException - If the Thread waiting for the abort + */ + public synchronized void cancelBaseActionRunnable(final AppcOam.RPC rpcCausingAbort, + AppcOamStates stateBeingAbborted, + long timeout, TimeUnit timeUnit) + throws TimeoutException,InterruptedException { + + final MyFuture localBackgroundBaseRunnableFuture = backgroundBaseRunnableFuture; + final Consumer localCancelCallBackForBaseRunnable = cancelCallBackForBaseRunnable; + + if (localBackgroundBaseRunnableFuture == null || localBackgroundBaseRunnableFuture.isDone()) { + return; + } + + if (localCancelCallBackForBaseRunnable != null) { + localCancelCallBackForBaseRunnable.accept(rpcCausingAbort); + } + localBackgroundBaseRunnableFuture.cancel(true); + + long timeoutMillis = timeUnit.toMillis(timeout); + long expiryTime = System.currentTimeMillis() + timeoutMillis; + while (!(localBackgroundBaseRunnableFuture.isDone())) { + long sleepTime = expiryTime - System.currentTimeMillis(); + if (sleepTime < 1) { + break; + } + this.wait(sleepTime); + } + + if (!localBackgroundBaseRunnableFuture.isDone()) { + throw new TimeoutException(String.format("Unable to abort %s in timely manner.",stateBeingAbborted)); + } + } + + /** + * Schedule a {@link BaseActionRunnable} to begin async execution. This is the Parent {@link Runnable} for the + * children that are submitted by {@link #submitBaseSubCallable(Callable)} + * + * The currently executing {@link BaseActionRunnable} must fully be terminated before the next can be scheduled. + * This means all Tasks' {@link MyFuture#isDone()} must equal true and all threads must return to their respective + * thread pools. + * + * @param runnable of the to be scheduled service. + * @param cancelCallBack to be invoked when + * {@link #cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)} is invoked. + * @param initialDelayMillis the time to delay first execution + * @param delayMillis the delay between the termination of one + * execution and the commencement of the next + * @return The {@link BaseActionRunnable}'s {@link Future} + * @throws IllegalStateException if there is currently executing Task + */ + public synchronized Future scheduleBaseRunnable(final Runnable runnable, + final Consumer cancelCallBack, + long initialDelayMillis, + long delayMillis) + throws IllegalStateException { + + if (backgroundBaseRunnableFuture != null && !backgroundBaseRunnableFuture.isDone()) { + throw new IllegalStateException("Unable to schedule background task when one is already running. All task must fully terminated before another can be scheduled. "); + } + + this.cancelCallBackForBaseRunnable = cancelCallBack; + + backgroundBaseRunnableFuture = new MyFuture(runnable) { + /** + * augments the cancel operation to cancel all subTack too, + */ + @Override + public boolean cancel(final boolean mayInterruptIfRunning) { + boolean cancel; + synchronized (AsyncTaskHelper.this) { + cancel = super.cancel(mayInterruptIfRunning); + //clone the set to prevent java.util.ConcurrentModificationException. The synchronized prevents + //other threads from modifying this set, but not itself. The f->f.cancel may modify myFutureSet by + //removing an entry which breaks the iteration in the forEach. + (new HashSet(myFutureSet)) + .stream().filter(f->!this.equals(f)).forEach(f->f.cancel(mayInterruptIfRunning)); + } + return cancel; + } + + /** + * augments the isDone operation to return false until all subTask have completed too. + */ + @Override + public boolean isDone() { + synchronized (AsyncTaskHelper.this) { + return myFutureSet.isEmpty(); + } + } + }; + backgroundBaseRunnableFuture.setFuture( + scheduledExecutorService.scheduleWithFixedDelay( + backgroundBaseRunnableFuture, initialDelayMillis, delayMillis, TimeUnit.MILLISECONDS) + ); + return backgroundBaseRunnableFuture; + } + + /** + * Submits children {@link Callable} to be executed as soon as possible, A parent must have been scheduled + * previously via {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} + * @param callable the Callable to be submitted + * @return The {@link Callable}'s {@link Future} + */ + synchronized Future submitBaseSubCallable(final Callable callable) { + + if (backgroundBaseRunnableFuture == null + || backgroundBaseRunnableFuture.isCancelled() + || backgroundBaseRunnableFuture.isDone()){ + throw new IllegalStateException("Unable to schedule subCallable when a base Runnable is not running."); + } + + //Make sure the pool is ready to go + if(bundleOperationService.getPoolSize() != bundleOperationService.getMaximumPoolSize()){ + bundleOperationService.setCorePoolSize(bundleOperationService.getMaximumPoolSize()); + bundleOperationService.prestartAllCoreThreads(); + bundleOperationService.setCorePoolSize(0); + } + + MyFuture myFuture = new MyFuture(callable); + myFuture.setFuture(bundleOperationService.submit((Callable)myFuture)); + return myFuture; + } + + /** + * Genral debug log when debug logging level is enabled. + * @param message of the log message format + * @param args of the objects listed in the message format + */ + private void logDebug(String message, Object... args) { + if (logger.isDebugEnabled()) { + logger.debug(String.format(message, args)); + } + } + + /** + * This class has two purposes. First it insures {@link #isDone()} only returns true if the deligate is not + * currently running and will not be running in the future: See Java BUG JDK-8073704 Second this class maintains + * the {@link #myFutureSet } by insurring that itself is removed when {@link #isDone()} returns true. + * + * See {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and {@link #submitBaseSubCallable(Callable)} + * for usage of this class + */ + private class MyFuture implements Future, Runnable, Callable { + + private Future future; + private final Runnable runnable; + private final Callable callable; + private boolean isRunning; + + MyFuture(Runnable runnable) { + this.runnable = runnable; + this.callable = null; + myFutureSet.add(this); + } + + MyFuture(Callable callable) { + this.runnable = null; + this.callable = callable; + myFutureSet.add(this); + } + + void setFuture(Future future) { + this.future = future; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + synchronized (AsyncTaskHelper.this) { + if (!isRunning) { + myFutureSetRemove(); + } + + return future.cancel(mayInterruptIfRunning); + } + } + + @Override + public boolean isCancelled() { + synchronized (AsyncTaskHelper.this) { + return future.isCancelled(); + } + } + + @Override + public boolean isDone() { + synchronized (AsyncTaskHelper.this) { + return future.isDone() && !isRunning; + } + } + + @Override + public T get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Override + public void run() { + synchronized (AsyncTaskHelper.this) { + if(future.isCancelled()){ + return; + } + isRunning = true; + } + try { + runnable.run(); + } finally { + synchronized (AsyncTaskHelper.this) { + isRunning = false; + + //The Base Runnable is expected to run again. + //unless it has been canceled. + //so only removed if it is canceled. + if (future.isCancelled()) { + myFutureSetRemove(); + } + } + } + } + + @Override + public T call() throws Exception { + synchronized (AsyncTaskHelper.this) { + if(future.isCancelled()){ + throw new CancellationException(); + } + isRunning = true; + } + try { + return callable.call(); + } finally { + synchronized (AsyncTaskHelper.this){ + isRunning = false; + myFutureSetRemove(); + } + } + } + + + /** + * Removes this from the the myFutureSet. + * When all the BaseActionRunnable is Done notify any thread waiting in + * {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)} + */ + void myFutureSetRemove(){ + synchronized (AsyncTaskHelper.this) { + myFutureSet.remove(this); + if(myFutureSet.isEmpty()){ + backgroundBaseRunnableFuture = null; + cancelCallBackForBaseRunnable = null; + AsyncTaskHelper.this.notifyAll(); + + } + } + } + + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleFilter.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleFilter.java new file mode 100644 index 000000000..6dd98f165 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleFilter.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import org.osgi.framework.Bundle; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + + + +/** + * + * Utility Class that splits a given bundleSet into two sets: bundleToStopSet and + * bundleToNotStopSet + * + * The bundleToStopSet is defined as: all bundles which match at least one of + * the stopRegexes but exceptRegexes none of the + * + * The bundleToNotStopSet is defined as all bundles which are not a member of + * the bundleToStopSet + * + */ +class BundleFilter { + + private final Map bundleToStopSet; + private final Map bundleToNotStopSet; + + + /** + * BundleFilter a bundle filter + * @param stopRegexes - An array of regular expression used to pick out which bundles are candidates for stopping + * @param exceptRegexes - An array of regular expression used to override which bundles are candidates for stopping + * @param bundles - An array of the bundle to be split into {@link #getBundlesToStop()} {@link #getBundlesToNotStop()} + */ + BundleFilter(String[] stopRegexes, String[] exceptRegexes, Bundle[] bundles) { + + Pattern[] stopPatterns = toPattern(stopRegexes); + Pattern[] exceptPatterns = toPattern(exceptRegexes); + + Map bundleToStop = new HashMap<>(); + Map bundleToNotStop = new HashMap<>(); + + for (Bundle bundle : bundles) { + String symbolicName = bundle.getSymbolicName(); + if (isMatch(symbolicName,stopPatterns) && !isMatch(symbolicName,exceptPatterns)) { + bundleToStop.put(symbolicName, bundle); + } else { + bundleToNotStop.put(symbolicName, bundle); + } + } + + this.bundleToStopSet = Collections.unmodifiableMap(bundleToStop); + this.bundleToNotStopSet = Collections.unmodifiableMap(bundleToNotStop); + } + + /** + * Determines if the value matches any of the regular expressions. + * + * @param value + * - the value that is to be matched + * @param patterns + * - the array of {@link Pattern} to match the value against + * @return boolean true if there is a match + */ + private boolean isMatch(String value,Pattern[] patterns) { + for (Pattern pattern : patterns) { + if (pattern.matcher(value).matches()) { + return true; + } + } + return false; + } + + /** + * This method converts an Array of regular expression in String form into a + * Array of {@link Pattern} + * + * @param regex + * - A string array of regular expressions + * @return Pattern Array of compiled regular expressions + */ + private Pattern[] toPattern(String[] regex) { + Pattern[] pattern = new Pattern[regex.length]; + for (int i = 0; i < regex.length; i++ ) { + pattern[i] = Pattern.compile(regex[i]); + } + return pattern; + } + + + /**@return Map of bundles that are to be stopped */ + Map getBundlesToStop(){ + return bundleToStopSet; + } + + /** + * + * @return Map of bundles that are not to be stopped + */ + Map getBundlesToNotStop() { + return bundleToNotStopSet; + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleHelper.java new file mode 100644 index 000000000..3a4602542 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/BundleHelper.java @@ -0,0 +1,274 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.ArrayUtils; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.processor.BaseCommon; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.FrameworkUtil; + +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; + +/** + * Utility class provides general bundle operational helps. + */ +public class BundleHelper { + private final static String PROP_BUNDLE_TO_STOP = "appc.OAM.ToStop.properties"; + private final static String PROP_BUNDLES_TO_NOT_STOP = "appc.OAM.ToNotStop.properties"; + + private final EELFLogger logger; + private final StateHelper stateHelper; + private final ConfigurationHelper configurationHelper; + + /** + * Constructor + * + * @param eelfLogger of the logger + * @param configurationHelperIn of ConfigurationHelper instance + * @param stateHelperIn of StateHelper instance + */ + public BundleHelper(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn) { + logger = eelfLogger; + configurationHelper = configurationHelperIn; + stateHelper = stateHelperIn; + } + + /** + * Handle bundle operations, such as stop or start bundle. + * + * @param rpc enum indicate if the operation is to stop, start or restart + * @return boolean to indicate if the operation is successful (true) or failed (false) + * @throws APPCException when error occurs + */ + public boolean bundleOperations(AppcOam.RPC rpc, + Map> threads, + AsyncTaskHelper taskHelper, + BaseCommon baseCommon) + throws APPCException { + long mStartTime = System.currentTimeMillis(); + logDebug(String.format("Entering OAM bundleOperations with rpc (%s).", rpc.name())); + + String action = rpc.getAppcOperation().toString(); + if (rpc != AppcOam.RPC.stop && rpc != AppcOam.RPC.start) { + throw new APPCException("rpc(" + rpc + ") is not supported by bundleOperation."); + } + + AppcOamStates originalState = stateHelper.getState(); + + boolean isBundleOperationComplete = true; + + Map appcLcmBundles = getAppcLcmBundles(); + for (Map.Entry bundleEntry : appcLcmBundles.entrySet()) { + String bundleName = bundleEntry.getKey(); + Bundle bundle = bundleEntry.getValue(); + + logDebug("OAM launch thread for %s bundle %s", action, bundleName); + if (rpc == AppcOam.RPC.start) { + // Abort in the interruption case. + // such as when a Stop request is receive while APPC is still trying to Start Up. + if (!stateHelper.isSameState(originalState)) { + logger.warn("OAM %s bundle operation aborted since OAM state is no longer %s!", + originalState.name()); + isBundleOperationComplete = false; + break; + } + } + + threads.put(bundleName, + taskHelper.submitBaseSubCallable(new BundleTask(rpc, bundle,baseCommon))); + } + + logDebug(String.format("Leaving OAM bundleOperations with rpc (%s) with complete(%s), elasped (%d) ms.", + rpc.name(), Boolean.toString(isBundleOperationComplete), getElapseTimeMs(mStartTime))); + + return isBundleOperationComplete; + } + + private long getElapseTimeMs(long mStartTime) { + return System.currentTimeMillis() - mStartTime; + } + + /** + * Check if all BundleTasks are completed + * @param bundleNameFutureMap with bundle name and BundleTask Future object + * @return true if all are done, otherwise, false + */ + public boolean isAllTaskDone(Map> bundleNameFutureMap) { + boolean anyNotDone = bundleNameFutureMap.values().stream().anyMatch((f) -> !f.isDone()); + return !anyNotDone; + } + + /** + * Cancel BundleTasks which are not finished + * @param bundleNameFutureMap with bundle name and BundleTask Future object + */ + public void cancelUnfinished(Map> bundleNameFutureMap) { + bundleNameFutureMap.values().stream().filter((f) + -> !f.isDone()).forEach((f) + -> f.cancel(true)); + } + + /** + * Get number of failed BundleTasks + * @param bundleNameFutureMap with bundle name and BundleTask Future object + * @return number(long) of the failed BundleTasks + */ + public long getFailedMetrics(Map> bundleNameFutureMap) { + return bundleNameFutureMap.values().stream().map((f) -> { + try { + return f.get(); + } catch (Exception e) { + // should not get here + throw new RuntimeException(e); + } + }).filter((b) -> ((BundleTask)b).failException != null).count(); + } + + /** + * Gets the list of Appc-bundles to be stopped/started + * + * @return Map of bundle symbolic name and bundle instance + */ + Map getAppcLcmBundles() { + logDebug("In getAppcLcmBundles"); + + String[] bundlesToStop = readPropsFromPropListName(PROP_BUNDLE_TO_STOP); + String[] regExBundleNotStop = readPropsFromPropListName(PROP_BUNDLES_TO_NOT_STOP); + + BundleFilter bundleList = new BundleFilter(bundlesToStop, regExBundleNotStop, getBundleList()); + + logger.info(String.format("(%d) APPC bundles to Stop/Start: %s.", bundleList.getBundlesToStop().size(), + bundleList.getBundlesToStop().toString())); + + logger.debug(String.format("(%d) APPC bundles that won't be Stopped/Started: %s.", + bundleList.getBundlesToNotStop().size(), bundleList.getBundlesToNotStop().toString())); + + return bundleList.getBundlesToStop(); + } + + /** + * Gets a list of all user desired bundles that should be stopped/Started as part of + * OAM Stop and Start API + * + * @param propListKey String of the properties list property name + * @return properties values of the related + */ + String[] readPropsFromPropListName(String propListKey) { + // get properties list by properties list name + String[] propNames = configurationHelper.readProperty(propListKey); + // go through each property to get the property values + String[] propValue = ArrayUtils.EMPTY_STRING_ARRAY; + if (propNames != null) { + for (String aPropName : propNames) { + propValue = ArrayUtils.addAll(propValue, configurationHelper.readProperty(aPropName)); + } + } + return propValue; + } + + /** + * Get all bundle list of APP-C + * @return Array of Bundle + */ + Bundle[] getBundleList() { + BundleContext myBundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + if (myBundleContext != null) { + return myBundleContext.getBundles(); + } + return null; + } + + /** + * Genral debug log when debug logging level is enabled. + * @param message of the log message format + * @param args of the objects listed in the message format + */ + private void logDebug(String message, Object... args) { + if (logger.isDebugEnabled()) { + logger.debug(String.format(message, args)); + } + } + + /** + * Runnable to execute bundle operations: start or stop + */ + class BundleTask implements Callable { + Exception failException; + + private AppcOam.RPC rpc; + private Bundle bundle; + private String bundleName; + private String actionName; + private final BaseCommon baseCommon; + + BundleTask(AppcOam.RPC rpcIn, Bundle bundleIn, BaseCommon baseCommon) { + rpc = rpcIn; + actionName = rpc.getAppcOperation().toString(); + bundle = bundleIn; + bundleName = bundle.getSymbolicName(); + this.baseCommon = baseCommon; + } + + @Override + public BundleTask call() throws Exception { + try { + baseCommon.setInitialLogProperties(); + + long bundleOperStartTime = System.currentTimeMillis(); + logDebug(String.format("OAM %s bundle %s ===>", actionName, bundleName)); + switch (rpc) { + case start: + bundle.start(); + break; + case stop: + bundle.stop(); + break; + default: + // should do nothing + } + logDebug(String.format("OAM %s bundle %s completed <=== elasped %d", + actionName, bundleName, getElapseTimeMs(bundleOperStartTime))); + } catch (BundleException e) { + logger.error(String.format("Exception encountered when OAM %s bundle %s ", + actionName, bundleName), e); + failException = e; + } + finally { + baseCommon.clearRequestLogProperties(); + } + return this; + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/ConfigurationHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/ConfigurationHelper.java new file mode 100644 index 000000000..3c5629f11 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/ConfigurationHelper.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.ArrayUtils; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +import java.util.concurrent.TimeUnit; + +/** + * Utility class provides general configuration helps + */ +public class ConfigurationHelper { + final static String PROP_KEY_APPC_NAME = Constants.PROPERTY_APPLICATION_NAME; + final static String PROP_KEY_METRIC_STATE = "metric.enabled"; + private final String OAM_OPERATION_TIMEOUT_SECOND = "appc.OAM.api.timeout"; + /** Default operation timeout set to 1 minute */ + private final int DEFAULT_OAM_OPERATION_TIMEOUT = 60; + + private final EELFLogger logger; + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + public ConfigurationHelper(EELFLogger eelfLogger) { + logger = eelfLogger; + } + + public String getAppcName() { + return configuration.getProperty(PROP_KEY_APPC_NAME); + } + + public boolean isMetricEnabled() { + return configuration.getBooleanProperty(PROP_KEY_METRIC_STATE, false); + } + + public Configuration getConfig() { + return configuration; + } + + /** + * Read property value of a specified property key + * + * @param propertyKey string of the property key + * @return String[] of the property values associated with the propertyKey + */ + String[] readProperty(String propertyKey) { + String propertyValue = configuration.getProperty(propertyKey); + if (propertyValue == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + + if (logger.isDebugEnabled()) { + logger.debug(String.format("Property[%s] has value (%s).", propertyKey, propertyValue)); + } + + if (propertyValue.contains(",")) { + return propertyValue.split("\\s*,\\s*"); + } + return new String[]{propertyValue}; + } + + + + + + /** + * This method returns timeout in milliseconds. The source is chosen in the following order: + * The overrideTimeoutSeconds argument + * or {@link #OAM_OPERATION_TIMEOUT_SECOND} found in the configuration file + * or the {@link #DEFAULT_OAM_OPERATION_TIMEOUT} + * @param overrideTimeoutSeconds or null to us the other sources + * @return timeout in milliseconds + */ + public long getOAMOperationTimeoutValue(Integer overrideTimeoutSeconds) { + return TimeUnit.SECONDS.toMillis( + overrideTimeoutSeconds == null ? + getConfig().getIntegerProperty(OAM_OPERATION_TIMEOUT_SECOND, DEFAULT_OAM_OPERATION_TIMEOUT) + : + overrideTimeoutSeconds + ); + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/OperationHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/OperationHelper.java new file mode 100644 index 000000000..9eec0b67b --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/OperationHelper.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.common.header.Flags; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.messageadapter.MessageAdapter; +import org.onap.appc.oam.messageadapter.OAMContext; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +/** + * Utility class provides general operational helps. + */ +@SuppressWarnings("unchecked") +public class OperationHelper { + final String MISSING_COMMON_HEADER_MESSAGE = "Missing common header"; + final String MISSING_FIELD_MESSAGE = "Common header must have both originatorId and requestId"; + final String NOT_SUPPORT_FLAG = "Flags is not supported by this operation"; + final String NO_SERVICE_REF_FORMAT = "Using the BundleContext failed to get service reference for %s"; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(OperationHelper.class); + private LifecycleManager lifecycleMgr; + private MessageAdapter messageAdapter; + + public OperationHelper() { + // do nothing + } + + /** + * This method is used to validate OAM REST API input due to the following ODL bugs results no validation : + *

- + * Bug 8088 - Mandatory attributes in RPC input are not honoured + *

- + * Bug 5830 - Mandatory leaf enforcement is not correct with presence container + * + * @param inputObject object from the OAM REST API input object + * @throws InvalidInputException is thrown when the commonHeader is invalid + */ + public void isInputValid(final Object inputObject) throws InvalidInputException { + CommonHeader commonHeader = getCommonHeader(inputObject); + if (commonHeader == null) { + throw new InvalidInputException(MISSING_COMMON_HEADER_MESSAGE); + } + + if (commonHeader.getOriginatorId() == null + || commonHeader.getRequestId() == null) { + throw new InvalidInputException(MISSING_FIELD_MESSAGE); + } + + // check Flags + if (inputObject instanceof MaintenanceModeInput + && commonHeader.getFlags() != null) { + throw new InvalidInputException(NOT_SUPPORT_FLAG); + } + } + + /** + * Get commonHead of the inputObject (expecting the inputObject of OAM REST API) + * @param inputObject the OAM REST API input object + * @return CommonHeader of the inputObject. If the inputObject is not a OAM REST API input, null is returned. + */ + public CommonHeader getCommonHeader(final Object inputObject) { + if (inputObject instanceof StartInput) { + return ((StartInput)inputObject).getCommonHeader(); + } + if (inputObject instanceof StopInput) { + return ((StopInput)inputObject).getCommonHeader(); + } + if (inputObject instanceof MaintenanceModeInput) { + return ((MaintenanceModeInput)inputObject).getCommonHeader(); + } + if (inputObject instanceof RestartInput) { + return ((RestartInput)inputObject).getCommonHeader(); + } + return null; + } + + public Integer getParamRequestTimeout(final Object inputObject) { + if (inputObject instanceof MaintenanceModeInput) { + // maintanence mode, we do not support request timeout + return 0; + } + + CommonHeader commonHeader = getCommonHeader(inputObject); + if (commonHeader == null) { + return 0; + } + + Flags inputFlags = commonHeader.getFlags(); + if (inputFlags == null) { + return null; + } + return inputFlags.getRequestTimeout(); + } + /** + * Get service instance using bundle context. + * + * @param _class of the expected service instance + * @param of the expected service instance + * @return service instance of the expected + * @throws APPCException when cannot find service reference or service isntance + */ + public T getService(Class _class) throws APPCException { + BundleContext bctx = FrameworkUtil.getBundle(_class).getBundleContext(); + if (bctx != null) { + ServiceReference sref = bctx.getServiceReference(_class.getName()); + if (sref != null) { + if (logger.isTraceEnabled()) { + logger.debug("Using the BundleContext got the service reference for " + _class.getName()); + } + return (T) bctx.getService(sref); + } + } + + throw new APPCException(String.format(NO_SERVICE_REF_FORMAT, _class.getName())); + } + + /** + * Get next valid state from life cycle manager. + * + * @param operation of the AppcOperation for the state changes + * @param currentState of AppcOamStates + * @return next AppcOamStates based on the currentState and operation + * @throws APPCException If life cycle manager instance cannot be retrieved + * @throws InvalidStateException when the operation is not supported on the currentState + */ + public AppcOamStates getNextState(AppcOamMetaDataReader.AppcOperation operation, AppcOamStates currentState) + throws APPCException, InvalidStateException { + if (lifecycleMgr == null) { + lifecycleMgr = getService(LifecycleManager.class); + } + + try { + String nextState = lifecycleMgr.getNextState("APPC", currentState.name(), operation.toString()); + if (nextState != null) { + return AppcOamStates.valueOf(nextState); + } + } catch (LifecycleException |NoTransitionDefinedException ex) { + logger.error("Invalid next state based on the current state and attempted Operation " + ex.getMessage()); + } + + throw new InvalidStateException(String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, operation, "APPC", currentState)); + } + + /** + * Post notification through MessageAdapter. + * + * @param rpc of REST API RPC + * @param commonHeader of REST API request common header + * @param status of the to be post message + */ + public void sendNotificationMessage(AppcOam.RPC rpc, CommonHeader commonHeader, Status status) { + if (messageAdapter == null) { + messageAdapter = new MessageAdapter(); + messageAdapter.init(); + + } + + OAMContext oamContext = new OAMContext(); + oamContext.setRpcName(rpc); + oamContext.setCommonHeader(commonHeader); + oamContext.setStatus(status); + messageAdapter.post(oamContext); + } +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/StateHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/StateHelper.java new file mode 100644 index 000000000..871a07676 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/onap/appc/oam/util/StateHelper.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; + +import java.util.Map; + +/* + * Utility class provides general state helps + */ +public class StateHelper { + /** logger inherited from AppcOam */ + private final EELFLogger logger; + private ConfigurationHelper configurationHelper; + /** APP-C OAM current state in AppcOamStates value */ + private volatile AppcOamStates appcOamCurrentState; + + /** + * Constructor + * + * @param eelfLogger of the logger + */ + public StateHelper(EELFLogger eelfLogger, ConfigurationHelper cHelper) { + logger = eelfLogger; + configurationHelper = cHelper; + appcOamCurrentState = AppcOamStates.Unknown; + } + + /** + * Set the passed in state to the class appOamCurrentState. + * + * @param appcOamStates of the new state + */ + public void setState(AppcOamStates appcOamStates) { + appcOamCurrentState = appcOamStates; + } + + /** + * Get the state + * @return the class appOamCurrentState + */ + public AppcOamStates getState() { + return appcOamCurrentState; + } + + /** + * Validate if the passed in state is the same as the class appOamCurrentState. + * + * @param appcOamStates of the to be compared state + * @return true if they are the same, otherwise false + */ + boolean isSameState(AppcOamStates appcOamStates) { + return appcOamCurrentState == appcOamStates; + } + + /** + * Get APP-C OAM current state + * + *

When appcOamCurrentState is null or unknown, reset it with APPC LCM bundle state. + * + * @return AppcOamStates of the current APP-C OAM state + */ + public AppcOamStates getCurrentOamState() { + if (appcOamCurrentState == null || appcOamCurrentState.equals(AppcOamStates.Unknown)) { + appcOamCurrentState = getBundlesState(); + } + return appcOamCurrentState; + } + + /** + * Use getCurrentOamState to get current OAM AppcOamStates and then convert to AppcState of Yang. + * + * @return AppcState of current OAM state + */ + public AppcState getCurrentOamYangState() { + try { + AppcOamStates appcOamStates = getCurrentOamState(); + return AppcState.valueOf(appcOamStates.name()); + } catch (Exception ex) { + logger.error(String.format("Unable to determine the current APP-C OAM state due to %s.", ex.getMessage())); + } + return AppcState.Unknown; + } + + /** + * Get APPC state from the state of the set of APPC LCM bundles. + *

The state of each bundle will be checked and the lowest state will be uses as the returning AppcOamStates. + *

The bundle state order are defined in OSGI bundle (@see org.osgi.framework.Bundle) class + * as the int value assigned to each state as the following:
+ * - UNINSTALLED (1)
+ * - INSTALLED (2)
+ * - RESOLVED (4)
+ * - STARTING (8)
+ * - STOPPING (16)
+ * - ACTIVE (32)
+ * + * @return AppcOamStates + */ + public AppcOamStates getBundlesState() { + BundleHelper bundleHelper = new BundleHelper(logger, configurationHelper, this); + Map lcmBundleMap = bundleHelper.getAppcLcmBundles(); + if (lcmBundleMap == null || lcmBundleMap.isEmpty()) { + return AppcOamStates.Unknown; + } + + // As we are picking up the lowest bundle state as general APP-C state, we will start with ACTIVE + int currentState = Bundle.ACTIVE; + for (Bundle bundle : lcmBundleMap.values()) { + int bundleState = bundle.getState(); + logger.trace(String.format("getBundlesState: [%s] has state (%d)", bundle.getSymbolicName(), bundleState)); + if (bundleState < currentState) { + currentState = bundleState; + } + } + return AppcOamStates.getOamStateFromBundleState(currentState); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModule.java b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModule.java new file mode 100644 index 000000000..c978e3a45 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModule.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303; + +import org.onap.appc.oam.AppcOam; + +public class AppcOamModule extends org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AbstractAppcOamModule { + public AppcOamModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public AppcOamModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AppcOamModule oldModule, java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void customValidation() { + // add custom validation form module attributes here. + } + + @Override + public java.lang.AutoCloseable createInstance() { + final AppcOam oam = new AppcOam(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); + return new AutoCloseable() { + + @Override + public void close() throws Exception { + oam.close(); + } + }; + } + +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModuleFactory.java b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModuleFactory.java new file mode 100644 index 000000000..6913a68f0 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/oam/impl/rev170303/AppcOamModuleFactory.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/* +* Generated file +* +* Generated from: yang module name: appc-oam-impl yang module local name: appc-oam-impl +* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator +* Generated at: Mon Apr 24 16:25:46 IST 2017 +* +* Do not modify this file unless it is present under src/main directory +*/ +package org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303; +public class AppcOamModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AbstractAppcOamModuleFactory { + +} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModule.java b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModule.java deleted file mode 100644 index c978e3a45..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModule.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303; - -import org.onap.appc.oam.AppcOam; - -public class AppcOamModule extends org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AbstractAppcOamModule { - public AppcOamModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public AppcOamModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AppcOamModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - final AppcOam oam = new AppcOam(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); - return new AutoCloseable() { - - @Override - public void close() throws Exception { - oam.close(); - } - }; - } - -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModuleFactory.java b/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModuleFactory.java deleted file mode 100644 index 6913a68f0..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/oam/impl/rev170303/AppcOamModuleFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/* -* Generated file -* -* Generated from: yang module name: appc-oam-impl yang module local name: appc-oam-impl -* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator -* Generated at: Mon Apr 24 16:25:46 IST 2017 -* -* Do not modify this file unless it is present under src/main directory -*/ -package org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303; -public class AppcOamModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.oam.impl.rev170303.AbstractAppcOamModuleFactory { - -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java deleted file mode 100644 index 97938339c..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/AppcOam.java +++ /dev/null @@ -1,339 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.util.concurrent.Futures; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcOamService; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.Metrics; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.MetricsBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValues; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValuesBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.oam.processor.OamMmodeProcessor; -import org.onap.appc.oam.processor.OamRestartProcessor; -import org.onap.appc.oam.processor.OamStartProcessor; -import org.onap.appc.oam.processor.OamStopProcessor; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader.AppcOperation; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Future; - -/** - * RPC class of APP-C OAM API. - *

Implement all the RPCs defined in AppcOamService through yang model definition. - *

All RPC methods' JAVADOC are using "inheritDoc" to use the description from the yang model file. - */ -public class AppcOam implements AutoCloseable, AppcOamService { - /** - * Invalid state message format with fliexible operation, appc name and state values - */ - public final static String INVALID_STATE_MESSAGE_FORMAT = "%s API is not allowed when %s is in the %s state."; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcOam.class); - - private boolean isMetricEnabled = false; - - /** - * Represents our RPC implementation registration - */ - private BindingAwareBroker.RpcRegistration rpcRegistration; - - - /** - * The yang rpc names with value mapping to AppcOperation - */ - public enum RPC { - maintenance_mode(AppcOperation.MaintenanceMode), - start(AppcOperation.Start), - stop(AppcOperation.Stop), - restart(AppcOperation.Restart); - - AppcOperation appcOperation; - - RPC(AppcOperation appcOperation) { - this.appcOperation = appcOperation; - } - - public AppcOperation getAppcOperation() { - return appcOperation; - } - } - - private AsyncTaskHelper asyncTaskHelper; - private ConfigurationHelper configurationHelper; - private OperationHelper operationHelper; - private StateHelper stateHelper; - - /** - * APP-C OAM contructor - * - * @param dataBroker object of The ODL data store broker. Provides access to a conceptual data - * tree store - * and also provides the ability to subscribe for changes to data under a - * given branch - * of the tree. Not used in this class. - * @param notificationProviderService object of ODL Notification Service that provides publish/subscribe - * capabilities for YANG modeled notifications. Not used in this class. - * @param rpcProviderRegistry object of RpcProviderResigstry. Used to register our RPCs. - */ - @SuppressWarnings({"unused", "nls"}) - public AppcOam(DataBroker dataBroker, - NotificationProviderService notificationProviderService, - RpcProviderRegistry rpcProviderRegistry) { - - configurationHelper = new ConfigurationHelper(logger); - String appName = configurationHelper.getAppcName(); - logger.info(Msg.COMPONENT_INITIALIZING, appName, "oam"); - - if (rpcProviderRegistry != null) { - rpcRegistration = rpcProviderRegistry.addRpcImplementation(AppcOamService.class, this); - } - - isMetricEnabled = configurationHelper.isMetricEnabled(); - - initHelpers(); - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "oam"); - } - - /** - * Initialize helper classes. - *

Note: ConfigurationHelper initializetion is in included here - * because it is needed for extracting the AppName used in the debug logs within the constructor. - */ - private void initHelpers() { - operationHelper = new OperationHelper(); - asyncTaskHelper = new AsyncTaskHelper(logger); - stateHelper = new StateHelper(logger, configurationHelper); - } - - /** - * Implements the close of the service - * - * @see AutoCloseable#close() - */ - @SuppressWarnings("nls") - @Override - public void close() throws Exception { - String appName = configurationHelper.getAppcName(); - logger.info(Msg.COMPONENT_TERMINATING, appName, "oam"); - - asyncTaskHelper.close(); - - if (rpcRegistration != null) { - rpcRegistration.close(); - } - logger.info(Msg.COMPONENT_TERMINATED, appName, "oam"); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> getMetrics() { - - if (!isMetricEnabled) { - logger.error("Metric Service not enabled returning failure"); - RpcResult result = RpcResultBuilder. - status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not enabled").build(); - return Futures.immediateFuture(result); - } - - MetricService metricService; - try { - metricService = operationHelper.getService(MetricService.class); - } catch (APPCException e) { - logger.error("MetricService not found", e); - RpcResult result = RpcResultBuilder. - status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not found").build(); - return Futures.immediateFuture(result); - } - - Map allMetricRegitry = metricService.getAllRegistry(); - if (allMetricRegitry == null || allMetricRegitry.isEmpty()) { - logger.error("No metrics registered returning failure"); - RpcResult result = RpcResultBuilder. - status(false).withError(RpcError.ErrorType.APPLICATION, "No metrics Registered").build(); - return Futures.immediateFuture(result); - } - - List metricsList = new ArrayList<>(); - - logger.debug("Iterating metric registry list"); - for (MetricRegistry metricRegistry : allMetricRegitry.values()) { - logger.debug("Iterating metric registry :" + metricRegistry.toString()); - Metric[] metrics = metricRegistry.metrics(); - if (metrics != null && metrics.length > 0) { - logger.debug("Iterating though metrics in registry"); - for (Metric metric : metrics) { - logger.debug("Iterating though metrics: " + metric.name()); - MetricsBuilder metricsBuilder = new MetricsBuilder(); - metricsBuilder.setKpiName(metric.name()); - metricsBuilder.setLastResetTime(metric.getLastModified()); - List kpiList = new ArrayList<>(); - Map metricsOutput = metric.getMetricsOutput(); - for (Map.Entry kpi : metricsOutput.entrySet()) { - KpiValuesBuilder kpiValuesBuilder = new KpiValuesBuilder(); - kpiValuesBuilder.setName(kpi.getKey()); - kpiValuesBuilder.setValue(kpi.getValue()); - kpiList.add(kpiValuesBuilder.build()); - } - metricsBuilder.setKpiValues(kpiList); - metricsList.add(metricsBuilder.build()); - } - } - } - - GetMetricsOutputBuilder outputBuilder = new GetMetricsOutputBuilder(); - outputBuilder.setMetrics(metricsList); - RpcResult result = RpcResultBuilder. - status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> stop(StopInput stopInput) { - logger.debug("Entering Stop with Input : " + stopInput); - final CommonHeader commonHeader = stopInput.getCommonHeader(); - - OamStopProcessor oamStopProcessor = - new OamStopProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - Status status = oamStopProcessor.processRequest(stopInput); - - StopOutputBuilder stopOutputBuilder = new StopOutputBuilder(); - stopOutputBuilder.setStatus(status); - stopOutputBuilder.setCommonHeader(commonHeader); - return RpcResultBuilder.success(stopOutputBuilder.build()).buildFuture(); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> restart(RestartInput input) { - logger.debug("Entering restart with Input : " + input); - final CommonHeader commonHeader = input.getCommonHeader(); - - OamRestartProcessor oamRestartProcessor = - new OamRestartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - Status status = oamRestartProcessor.processRequest(input); - - RestartOutputBuilder restartOutputBuilder = new RestartOutputBuilder(); - restartOutputBuilder.setStatus(status); - restartOutputBuilder.setCommonHeader(commonHeader); - - return RpcResultBuilder.success(restartOutputBuilder.build()).buildFuture(); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> maintenanceMode(MaintenanceModeInput maintenanceModeInput) { - logger.debug("Entering MaintenanceMode with Input : " + maintenanceModeInput); - final CommonHeader commonHeader = maintenanceModeInput.getCommonHeader(); - - OamMmodeProcessor oamMmodeProcessor = - new OamMmodeProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - Status status = oamMmodeProcessor.processRequest(maintenanceModeInput); - - MaintenanceModeOutputBuilder maintenanceModeOutputBuilder = new MaintenanceModeOutputBuilder(); - maintenanceModeOutputBuilder.setStatus(status); - maintenanceModeOutputBuilder.setCommonHeader(commonHeader); - return RpcResultBuilder.success(maintenanceModeOutputBuilder.build()).buildFuture(); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> getAppcState() { - AppcState appcState = stateHelper.getCurrentOamYangState(); - - GetAppcStateOutputBuilder builder = new GetAppcStateOutputBuilder(); - builder.setState(appcState); - return RpcResultBuilder.success(builder.build()).buildFuture(); - } - - /** - * {@inheritDoc} - */ - @Override - public Future> start(StartInput startInput) { - logger.debug("Input received : " + startInput); - final CommonHeader commonHeader = startInput.getCommonHeader(); - - OamStartProcessor oamStartProcessor = - new OamStartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - Status status = oamStartProcessor.processRequest(startInput); - - StartOutputBuilder startOutputBuilder = new StartOutputBuilder(); - startOutputBuilder.setStatus(status); - startOutputBuilder.setCommonHeader(commonHeader); - StartOutput startOutput = startOutputBuilder.build(); - return RpcResultBuilder.success(startOutput).buildFuture(); - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/OAMCommandStatus.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/OAMCommandStatus.java deleted file mode 100644 index 294b9d2cf..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/OAMCommandStatus.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam; - -import org.onap.appc.executor.objects.Params; -import org.onap.appc.util.MessageFormatter; - -import java.util.Map; - -public enum OAMCommandStatus { - - ACCEPTED(100, "ACCEPTED - request accepted"), - UNEXPECTED_ERROR(200, "UNEXPECTED ERROR - ${errorMsg}"), - REJECTED(300, "REJECTED - ${errorMsg}"), - INVALID_PARAMETER(302, "INVALID PARAMETER - ${errorMsg}" ), - TIMEOUT(303, "OPERATION TIMEOUT REACHED - ${errorMsg}"), - ABORT(304, "OPERATION ABORT - ${errorMsg}"), - SUCCESS(400, "SUCCESS - request has been processed successfully"); - - final String TO_STRING_FORMAT = "OAMCommandStatus{responseCode=%d, responseMessage='%s'}"; - - private int responseCode; - private String responseMessage; - - OAMCommandStatus(int responseCode, String responseMessage) { - this.responseCode = responseCode; - this.responseMessage = responseMessage; - } - - public String getResponseMessage() { - return responseMessage; - } - - public int getResponseCode() { - return responseCode; - } - - /** - * Get formated message of passed in params - * - * @param params of Params object with name value pairs for message - * @return message string - */ - public String getFormattedMessage(Params params) { - Map paramsMap = params != null ? params.getParams() : null; - return MessageFormatter.format(getResponseMessage(), paramsMap); - } - - @Override - public String toString() { - return String.format(TO_STRING_FORMAT, responseCode, responseMessage); - }} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/Converter.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/Converter.java deleted file mode 100644 index 152ffc9cc..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/Converter.java +++ /dev/null @@ -1,156 +0,0 @@ -/*-/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.messageadapter; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.opendaylight.yangtools.concepts.Builder; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.onap.appc.oam.AppcOam; - -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -public class Converter { - private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); - - static { - isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - - private static Builder convAsyncResponseToBuilder1(AppcOam.RPC rpcName, - CommonHeader commonHeader, - Status status) { - Builder outObj; - if (rpcName == null) { - throw new IllegalArgumentException("empty asyncResponse.rpcName"); - } - if (commonHeader == null) { - throw new IllegalArgumentException("empty asyncResponse.commonHeader"); - } - if (status == null) { - throw new IllegalArgumentException("empty asyncResponse.status"); - } - switch (rpcName) { - case maintenance_mode: - outObj = new MaintenanceModeOutputBuilder(); - ((MaintenanceModeOutputBuilder) outObj).setCommonHeader(commonHeader); - ((MaintenanceModeOutputBuilder) outObj).setStatus(status); - return outObj; - - case start: - outObj = new StartOutputBuilder(); - ((StartOutputBuilder) outObj).setCommonHeader(commonHeader); - ((StartOutputBuilder) outObj).setStatus(status); - return outObj; - - case stop: - outObj = new StopOutputBuilder(); - ((StopOutputBuilder) outObj).setCommonHeader(commonHeader); - ((StopOutputBuilder) outObj).setStatus(status); - return outObj; - - case restart: - outObj = new RestartOutputBuilder(); - ((RestartOutputBuilder) outObj).setCommonHeader(commonHeader); - ((RestartOutputBuilder) outObj).setStatus(status); - return outObj; - - default: - throw new IllegalArgumentException(rpcName + " action is not supported"); - } - } - - static String convAsyncResponseToUebOutgoingMessageJsonString(OAMContext oamContext) throws - JsonProcessingException { - AppcOam.RPC rpcName = oamContext.getRpcName(); - CommonHeader commonHeader = oamContext.getCommonHeader(); - Status status = oamContext.getStatus(); - - DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToUebOutgoingMessage(rpcName, commonHeader, - status); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), - MixInFlagsMessage.class); - objectMapper.addMixInAnnotations(Status.class, MixIn.class); - objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure - (MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true).writer(); - return writer.writeValueAsString(dmaapOutgoingMessage); - } - - private static DmaapOutgoingMessage convAsyncResponseToUebOutgoingMessage(AppcOam.RPC rpcName, CommonHeader - commonHeader, Status status) throws JsonProcessingException { - DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); - String correlationID = commonHeader.getRequestId(); - outObj.setCorrelationID(correlationID); - outObj.setType("response"); - outObj.setRpcName(rpcName.name()); - Builder builder = Converter.convAsyncResponseToBuilder1(rpcName, commonHeader, status); - Object messageBody = builder.build(); - - DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); - outObj.setBody(body); - return outObj; - } - - - abstract class MixIn { - // to be removed during serialization - @JsonIgnore - abstract Class getImplementedInterface(); - - @JsonValue - abstract java.lang.String getValue(); - } - - abstract class MixInCommonHeader extends MixIn { - @JsonProperty("request-id") - abstract java.lang.String getRequestId(); - - @JsonProperty("originator-id") - abstract java.lang.String getOriginatorId(); - - } - - abstract class MixInFlagsMessage extends MixIn { - @JsonProperty("common-header") - abstract CommonHeader getCommonHeader(); - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/DmaapOutgoingMessage.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/DmaapOutgoingMessage.java deleted file mode 100644 index 25bf0cf8b..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/DmaapOutgoingMessage.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.messageadapter; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** - * This class represents a message being sent out to DMaaP by APPC as async response. - * note the structure of this class must be adapted to the sync message sent to DMaaP represented in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapOutgoingMessage { - - @JsonProperty("type") - private String type; - - @JsonProperty("correlation-id") - private String correlationID; - - private final static String defaultCambriaPartition = "MSO"; - @JsonProperty("cambria.partition") - private String cambriaPartition = defaultCambriaPartition; - - @JsonProperty("rpc-name") - private String rpcName; - - @JsonProperty("body") - private Body body; - - public DmaapOutgoingMessage() { - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCorrelationID() { - return correlationID; - } - - public void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - public String getCambriaPartition() { - return cambriaPartition; - } - - public void setCambriaPartition(String cambriaPartition) { - this.cambriaPartition = cambriaPartition; - } - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public Body getBody() { - return body; - } - - public void setBody(Body body) { - this.body = body; - } - - @Override - public String toString() { - return "DmaapOutgoingMessage{" + - "cambriaPartition='" + cambriaPartition + '\'' + - ", rpcName='" + rpcName + '\'' + - ", body=" + body + - '}'; - } - - @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) - @JsonIgnoreProperties(ignoreUnknown = true) - public static class Body { - public Body() { - } - - public Body(Object output) { - this.output = output; - } - - @JsonProperty("output") - private Object output; - - public Object getOutput() { - return output; - } - - public void setOutput(Object body) { - this.output = body; - } - - @Override - public String toString() { - return "Body{" + - "output=" + output + - '}'; - } - } -} - diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/MessageAdapter.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/MessageAdapter.java deleted file mode 100644 index 91836cb40..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/MessageAdapter.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.messageadapter; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashSet; -import java.util.Properties; - -public class MessageAdapter { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapter.class); - - private final String PROP_APPC_OAM_DISABLED = "appc.OAM.disabled"; - private final String PROP_APPC_OAM_TOPIC_WRITE = "appc.OAM.topic.write"; - private String PROP_APPC_OAM_CLIENT_KEY = "appc.OAM.client.key"; - private String PROP_APPC_OAM_CLIENT_SECRET = "appc.OAM.client.secret"; - private String PROP_APPC_OAM_POOLMEMBERS = "appc.OAM.poolMembers"; - - private Producer producer; - private String partition; - private Configuration configuration; - private HashSet pool; - private String writeTopic; - private String apiKey; - private String apiSecret; - private boolean isDisabled; - - /** - * Initialize producer client to post messages using configuration properties. - */ - public void init() { - configuration = ConfigurationFactory.getConfiguration(); - Properties properties = configuration.getProperties(); - updateProperties(properties); - - if (isAppcOamPropsListenerEnabled()) { - createProducer(); - } else { - logger.warn(String.format("The listener %s is disabled and will not be run", "appc.OAM")); - } - } - - /** - * Create producer using MessageAdapterFactory which is found through bundle context. - */ - void createProducer() { - BundleContext ctx = FrameworkUtil.getBundle(MessageAdapter.class).getBundleContext(); - if (ctx == null) { - logger.warn("MessageAdapter cannot create producer due to no bundle context."); - return; - } - - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef == null) { - logger.warn("MessageAdapter cannot create producer due to no MessageAdapterFactory service reference."); - return; - } - - Producer localProducer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic, - apiKey, apiSecret); - - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - localProducer.useHttps(true); - break; - } - } - - producer = localProducer; - - logger.debug("MessageAdapter created producer."); - } - - /** - * Read property value to set writeTopic, apiKey, apiSecret and pool. - * - * @param props of configuration - */ - private void updateProperties(Properties props) { - logger.trace("Entering to updateProperties with Properties = " + ObjectUtils.toString(props)); - - pool = new HashSet<>(); - if (props != null) { - isDisabled = Boolean.parseBoolean(props.getProperty(PROP_APPC_OAM_DISABLED)); - writeTopic = props.getProperty(PROP_APPC_OAM_TOPIC_WRITE); - apiKey = props.getProperty(PROP_APPC_OAM_CLIENT_KEY); - apiSecret = props.getProperty(PROP_APPC_OAM_CLIENT_SECRET); - String hostnames = props.getProperty(PROP_APPC_OAM_POOLMEMBERS); - if (hostnames != null && !hostnames.isEmpty()) { - for (String name : hostnames.split(",")) { - pool.add(name); - } - } - } - } - - /** - * Get producer. If it is null, call createProducer to create it again. - * - * @return Producer - */ - Producer getProducer() { - if (producer == null) { - // In case, producer was not properly set yet, set it again. - logger.info("Calling createProducer as producer is null."); - createProducer(); - } - - return producer; - } - - /** - * Posts message to UEB. As UEB accepts only json messages this method first convert uebMessage to json format - * and post it to UEB. - * - * @param oamContext response data that based on it a message will be send to UEB (the format of the message that - * will be sent to UEB based on the action and its YANG domainmodel). - */ - public void post(OAMContext oamContext) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(oamContext)); - } - - boolean success; - String jsonMessage; - try { - jsonMessage = Converter.convAsyncResponseToUebOutgoingMessageJsonString(oamContext); - if (logger.isDebugEnabled()) { - logger.debug("UEB Response = " + jsonMessage); - } - - Producer myProducer = getProducer(); - success = myProducer != null && myProducer.post(this.partition, jsonMessage); - } catch (JsonProcessingException e1) { - logger.error("Error generating Json from UEB message " + e1.getMessage()); - success = false; - } catch (Exception e) { - logger.error("Error sending message to UEB " + e.getMessage(), e); - success = false; - } - - if (logger.isTraceEnabled()) { - logger.trace("Exiting from post with (success = " + ObjectUtils.toString(success) + ")"); - } - } - - private boolean isAppcOamPropsListenerEnabled() { - return !isDisabled; - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/OAMContext.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/OAMContext.java deleted file mode 100644 index 3af395923..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/OAMContext.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.messageadapter; - - - - -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.*; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeaderBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status;import org.onap.appc.oam.AppcOam; - -public class OAMContext { - - private AppcOam.RPC rpcName; - private CommonHeader commonHeader; - private Status status; - - - public AppcOam.RPC getRpcName() { - return rpcName; - } - - public void setRpcName(AppcOam.RPC rpcName) { - this.rpcName = rpcName; - } - - public CommonHeader getCommonHeader() { - return commonHeader; - } - - public void setCommonHeader(CommonHeader commonHeader) { - this.commonHeader = commonHeader; - } - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - - @Override - public String toString() { - return "OAMContext {" + - "rpcName=" + rpcName + - ", commonHeader=" + commonHeader + - ", status=" + status + - '}'; - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseActionRunnable.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseActionRunnable.java deleted file mode 100644 index 927334670..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseActionRunnable.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Future; - -/** - * Base runnable actions for OAM APIs, such as maintenance mode, restart, start and stop API. - * - *

This class holds the general action async handling methods for all OAM APIs. - *

Specific API action runnable will overwrite the general methods to add specific behaviors. - * - *

Subclass constructor must set the following class variables: - *
- actionName - *
- auditMsg - *
- finalState - */ -public abstract class BaseActionRunnable extends BaseCommon implements Runnable { - /** Abort due to rejection message format with flexible operation name */ - final String ABORT_MESSAGE_FORMAT = "Aborting %s operation due to %s."; - /** Timeout message format with flexible operation name */ - final String TIMEOUT_MESSAGE_FORMAT = "%s operation has reached timeout %d milliseconds."; - /** Failure message format with flexible number of bundles */ - final String BUNDLE_OPERATION_FAILED_FORMAT = "%d bundle(s) failed, see logs for details."; - final String NEW_RPC_OPERATION_REQUEST = "new %s operation request"; - final String DUE_TO_EXECUTION_ERROR = "due to execution error."; - - private boolean isWaiting = false; - long startTimeMs = 0; - long timeoutMs = 0; - boolean doTimeoutChecking = false; - - String actionName = "Need to be reset"; - Msg auditMsg; - AppcOamStates finalState; - - BaseProcessor myParent; - Map> bundleNameToFuture = new HashMap<>(); - - /** - * Constructor - * - * @param parent BaseProcessor who has called this constructor. - */ - BaseActionRunnable(BaseProcessor parent) { - super(parent.logger, parent.configurationHelper, parent.stateHelper, parent.operationHelper); - - rpc = parent.rpc; - commonHeader = parent.commonHeader; - myParent = parent; - setTimeoutValues(); - } - - /** - * Collect the timeout value for this {@link BaseActionRunnable} - */ - void setTimeoutValues() { - startTime = myParent.startTime; - timeoutMs = myParent.getTimeoutMilliseconds(); - doTimeoutChecking = timeoutMs != 0; - if (doTimeoutChecking) { - startTimeMs = startTime.getTime(); - } - logDebug("%s action runnable check timeout (%s) with timeout (%d)ms, and startMs (%d)", - rpc.name(), Boolean.toString(doTimeoutChecking), timeoutMs, startTimeMs); - } - - - /** - * Abort operation handling due to outside interruption, does
- * - set ABORT status
- * - send notification message
- * - add audit log - * - * @param newRpc of the new AppcOam.RPC operation. - */ - void abortRunnable(final AppcOam.RPC newRpc) { - resetLogProperties(false); - - String additionalMsg = String.format(NEW_RPC_OPERATION_REQUEST, newRpc); - logDebug("%s action aborted due to %s", rpc.name(), additionalMsg); - setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), additionalMsg)); - operationHelper.sendNotificationMessage(rpc, commonHeader, status); - auditInfoLog(auditMsg); - - resetLogProperties(true); - } - - @Override - public void run() { - try { - setInitialLogProperties(); - logDebug(String.format("===========in %s run (waiting: %s)=======", - actionName, Boolean.toString(isWaiting))); - - if (isWaiting) { - if (!checkState()) { - keepWaiting(); - } - } else { - if (doAction()) { - isWaiting = !checkState(); - } else { - postDoAction(false); - } - } - } catch (Exception e) { - logDebug(String.format("%s got exception %s", actionName, e.getMessage())); - logger.error(actionName + " exception", e); - - } finally { - clearRequestLogProperties(); - } - } - - /** - * Keep waiting to be override by children classes for different behaviors. - * Timeout is validated here. - */ - void keepWaiting() { - logDebug(String.format("%s runnable waiting, current state is %s.", - actionName, stateHelper.getCurrentOamState())); - - isTimeout("keepWaiting"); - } - - /** - * Check if the timeout milliseconds has reached. - * - * @param parentName String of the caller, for logging purpose. - * @return true if the timeout has reached, otherwise false. - */ - boolean isTimeout(String parentName) { - logDebug(String.format("%s task isTimeout called from %s", actionName, parentName)); - if (doTimeoutChecking - && System.currentTimeMillis() - startTimeMs > timeoutMs) { - logger.error(String.format("%s operation timeout (%d) ms has reached, abort with error state.", - actionName, timeoutMs)); - - setStatus(OAMCommandStatus.TIMEOUT, String.format(TIMEOUT_MESSAGE_FORMAT, rpc.name(), timeoutMs)); - postAction(AppcOamStates.Error); - return true; - } - return false; - } - - /** - * Check if all bundle operations are successful through BundleHelper. - * If there's failed bundler operation, set error status and trigger postAction with Error state. - * - * @return true if bundler operations have failure, otherwise false. - */ - boolean hasBundleOperationFailure() { - long failedTask = myParent.bundleHelper.getFailedMetrics(bundleNameToFuture); - if (failedTask == 0) { - return false; - } - - setStatus(OAMCommandStatus.UNEXPECTED_ERROR, String.format(BUNDLE_OPERATION_FAILED_FORMAT, failedTask)); - postAction(AppcOamStates.Error); - return true; - } - - /** - * Set class status to ABORT with abort message. - */ - void setAbortStatus() { - setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), DUE_TO_EXECUTION_ERROR)); - } - - /** - * Final handling. The thread is cancelled. - * - * @param setState boolean to indicate if set OAM state or not - */ - void postDoAction(boolean setState) { - logDebug(String.format("Finished %s task", actionName)); - } - - /** - * Handling for after doAction. does post notification, issue audit log and set OAM state based on input. - * - * @param state of AppcOamState to be set as OAM state when it is not null. - */ - void postAction(AppcOamStates state) { - operationHelper.sendNotificationMessage(rpc, commonHeader, status); - - if (state != null) { - stateHelper.setState(state); - } - - auditInfoLog(auditMsg); - - myParent.cancelAsyncTask(); - } - - /** - * Check state - * - * @return true if final state reached, otherwise return false - */ - boolean checkState() { - if (isTimeout("checkState")) { - myParent.bundleHelper.cancelUnfinished(bundleNameToFuture); - return true; - } - - if (!myParent.bundleHelper.isAllTaskDone(bundleNameToFuture)) { - return false; - } - - if (hasBundleOperationFailure()) { - return true; - } - - if (stateHelper.getBundlesState() == finalState) { - setStatus(OAMCommandStatus.SUCCESS); - postDoAction(true); - return true; - } - return false; - } - - abstract boolean doAction(); -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseCommon.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseCommon.java deleted file mode 100644 index 93e79dd2f..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseCommon.java +++ /dev/null @@ -1,265 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.i18n.EELFResourceManager; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.StatusBuilder; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.i18n.Msg; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.time.Instant; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -/** - * Common handling methods of
- * - BaseProcessor (for REST sync handling)
- * - BaseActionRunnable (for REST async handling) - */ -public abstract class BaseCommon { - final EELFLogger logger; - final ConfigurationHelper configurationHelper; - final StateHelper stateHelper; - final OperationHelper operationHelper; - - Status status; - Date startTime; - - AppcOam.RPC rpc; - CommonHeader commonHeader; - - private final List MDC_KEYS = Arrays.asList( - LoggingConstants.MDCKeys.PARTNER_NAME, - LoggingConstants.MDCKeys.SERVER_NAME, - MDC_INSTANCE_UUID, - MDC_KEY_REQUEST_ID, - MDC_SERVER_FQDN, - MDC_SERVER_IP_ADDRESS, - MDC_SERVICE_NAME - ); - private Map oldMdcContent = new HashMap<>(); - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelperIn for property reading - * @param stateHelperIn for APP-C OAM state checking - * @param operationHelperIn for operational helper - */ - BaseCommon(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn, - OperationHelper operationHelperIn) { - logger = eelfLogger; - configurationHelper = configurationHelperIn; - stateHelper = stateHelperIn; - operationHelper = operationHelperIn; - } - - /** - * Audit log the passed in message at INFO level. - * @param msg the Msg to be audit logged. - */ - void auditInfoLog(Msg msg) { - LoggingUtils.auditInfo(startTime.toInstant(), - Instant.now(), - String.valueOf(status.getCode()), - status.getMessage(), - getClass().getCanonicalName(), - msg, - configurationHelper.getAppcName(), - stateHelper.getCurrentOamState().toString() - ); - } - - /** - * Set MDC properties. - */ - public final void setInitialLogProperties() { - MDC.put(MDC_KEY_REQUEST_ID, commonHeader.getRequestId()); - MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, commonHeader.getOriginatorId()); - MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future - MDC.put(MDC_SERVICE_NAME, rpc.name()); - try { - //!!!Don't change the following to a .getHostName() again please. It's wrong!MDC.put(MDC_SERVER_FQDN, - // InetAddress.getLocalHost().getCanonicalHostName()); - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); - } catch (Exception e) { - logger.error("MDC constant error", e); - } - } - - /** - * Clear MDC properties. - */ - public final void clearRequestLogProperties() { - for (String key : MDC_KEYS) { - try { - MDC.remove(key); - } catch (Exception e) { - logger.error( - String.format("Unable to clear the Log properties (%s) due to exception: %s", key, e.getMessage())); - } - } - } - - /** - * Reset MDC log properties based on passed in condition. does:
- * - persist existing MDC setting and set my MDC log properties
- * - or re-apply persisted MDC log properties - * @param useMdcMap boolean to indicate whether to persist the existing MDC setting and set my MDC log properties, - * or to re-apply the persisted MDC log properties. - */ - void resetLogProperties(boolean useMdcMap) { - if (useMdcMap) { - for (Map.Entry aEntry : oldMdcContent.entrySet()) { - MDC.put(aEntry.getKey(), aEntry.getValue()); - } - return; - } - - // persist existing log properties and set my log properties - oldMdcContent.clear(); - for (String key : MDC_KEYS) { - String value = MDC.get(key); - if (value != null) { - oldMdcContent.put(key, value); - } - } - setInitialLogProperties(); - } - - /** - * Set class status by calling setStatus(OAMCommandStatus, Params) with null paramter. - * @see #setStatus(OAMCommandStatus, String) - * - * @param oamCommandStatus of the to be set new state - */ - void setStatus(OAMCommandStatus oamCommandStatus) { - setStatus(oamCommandStatus, null); - } - - /** - * Create Status based on the passed in parameter, then set the class status with it. - * - * @param oamCommandStatus of the current OAM command status - * @param message to be set in the new status - */ - void setStatus(OAMCommandStatus oamCommandStatus, String message) { - Params params = new Params().addParam("errorMsg", message); - - StatusBuilder statusBuilder = new StatusBuilder(); - statusBuilder.setCode(oamCommandStatus.getResponseCode()); - if (params != null) { - statusBuilder.setMessage(oamCommandStatus.getFormattedMessage(params)); - } else { - statusBuilder.setMessage(oamCommandStatus.getResponseMessage()); - } - - status = statusBuilder.build(); - } - - /** - * Set class status with error status calculated from the passed in paremeter - * and audit log the error message. - * @param t of the error Throwable. - */ - void setErrorStatus(Throwable t) { - resetLogProperties(false); - - final String appName = configurationHelper.getAppcName(); - String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString(); - - OAMCommandStatus oamCommandStatus; - String errorMessage; - if (t instanceof InvalidInputException) { - oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER; - errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_INVALID_INPUT, t.getMessage()); - } else if (t instanceof InvalidStateException) { - exceptionMessage = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, - rpc.getAppcOperation(), appName, stateHelper.getCurrentOamState()); - oamCommandStatus = OAMCommandStatus.REJECTED; - errorMessage = EELFResourceManager.format(Msg.INVALID_STATE_TRANSITION, exceptionMessage); - } else if (t instanceof TimeoutException) { - oamCommandStatus = OAMCommandStatus.TIMEOUT; - errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t, - appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage); - } else { - oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; - errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t, - appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage); - } - - setStatus(oamCommandStatus, exceptionMessage); - - LoggingUtils.logErrorMessage( - String.valueOf(status.getCode()), - status.getMessage(), - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.APPC_OAM_PROVIDER, - errorMessage, - AppcOam.class.getCanonicalName()); - - resetLogProperties(true); - } - - /** - * Genral debug log when debug logging level is enabled. - * @param message of the log message format - * @param args of the objects listed in the message format - */ - void logDebug(String message, Object... args) { - if (logger.isDebugEnabled()) { - logger.debug(String.format(message, args)); - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java deleted file mode 100644 index 414b94605..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseProcessor.java +++ /dev/null @@ -1,216 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.BundleHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -import java.util.Date; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Base processor for OAM APIs, such as maintenance mode, restart, start and stop API. - * - *

This class holds the general API request sync handling methods for all OAM APIs. - *

Specific API processor will overwrite the general methods to add specific behaviors. - */ -public abstract class BaseProcessor extends BaseCommon { - /** lock to serialize incoming OAM operations. */ - private static final Object LOCK = new Object(); - - final AsyncTaskHelper asyncTaskHelper; - final BundleHelper bundleHelper; - - /** the requestTimeoutSeconds to use for this OAM operation */ - private Integer requestTimeoutSeconds; - Msg auditMsg; - BaseActionRunnable runnable; - private Future scheduledRunnable = null; - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelperIn for property reading - * @param stateHelperIn for APP-C OAM state checking - * @param asyncTaskHelperIn for scheduling async task - * @param operationHelperIn for operational helper - */ - BaseProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn, - AsyncTaskHelper asyncTaskHelperIn, - OperationHelper operationHelperIn) { - super(eelfLogger, configurationHelperIn, stateHelperIn, operationHelperIn); - - asyncTaskHelper = asyncTaskHelperIn; - bundleHelper = new BundleHelper(eelfLogger, configurationHelper, stateHelper); - } - - /** - * Process synch handling and schedule asynch task - * - * @param requestInput of REST API request - * @return Status of new APP-C OAM state - */ - public Status processRequest(final Object requestInput) { - startTime = new Date(); - commonHeader = operationHelper.getCommonHeader(requestInput); - setStatus(OAMCommandStatus.ACCEPTED); - - try { - preProcess(requestInput); - scheduleAsyncTask(); - } catch (Exception e) { - setErrorStatus(e); - } finally { - postProcess(); - } - - return status; - } - - /** - * Preprocess before actual handling of the REST API call. Does: - *

- commonHeader validation - *

- get NextState as well as validate if next state is valid - *

- set logging properties - *

- set appcCurrentState to next state - * - * @throws InvalidInputException when commonHeader validation failed - * @throws APPCException when state validation failed - */ - protected void preProcess(final Object requestInput) - throws InvalidInputException, APPCException, InvalidStateException,InterruptedException,TimeoutException { - setInitialLogProperties(); - operationHelper.isInputValid(requestInput); - - //The OAM request may specify timeout value - requestTimeoutSeconds = operationHelper.getParamRequestTimeout(requestInput); - - //All OAM operation pass through here first to validate if an OAM state change is allowed. - //If a state change is allowed cancel the occurring OAM (if any) before starting this one. - //we will synchronized so that only one can do this at any given time. - synchronized(LOCK) { - AppcOamStates currentOamState = stateHelper.getCurrentOamState(); - - //make sure this OAM operation can transition to the desired OAM operation - AppcOamStates nextState = operationHelper.getNextState( - rpc.getAppcOperation(), currentOamState); - - stateHelper.setState(nextState); - - - try { - //cancel the BaseActionRunnable currently executing - //it got to be completely terminated before proceeding - asyncTaskHelper.cancelBaseActionRunnable( - rpc, - currentOamState, - getTimeoutMilliseconds(), - TimeUnit.MILLISECONDS - ); - } catch (TimeoutException e) { - stateHelper.setState(AppcOamStates.Error); - throw e; - } - - - } - } - - /** - * Post process includes audit logging as well as clear MDC properties. - */ - private void postProcess() { - auditInfoLog(auditMsg); - clearRequestLogProperties(); - } - - /** - * Schedule async task through AsyncTaskHelper. - */ - protected void scheduleAsyncTask() { - if (runnable == null) { - logger.error(String.format( - "Skipped schedule async task for rpc(%s) due to runnable is null", rpc.name())); - return; - } - - scheduledRunnable = asyncTaskHelper.scheduleBaseRunnable( - runnable, runnable::abortRunnable, getInitialDelayMillis(), getDelayMillis()); - } - - - /** - * The timeout for this OAM operation. The timeout source is chosen in the following order: - * request, config file, default value - * @return - the timeout for this OAM operation. - */ - long getTimeoutMilliseconds() { - return configurationHelper.getOAMOperationTimeoutValue(this.requestTimeoutSeconds); - } - - - /** - * @return initialDelayMillis - the time to delay first execution of {@link BaseActionRunnable} - */ - protected long getInitialDelayMillis(){ - return 0L; - } - - /** - * @return delayMillis the delay between the consecutive executions of {@link BaseActionRunnable} - */ - private long getDelayMillis(){ - return 1000L; - } - - /** - * Cancel the scheduled {@link BaseActionRunnable} through AsyncTaskHelper - */ - void cancelAsyncTask() { - if (scheduledRunnable == null) { - logger.error(String.format( - "Skipped cancel schedule async task for rpc(%s) due to scheduledRunnable is null", rpc.name())); - return; - } - scheduledRunnable.cancel(true); - } - -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java deleted file mode 100644 index 23f9fd130..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamMmodeProcessor.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -import java.util.concurrent.TimeoutException; - -/** - * Processor to handle maintenance mode OAM API. - */ -public class OamMmodeProcessor extends BaseProcessor { - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelper for property reading - * @param stateHelper for APP-C OAM state checking - * @param asyncTaskHelper for scheduling async task - * @param operationHelper for operational helper - */ - public OamMmodeProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelper, - StateHelper stateHelper, - AsyncTaskHelper asyncTaskHelper, - OperationHelper operationHelper) { - super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - - rpc = AppcOam.RPC.maintenance_mode; - auditMsg = Msg.OAM_OPERATION_ENTERING_MAINTENANCE_MODE; - } - - @Override - protected void preProcess(final Object requestInput) - throws InvalidInputException, InvalidStateException, APPCException, InterruptedException, TimeoutException { - super.preProcess(requestInput); - - //Close the gate so that no more new LCM request will be excepted. - LCMStateManager lcmStateManager = operationHelper.getService(LCMStateManager.class); - lcmStateManager.disableLCMOperations(); - } - - @Override - protected void scheduleAsyncTask() { - runnable = new MyRunnable(this); - super.scheduleAsyncTask(); - } - - /** - * {@inheritDoc} - * For maintenance mode we want a longer delay before initial execution of {@link BaseActionRunnable} - * so that any accepted LCM actions have time to git scheduled in the Dispatcher. - */ - @Override - protected long getInitialDelayMillis(){ - //wait ten seconds before - return 10000L; - } - - /** - * This runnable does the async handling for the maintenance mode REST API, and will be scheduled to run - * until terminating condition reaches. - * - *

The runnable will continue run if:
- * - the runnable is not canceled outside
- * - the in progress LCM request count is not zero
- *

When LCM request count reaches to zero, this runnable will:
- * - post message through operationHelper
- * - set APP-C OAM state to maintenance mode
- * - audit log the state
- * - terminate this runnable itself
- */ - class MyRunnable extends BaseActionRunnable { - private int inprogressRequestCount; - - MyRunnable(BaseProcessor parent) { - super(parent); - - actionName = "OAM Maintenance mode"; - auditMsg = Msg.OAM_OPERATION_MAINTENANCE_MODE; - finalState = AppcOamStates.MaintenanceMode; - } - - @Override - boolean doAction() { - // always return true, so that we can check the LCM request count - return true; - } - - @Override - boolean checkState() { - logDebug(String.format("Executing %s task", actionName)); - - - boolean hasError = false; - try { - inprogressRequestCount = getInprogressLCMRequestCount(); - if (inprogressRequestCount > 0) { - // if there are still LCM request in progress, keep waiting - return false; - } - - setStatus(OAMCommandStatus.SUCCESS); - } catch (Exception e) { - setErrorStatus(e); - hasError = true; - } - - postAction(hasError ? AppcOamStates.Error : finalState); - return true; - } - - /** - * Get in progress LCM request count through RequestHandler. - * @return thecount of in progress LCM request - * @throws APPCException if RequestHandler throws it. - */ - private int getInprogressLCMRequestCount() throws APPCException { - RequestHandler requestHandler = operationHelper.getService(RequestHandler.class); - - if (requestHandler == null) { - return 0; - } - - return requestHandler.getInprogressRequestCount(); - } - - @Override - void keepWaiting() { - logDebug("The application '%s' has '%s' outstanding LCM request to complete" + - " before coming to a complete maintenance_mode.", - configurationHelper.getAppcName(), inprogressRequestCount); - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamRestartProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamRestartProcessor.java deleted file mode 100644 index b23b4d2aa..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamRestartProcessor.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -/** - * Processor to handle restart OAM API. - */ -public class OamRestartProcessor extends BaseProcessor { - /** - * Action phases: - *
-ToStop: call bundles stop - *
-Stopped: check if all bundle state reached stopped - *
-ToStart: call bundles start - *
-Started: action is full completed - *
-Error: indication of error, such as timeout reached, bundler operation failure and etc. - */ - private enum ActionPhases { - ToStop, - Stopped, - ToStart, - Started, - Error - } - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelper for property reading - * @param stateHelper for APP-C OAM state checking - * @param asyncTaskHelper for scheduling async task - * @param operationHelper for operational helper - */ - public OamRestartProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelper, - StateHelper stateHelper, - AsyncTaskHelper asyncTaskHelper, - OperationHelper operationHelper) { - super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - - rpc = AppcOam.RPC.restart; - auditMsg = Msg.OAM_OPERATION_RESTARTING; - } - - @Override - protected void scheduleAsyncTask() { - runnable = new MyRunnable(this); - super.scheduleAsyncTask(); - } - - /** - * This runnable does the async handling for the restart REST API. And it will be scheduled to run one time. - * - *

This runnable will the following operations:
- * - do APP-C OAM bundle stop and then start through BundlerHelper
- * - and always enable LCM operation handling (which can be disabled through maintenance mode API).
- *

Once above operations are done, the runnale will
- * - post message through operatonHelper
- * - set APP-C OAM state to started
- * - audit log the state
- */ - class MyRunnable extends BaseActionRunnable { - - ActionPhases currentPhase = ActionPhases.ToStop; - private LCMStateManager lcmStateManager; - - MyRunnable(BaseProcessor parent) { - super(parent); - - actionName = "OAM Restart"; - auditMsg = Msg.OAM_OPERATION_RESTARTED; - finalState = AppcOamStates.Started; - } - - /** - * Do restart action, include stop then start and always enable LCM operation. - * @return true if action is successful, false when aciton is failed or aborted - */ - @Override - boolean doAction() { - logDebug(String.format("Executing %s task at phase (%s)", - actionName, currentPhase == null ? "null" : currentPhase.name())); - - boolean isBundleOperationCompleted = true; - try { - switch (currentPhase) { - case ToStop: - isBundleOperationCompleted = bundleHelper.bundleOperations( - AppcOam.RPC.stop, bundleNameToFuture, myParent.asyncTaskHelper, this); - currentPhase = ActionPhases.Stopped; - break; - case Stopped: - // check state - AppcOamStates currentState = stateHelper.getBundlesState(); - if (currentState == AppcOamStates.Stopped) { - currentPhase = ActionPhases.ToStart; - } else { - logDebug(String.format("%s task is waiting in stopped phase, current state is %s", - actionName, currentState)); - } - break; - case ToStart: - isBundleOperationCompleted = bundleHelper.bundleOperations( - AppcOam.RPC.start, bundleNameToFuture, myParent.asyncTaskHelper, this); - currentPhase = ActionPhases.Started; - break; - case Error: - // do nothing - break; - default: - // Should not reach log it and return false; - logger.error("%s task doAction reached %s phase. not supported. return false.", - actionName, currentPhase.name()); - stateHelper.setState(AppcOamStates.Error); - return false; - } - - if (isTimeout("restart doAction") - || hasBundleOperationFailure()) { - currentPhase = ActionPhases.Error; - return true; - } - if (isBundleOperationCompleted) { - return true; - } - - setAbortStatus(); - } catch (APPCException e) { - setErrorStatus(e); - stateHelper.setState(AppcOamStates.Error); - } - - return false; - } - - /** - * With additional to get the LCMStateManager service - * @see BaseActionRunnable#checkState() - */ - @Override - boolean checkState() { - switch (currentPhase) { - case Started: - try { - lcmStateManager = operationHelper.getService(LCMStateManager.class); - return super.checkState(); - } catch (APPCException e) { - logDebug("LCMStateManager is not available."); - } - break; - default: - // in all the other ActionPhase, we want the run go back to doAction - return true; - } - return false; - } - - /** - * Final handling. The thread is cancelled. - * @param setState boolean to indicate if set OAM state or not - */ - @Override - void postDoAction(boolean setState) { - AppcOamStates newState = null; - if (setState) { - logDebug("Always enable LCM operation"); - lcmStateManager.enableLCMOperations(); - newState = finalState; - } - postAction(newState); - super.postDoAction(setState); - } - - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStartProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStartProcessor.java deleted file mode 100644 index 2ca353244..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStartProcessor.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -/** - * Processor to handle start OAM API. - */ -public class OamStartProcessor extends BaseProcessor { - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelper for property reading - * @param stateHelper for APP-C OAM state checking - * @param asyncTaskHelper for scheduling async task - * @param operationHelper for operational helper - */ - public OamStartProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelper, - StateHelper stateHelper, - AsyncTaskHelper asyncTaskHelper, - OperationHelper operationHelper) { - super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - - rpc = AppcOam.RPC.start; - auditMsg = Msg.OAM_OPERATION_STARTING; - } - - @Override - protected void scheduleAsyncTask() { - runnable = new MyRunnable(this); - super.scheduleAsyncTask(); - } - - /** - * This runnable does the async handling for the start REST API. And it will be scheduled to run one time. - * - *

This runnable will the following operations:
- * - do APP-C OAM bundle start through BundlerHelper
- * - and always enable LCM operation handling (which can be disabled through maintenance mode API).
- *

Once above operations are done, the runnale will
- * - post message through operatonHelper
- * - set APP-C OAM state to started
- * - audit log the state
- */ - class MyRunnable extends BaseActionRunnable { - - private LCMStateManager lcmStateManager; - - MyRunnable(BaseProcessor parent) { - super(parent); - actionName = "OAM Start"; - auditMsg = Msg.OAM_OPERATION_STARTED; - finalState = AppcOamStates.Started; - } - - /** - * Do start action, include start bundle if needed and always enable LCM operation. - * @return true if action is successful, false when aciton is failed or aborted - */ - @Override - boolean doAction() { - logDebug(String.format("Executing %s task", actionName)); - - boolean isBundleOperationCompleted = true; - try { - if (stateHelper.getState() != AppcOamStates.Started) { - logDebug("Start - APPC OAM state is not started, start the bundles"); - isBundleOperationCompleted = bundleHelper.bundleOperations( - rpc, bundleNameToFuture, myParent.asyncTaskHelper, this); - } - - if (isBundleOperationCompleted) { - return true; - } - - setAbortStatus(); - } catch (APPCException e) { - setErrorStatus(e); - stateHelper.setState(AppcOamStates.Error); - } - - return false; - } - - /** - * With additional to get the LCMStateManager service - * @see BaseActionRunnable#checkState() - */ - @Override - boolean checkState() { - try { - lcmStateManager = operationHelper.getService(LCMStateManager.class); - return super.checkState(); - } catch (APPCException e) { - logDebug("LCMStateManager is not available."); - return false; - } - } - - /** - * Final handling - * @param setState boolean to indicate if set OAM state or not - */ - @Override - void postDoAction(boolean setState) { - AppcOamStates newState = null; - if (setState) { - logDebug("Always enable LCM operation"); - lcmStateManager.enableLCMOperations(); - newState = finalState; - } - postAction(newState); - super.postDoAction(setState); - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStopProcessor.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStopProcessor.java deleted file mode 100644 index 8710e0f08..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/OamStopProcessor.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; - -/** - * Processor to handle stop OAM API. - */ -public class OamStopProcessor extends BaseProcessor { - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelper for property reading - * @param stateHelper for APP-C OAM state checking - * @param asyncTaskHelper for scheduling async task - * @param operationHelper for operational helper - */ - public OamStopProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelper, - StateHelper stateHelper, - AsyncTaskHelper asyncTaskHelper, - OperationHelper operationHelper) { - super(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper); - - rpc = AppcOam.RPC.stop; - auditMsg = Msg.OAM_OPERATION_STOPPING; - } - - - @Override - protected void scheduleAsyncTask() { - runnable = new MyRunnable(this); - super.scheduleAsyncTask(); - } - - /** - * This runnable does the async handling for the stop REST API. And it will be scheduled to run one time. - * - *

This runnable will the following operations:
- * - do APP-C OAM bundle stop and then refresh through BundlerHelper
- *

Once above operations are done, the runnale will
- * - post message through operatonHelper
- * - set APP-C OAM state to started
- * - audit log the state
- */ - class MyRunnable extends BaseActionRunnable { - - MyRunnable(BaseProcessor parent) { - super(parent); - actionName = "OAM Stop"; - auditMsg = Msg.OAM_OPERATION_STOPPED; - finalState = AppcOamStates.Stopped; - } - - /** - * Do stop action, include stop bundle . - * @return true if action is successful, false when aciton is failed. - */ - @Override - boolean doAction() { - logDebug(String.format("Executing %s task", actionName)); - - try { - boolean isBundleOperationCompleted = bundleHelper.bundleOperations( - rpc, bundleNameToFuture, myParent.asyncTaskHelper, this); - if (isBundleOperationCompleted) { - return true; - } - - setAbortStatus(); - } catch (APPCException e) { - setErrorStatus(e); - stateHelper.setState(AppcOamStates.Error); - } - return false; - } - - /** - * Final handling - * @param setState boolean to indicate if set OAM state or not - */ - @Override - void postDoAction(boolean setState) { - postAction(setState ? finalState : null); - super.postDoAction(setState); - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java deleted file mode 100644 index 2f74bf5a9..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java +++ /dev/null @@ -1,394 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.processor.BaseActionRunnable; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.osgi.framework.FrameworkUtil; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Consumer; - -/** - * The AsyncTaskHelper class manages an internal parent child data structure. The parent is a transient singleton, - * meaning only one can exist at any given time. The parent is scheduled with the - * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and is executed at configured interval. It can be - * terminated by using the {@link Future#cancel(boolean)} or the {@link Future#cancel(boolean)} returned from \ - * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)}. - *

- * The children are scheduled using {@link #submitBaseSubCallable(Callable)}} and can only be scheduled if a parent - * is scheduled. Children only execute once, but can be terminated preemptively by the {@link Future#cancel(boolean)} - * returned from {@link #submitBaseSubCallable(Callable)} or indirectly by terminating the parent via the method - * described above. - *

- * This class augments the meaning of {@link Future#isDone()} in that it guarantees that this method only returns true - * if the scheduled {@link Runnable} or {@link Callable} is not currently executing and is not going to execute in the - * future. This is different than the Java core implementation of {@link Future#isDone()} in which it will return - * true immediately after the {@link Future#cancel(boolean)} is called. Even if a Thread is actively executing the - * {@link Runnable} or {@link Callable} and has not return yet. See Java BUG JDK-8073704 - *

- * The parent {@link Future#isDone()} has an additional augmentation in that it will not return true until all of its - * children's {@link Future#isDone()} also return true. - * - */ -@SuppressWarnings("unchecked") -public class AsyncTaskHelper { - - private final EELFLogger logger; - private final ScheduledExecutorService scheduledExecutorService; - private final ThreadPoolExecutor bundleOperationService; - - /** Reference to {@link MyFuture} return from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} */ - private MyFuture backgroundBaseRunnableFuture; - - /** The cancel Callback from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} */ - private Consumer cancelCallBackForBaseRunnable; - - /** All Futures created by thus calls which have not completed -- {@link Future#isDone()} equals false */ - private Set myFutureSet = new HashSet<>(); - - /** - * Constructor - * @param eelfLogger of the logger - */ - public AsyncTaskHelper(EELFLogger eelfLogger) { - logger = eelfLogger; - - scheduledExecutorService = Executors.newSingleThreadScheduledExecutor( - (runnable) -> { - Bundle bundle = FrameworkUtil.getBundle(AppcOam.class); - return new Thread(runnable, bundle.getSymbolicName() + " scheduledExecutor"); - } - ); - - bundleOperationService = new ThreadPoolExecutor( - 0, - 10, - 10, - TimeUnit.SECONDS, - new LinkedBlockingQueue(), //BlockingQueue workQueue - (runnable) -> { - Bundle bundle = FrameworkUtil.getBundle(AppcOam.class); - return new Thread(runnable, bundle.getSymbolicName() + " bundle operation executor"); - } - ); - } - - /** - * Terminate the class ScheduledExecutorService - */ - public void close() { - logDebug("Start shutdown scheduleExcutorService."); - bundleOperationService.shutdownNow(); - scheduledExecutorService.shutdownNow(); - logDebug("Completed shutdown scheduleExcutorService."); - } - - - /** - * Cancel currently executing {@link BaseActionRunnable} if any. - * This method returns immediately if there is currently no {@link BaseActionRunnable} actively executing. - * @param rpcCausingAbort - The RPC causing the abort - * @param stateBeingAbborted - The current state being canceled - * @param timeout - The amount of time to wait for a cancel to complete - * @param timeUnit - The unit of time of timeout - * @throws TimeoutException - If {@link BaseActionRunnable} has not completely cancelled within the timeout period - * @throws InterruptedException - If the Thread waiting for the abort - */ - public synchronized void cancelBaseActionRunnable(final AppcOam.RPC rpcCausingAbort, - AppcOamStates stateBeingAbborted, - long timeout, TimeUnit timeUnit) - throws TimeoutException,InterruptedException { - - final MyFuture localBackgroundBaseRunnableFuture = backgroundBaseRunnableFuture; - final Consumer localCancelCallBackForBaseRunnable = cancelCallBackForBaseRunnable; - - if (localBackgroundBaseRunnableFuture == null || localBackgroundBaseRunnableFuture.isDone()) { - return; - } - - if (localCancelCallBackForBaseRunnable != null) { - localCancelCallBackForBaseRunnable.accept(rpcCausingAbort); - } - localBackgroundBaseRunnableFuture.cancel(true); - - long timeoutMillis = timeUnit.toMillis(timeout); - long expiryTime = System.currentTimeMillis() + timeoutMillis; - while (!(localBackgroundBaseRunnableFuture.isDone())) { - long sleepTime = expiryTime - System.currentTimeMillis(); - if (sleepTime < 1) { - break; - } - this.wait(sleepTime); - } - - if (!localBackgroundBaseRunnableFuture.isDone()) { - throw new TimeoutException(String.format("Unable to abort %s in timely manner.",stateBeingAbborted)); - } - } - - /** - * Schedule a {@link BaseActionRunnable} to begin async execution. This is the Parent {@link Runnable} for the - * children that are submitted by {@link #submitBaseSubCallable(Callable)} - * - * The currently executing {@link BaseActionRunnable} must fully be terminated before the next can be scheduled. - * This means all Tasks' {@link MyFuture#isDone()} must equal true and all threads must return to their respective - * thread pools. - * - * @param runnable of the to be scheduled service. - * @param cancelCallBack to be invoked when - * {@link #cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)} is invoked. - * @param initialDelayMillis the time to delay first execution - * @param delayMillis the delay between the termination of one - * execution and the commencement of the next - * @return The {@link BaseActionRunnable}'s {@link Future} - * @throws IllegalStateException if there is currently executing Task - */ - public synchronized Future scheduleBaseRunnable(final Runnable runnable, - final Consumer cancelCallBack, - long initialDelayMillis, - long delayMillis) - throws IllegalStateException { - - if (backgroundBaseRunnableFuture != null && !backgroundBaseRunnableFuture.isDone()) { - throw new IllegalStateException("Unable to schedule background task when one is already running. All task must fully terminated before another can be scheduled. "); - } - - this.cancelCallBackForBaseRunnable = cancelCallBack; - - backgroundBaseRunnableFuture = new MyFuture(runnable) { - /** - * augments the cancel operation to cancel all subTack too, - */ - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - boolean cancel; - synchronized (AsyncTaskHelper.this) { - cancel = super.cancel(mayInterruptIfRunning); - //clone the set to prevent java.util.ConcurrentModificationException. The synchronized prevents - //other threads from modifying this set, but not itself. The f->f.cancel may modify myFutureSet by - //removing an entry which breaks the iteration in the forEach. - (new HashSet(myFutureSet)) - .stream().filter(f->!this.equals(f)).forEach(f->f.cancel(mayInterruptIfRunning)); - } - return cancel; - } - - /** - * augments the isDone operation to return false until all subTask have completed too. - */ - @Override - public boolean isDone() { - synchronized (AsyncTaskHelper.this) { - return myFutureSet.isEmpty(); - } - } - }; - backgroundBaseRunnableFuture.setFuture( - scheduledExecutorService.scheduleWithFixedDelay( - backgroundBaseRunnableFuture, initialDelayMillis, delayMillis, TimeUnit.MILLISECONDS) - ); - return backgroundBaseRunnableFuture; - } - - /** - * Submits children {@link Callable} to be executed as soon as possible, A parent must have been scheduled - * previously via {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} - * @param callable the Callable to be submitted - * @return The {@link Callable}'s {@link Future} - */ - synchronized Future submitBaseSubCallable(final Callable callable) { - - if (backgroundBaseRunnableFuture == null - || backgroundBaseRunnableFuture.isCancelled() - || backgroundBaseRunnableFuture.isDone()){ - throw new IllegalStateException("Unable to schedule subCallable when a base Runnable is not running."); - } - - //Make sure the pool is ready to go - if(bundleOperationService.getPoolSize() != bundleOperationService.getMaximumPoolSize()){ - bundleOperationService.setCorePoolSize(bundleOperationService.getMaximumPoolSize()); - bundleOperationService.prestartAllCoreThreads(); - bundleOperationService.setCorePoolSize(0); - } - - MyFuture myFuture = new MyFuture(callable); - myFuture.setFuture(bundleOperationService.submit((Callable)myFuture)); - return myFuture; - } - - /** - * Genral debug log when debug logging level is enabled. - * @param message of the log message format - * @param args of the objects listed in the message format - */ - private void logDebug(String message, Object... args) { - if (logger.isDebugEnabled()) { - logger.debug(String.format(message, args)); - } - } - - /** - * This class has two purposes. First it insures {@link #isDone()} only returns true if the deligate is not - * currently running and will not be running in the future: See Java BUG JDK-8073704 Second this class maintains - * the {@link #myFutureSet } by insurring that itself is removed when {@link #isDone()} returns true. - * - * See {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and {@link #submitBaseSubCallable(Callable)} - * for usage of this class - */ - private class MyFuture implements Future, Runnable, Callable { - - private Future future; - private final Runnable runnable; - private final Callable callable; - private boolean isRunning; - - MyFuture(Runnable runnable) { - this.runnable = runnable; - this.callable = null; - myFutureSet.add(this); - } - - MyFuture(Callable callable) { - this.runnable = null; - this.callable = callable; - myFutureSet.add(this); - } - - void setFuture(Future future) { - this.future = future; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - synchronized (AsyncTaskHelper.this) { - if (!isRunning) { - myFutureSetRemove(); - } - - return future.cancel(mayInterruptIfRunning); - } - } - - @Override - public boolean isCancelled() { - synchronized (AsyncTaskHelper.this) { - return future.isCancelled(); - } - } - - @Override - public boolean isDone() { - synchronized (AsyncTaskHelper.this) { - return future.isDone() && !isRunning; - } - } - - @Override - public T get() throws InterruptedException, ExecutionException { - return future.get(); - } - - @Override - public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - return future.get(timeout, unit); - } - - @Override - public void run() { - synchronized (AsyncTaskHelper.this) { - if(future.isCancelled()){ - return; - } - isRunning = true; - } - try { - runnable.run(); - } finally { - synchronized (AsyncTaskHelper.this) { - isRunning = false; - - //The Base Runnable is expected to run again. - //unless it has been canceled. - //so only removed if it is canceled. - if (future.isCancelled()) { - myFutureSetRemove(); - } - } - } - } - - @Override - public T call() throws Exception { - synchronized (AsyncTaskHelper.this) { - if(future.isCancelled()){ - throw new CancellationException(); - } - isRunning = true; - } - try { - return callable.call(); - } finally { - synchronized (AsyncTaskHelper.this){ - isRunning = false; - myFutureSetRemove(); - } - } - } - - - /** - * Removes this from the the myFutureSet. - * When all the BaseActionRunnable is Done notify any thread waiting in - * {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)} - */ - void myFutureSetRemove(){ - synchronized (AsyncTaskHelper.this) { - myFutureSet.remove(this); - if(myFutureSet.isEmpty()){ - backgroundBaseRunnableFuture = null; - cancelCallBackForBaseRunnable = null; - AsyncTaskHelper.this.notifyAll(); - - } - } - } - - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleFilter.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleFilter.java deleted file mode 100644 index 6dd98f165..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleFilter.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import org.osgi.framework.Bundle; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - - - -/** - * - * Utility Class that splits a given bundleSet into two sets: bundleToStopSet and - * bundleToNotStopSet - * - * The bundleToStopSet is defined as: all bundles which match at least one of - * the stopRegexes but exceptRegexes none of the - * - * The bundleToNotStopSet is defined as all bundles which are not a member of - * the bundleToStopSet - * - */ -class BundleFilter { - - private final Map bundleToStopSet; - private final Map bundleToNotStopSet; - - - /** - * BundleFilter a bundle filter - * @param stopRegexes - An array of regular expression used to pick out which bundles are candidates for stopping - * @param exceptRegexes - An array of regular expression used to override which bundles are candidates for stopping - * @param bundles - An array of the bundle to be split into {@link #getBundlesToStop()} {@link #getBundlesToNotStop()} - */ - BundleFilter(String[] stopRegexes, String[] exceptRegexes, Bundle[] bundles) { - - Pattern[] stopPatterns = toPattern(stopRegexes); - Pattern[] exceptPatterns = toPattern(exceptRegexes); - - Map bundleToStop = new HashMap<>(); - Map bundleToNotStop = new HashMap<>(); - - for (Bundle bundle : bundles) { - String symbolicName = bundle.getSymbolicName(); - if (isMatch(symbolicName,stopPatterns) && !isMatch(symbolicName,exceptPatterns)) { - bundleToStop.put(symbolicName, bundle); - } else { - bundleToNotStop.put(symbolicName, bundle); - } - } - - this.bundleToStopSet = Collections.unmodifiableMap(bundleToStop); - this.bundleToNotStopSet = Collections.unmodifiableMap(bundleToNotStop); - } - - /** - * Determines if the value matches any of the regular expressions. - * - * @param value - * - the value that is to be matched - * @param patterns - * - the array of {@link Pattern} to match the value against - * @return boolean true if there is a match - */ - private boolean isMatch(String value,Pattern[] patterns) { - for (Pattern pattern : patterns) { - if (pattern.matcher(value).matches()) { - return true; - } - } - return false; - } - - /** - * This method converts an Array of regular expression in String form into a - * Array of {@link Pattern} - * - * @param regex - * - A string array of regular expressions - * @return Pattern Array of compiled regular expressions - */ - private Pattern[] toPattern(String[] regex) { - Pattern[] pattern = new Pattern[regex.length]; - for (int i = 0; i < regex.length; i++ ) { - pattern[i] = Pattern.compile(regex[i]); - } - return pattern; - } - - - /**@return Map of bundles that are to be stopped */ - Map getBundlesToStop(){ - return bundleToStopSet; - } - - /** - * - * @return Map of bundles that are not to be stopped - */ - Map getBundlesToNotStop() { - return bundleToNotStopSet; - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleHelper.java deleted file mode 100644 index 3a4602542..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/BundleHelper.java +++ /dev/null @@ -1,274 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.apache.commons.lang3.ArrayUtils; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.processor.BaseCommon; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.FrameworkUtil; - -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -/** - * Utility class provides general bundle operational helps. - */ -public class BundleHelper { - private final static String PROP_BUNDLE_TO_STOP = "appc.OAM.ToStop.properties"; - private final static String PROP_BUNDLES_TO_NOT_STOP = "appc.OAM.ToNotStop.properties"; - - private final EELFLogger logger; - private final StateHelper stateHelper; - private final ConfigurationHelper configurationHelper; - - /** - * Constructor - * - * @param eelfLogger of the logger - * @param configurationHelperIn of ConfigurationHelper instance - * @param stateHelperIn of StateHelper instance - */ - public BundleHelper(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn) { - logger = eelfLogger; - configurationHelper = configurationHelperIn; - stateHelper = stateHelperIn; - } - - /** - * Handle bundle operations, such as stop or start bundle. - * - * @param rpc enum indicate if the operation is to stop, start or restart - * @return boolean to indicate if the operation is successful (true) or failed (false) - * @throws APPCException when error occurs - */ - public boolean bundleOperations(AppcOam.RPC rpc, - Map> threads, - AsyncTaskHelper taskHelper, - BaseCommon baseCommon) - throws APPCException { - long mStartTime = System.currentTimeMillis(); - logDebug(String.format("Entering OAM bundleOperations with rpc (%s).", rpc.name())); - - String action = rpc.getAppcOperation().toString(); - if (rpc != AppcOam.RPC.stop && rpc != AppcOam.RPC.start) { - throw new APPCException("rpc(" + rpc + ") is not supported by bundleOperation."); - } - - AppcOamStates originalState = stateHelper.getState(); - - boolean isBundleOperationComplete = true; - - Map appcLcmBundles = getAppcLcmBundles(); - for (Map.Entry bundleEntry : appcLcmBundles.entrySet()) { - String bundleName = bundleEntry.getKey(); - Bundle bundle = bundleEntry.getValue(); - - logDebug("OAM launch thread for %s bundle %s", action, bundleName); - if (rpc == AppcOam.RPC.start) { - // Abort in the interruption case. - // such as when a Stop request is receive while APPC is still trying to Start Up. - if (!stateHelper.isSameState(originalState)) { - logger.warn("OAM %s bundle operation aborted since OAM state is no longer %s!", - originalState.name()); - isBundleOperationComplete = false; - break; - } - } - - threads.put(bundleName, - taskHelper.submitBaseSubCallable(new BundleTask(rpc, bundle,baseCommon))); - } - - logDebug(String.format("Leaving OAM bundleOperations with rpc (%s) with complete(%s), elasped (%d) ms.", - rpc.name(), Boolean.toString(isBundleOperationComplete), getElapseTimeMs(mStartTime))); - - return isBundleOperationComplete; - } - - private long getElapseTimeMs(long mStartTime) { - return System.currentTimeMillis() - mStartTime; - } - - /** - * Check if all BundleTasks are completed - * @param bundleNameFutureMap with bundle name and BundleTask Future object - * @return true if all are done, otherwise, false - */ - public boolean isAllTaskDone(Map> bundleNameFutureMap) { - boolean anyNotDone = bundleNameFutureMap.values().stream().anyMatch((f) -> !f.isDone()); - return !anyNotDone; - } - - /** - * Cancel BundleTasks which are not finished - * @param bundleNameFutureMap with bundle name and BundleTask Future object - */ - public void cancelUnfinished(Map> bundleNameFutureMap) { - bundleNameFutureMap.values().stream().filter((f) - -> !f.isDone()).forEach((f) - -> f.cancel(true)); - } - - /** - * Get number of failed BundleTasks - * @param bundleNameFutureMap with bundle name and BundleTask Future object - * @return number(long) of the failed BundleTasks - */ - public long getFailedMetrics(Map> bundleNameFutureMap) { - return bundleNameFutureMap.values().stream().map((f) -> { - try { - return f.get(); - } catch (Exception e) { - // should not get here - throw new RuntimeException(e); - } - }).filter((b) -> ((BundleTask)b).failException != null).count(); - } - - /** - * Gets the list of Appc-bundles to be stopped/started - * - * @return Map of bundle symbolic name and bundle instance - */ - Map getAppcLcmBundles() { - logDebug("In getAppcLcmBundles"); - - String[] bundlesToStop = readPropsFromPropListName(PROP_BUNDLE_TO_STOP); - String[] regExBundleNotStop = readPropsFromPropListName(PROP_BUNDLES_TO_NOT_STOP); - - BundleFilter bundleList = new BundleFilter(bundlesToStop, regExBundleNotStop, getBundleList()); - - logger.info(String.format("(%d) APPC bundles to Stop/Start: %s.", bundleList.getBundlesToStop().size(), - bundleList.getBundlesToStop().toString())); - - logger.debug(String.format("(%d) APPC bundles that won't be Stopped/Started: %s.", - bundleList.getBundlesToNotStop().size(), bundleList.getBundlesToNotStop().toString())); - - return bundleList.getBundlesToStop(); - } - - /** - * Gets a list of all user desired bundles that should be stopped/Started as part of - * OAM Stop and Start API - * - * @param propListKey String of the properties list property name - * @return properties values of the related - */ - String[] readPropsFromPropListName(String propListKey) { - // get properties list by properties list name - String[] propNames = configurationHelper.readProperty(propListKey); - // go through each property to get the property values - String[] propValue = ArrayUtils.EMPTY_STRING_ARRAY; - if (propNames != null) { - for (String aPropName : propNames) { - propValue = ArrayUtils.addAll(propValue, configurationHelper.readProperty(aPropName)); - } - } - return propValue; - } - - /** - * Get all bundle list of APP-C - * @return Array of Bundle - */ - Bundle[] getBundleList() { - BundleContext myBundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - if (myBundleContext != null) { - return myBundleContext.getBundles(); - } - return null; - } - - /** - * Genral debug log when debug logging level is enabled. - * @param message of the log message format - * @param args of the objects listed in the message format - */ - private void logDebug(String message, Object... args) { - if (logger.isDebugEnabled()) { - logger.debug(String.format(message, args)); - } - } - - /** - * Runnable to execute bundle operations: start or stop - */ - class BundleTask implements Callable { - Exception failException; - - private AppcOam.RPC rpc; - private Bundle bundle; - private String bundleName; - private String actionName; - private final BaseCommon baseCommon; - - BundleTask(AppcOam.RPC rpcIn, Bundle bundleIn, BaseCommon baseCommon) { - rpc = rpcIn; - actionName = rpc.getAppcOperation().toString(); - bundle = bundleIn; - bundleName = bundle.getSymbolicName(); - this.baseCommon = baseCommon; - } - - @Override - public BundleTask call() throws Exception { - try { - baseCommon.setInitialLogProperties(); - - long bundleOperStartTime = System.currentTimeMillis(); - logDebug(String.format("OAM %s bundle %s ===>", actionName, bundleName)); - switch (rpc) { - case start: - bundle.start(); - break; - case stop: - bundle.stop(); - break; - default: - // should do nothing - } - logDebug(String.format("OAM %s bundle %s completed <=== elasped %d", - actionName, bundleName, getElapseTimeMs(bundleOperStartTime))); - } catch (BundleException e) { - logger.error(String.format("Exception encountered when OAM %s bundle %s ", - actionName, bundleName), e); - failException = e; - } - finally { - baseCommon.clearRequestLogProperties(); - } - return this; - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/ConfigurationHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/ConfigurationHelper.java deleted file mode 100644 index 3c5629f11..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/ConfigurationHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.apache.commons.lang3.ArrayUtils; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -import java.util.concurrent.TimeUnit; - -/** - * Utility class provides general configuration helps - */ -public class ConfigurationHelper { - final static String PROP_KEY_APPC_NAME = Constants.PROPERTY_APPLICATION_NAME; - final static String PROP_KEY_METRIC_STATE = "metric.enabled"; - private final String OAM_OPERATION_TIMEOUT_SECOND = "appc.OAM.api.timeout"; - /** Default operation timeout set to 1 minute */ - private final int DEFAULT_OAM_OPERATION_TIMEOUT = 60; - - private final EELFLogger logger; - private Configuration configuration = ConfigurationFactory.getConfiguration(); - - public ConfigurationHelper(EELFLogger eelfLogger) { - logger = eelfLogger; - } - - public String getAppcName() { - return configuration.getProperty(PROP_KEY_APPC_NAME); - } - - public boolean isMetricEnabled() { - return configuration.getBooleanProperty(PROP_KEY_METRIC_STATE, false); - } - - public Configuration getConfig() { - return configuration; - } - - /** - * Read property value of a specified property key - * - * @param propertyKey string of the property key - * @return String[] of the property values associated with the propertyKey - */ - String[] readProperty(String propertyKey) { - String propertyValue = configuration.getProperty(propertyKey); - if (propertyValue == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - - if (logger.isDebugEnabled()) { - logger.debug(String.format("Property[%s] has value (%s).", propertyKey, propertyValue)); - } - - if (propertyValue.contains(",")) { - return propertyValue.split("\\s*,\\s*"); - } - return new String[]{propertyValue}; - } - - - - - - /** - * This method returns timeout in milliseconds. The source is chosen in the following order: - * The overrideTimeoutSeconds argument - * or {@link #OAM_OPERATION_TIMEOUT_SECOND} found in the configuration file - * or the {@link #DEFAULT_OAM_OPERATION_TIMEOUT} - * @param overrideTimeoutSeconds or null to us the other sources - * @return timeout in milliseconds - */ - public long getOAMOperationTimeoutValue(Integer overrideTimeoutSeconds) { - return TimeUnit.SECONDS.toMillis( - overrideTimeoutSeconds == null ? - getConfig().getIntegerProperty(OAM_OPERATION_TIMEOUT_SECOND, DEFAULT_OAM_OPERATION_TIMEOUT) - : - overrideTimeoutSeconds - ); - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/OperationHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/OperationHelper.java deleted file mode 100644 index 9eec0b67b..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/OperationHelper.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.common.header.Flags; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.messageadapter.MessageAdapter; -import org.onap.appc.oam.messageadapter.OAMContext; -import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -/** - * Utility class provides general operational helps. - */ -@SuppressWarnings("unchecked") -public class OperationHelper { - final String MISSING_COMMON_HEADER_MESSAGE = "Missing common header"; - final String MISSING_FIELD_MESSAGE = "Common header must have both originatorId and requestId"; - final String NOT_SUPPORT_FLAG = "Flags is not supported by this operation"; - final String NO_SERVICE_REF_FORMAT = "Using the BundleContext failed to get service reference for %s"; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(OperationHelper.class); - private LifecycleManager lifecycleMgr; - private MessageAdapter messageAdapter; - - public OperationHelper() { - // do nothing - } - - /** - * This method is used to validate OAM REST API input due to the following ODL bugs results no validation : - *

- - * Bug 8088 - Mandatory attributes in RPC input are not honoured - *

- - * Bug 5830 - Mandatory leaf enforcement is not correct with presence container - * - * @param inputObject object from the OAM REST API input object - * @throws InvalidInputException is thrown when the commonHeader is invalid - */ - public void isInputValid(final Object inputObject) throws InvalidInputException { - CommonHeader commonHeader = getCommonHeader(inputObject); - if (commonHeader == null) { - throw new InvalidInputException(MISSING_COMMON_HEADER_MESSAGE); - } - - if (commonHeader.getOriginatorId() == null - || commonHeader.getRequestId() == null) { - throw new InvalidInputException(MISSING_FIELD_MESSAGE); - } - - // check Flags - if (inputObject instanceof MaintenanceModeInput - && commonHeader.getFlags() != null) { - throw new InvalidInputException(NOT_SUPPORT_FLAG); - } - } - - /** - * Get commonHead of the inputObject (expecting the inputObject of OAM REST API) - * @param inputObject the OAM REST API input object - * @return CommonHeader of the inputObject. If the inputObject is not a OAM REST API input, null is returned. - */ - public CommonHeader getCommonHeader(final Object inputObject) { - if (inputObject instanceof StartInput) { - return ((StartInput)inputObject).getCommonHeader(); - } - if (inputObject instanceof StopInput) { - return ((StopInput)inputObject).getCommonHeader(); - } - if (inputObject instanceof MaintenanceModeInput) { - return ((MaintenanceModeInput)inputObject).getCommonHeader(); - } - if (inputObject instanceof RestartInput) { - return ((RestartInput)inputObject).getCommonHeader(); - } - return null; - } - - public Integer getParamRequestTimeout(final Object inputObject) { - if (inputObject instanceof MaintenanceModeInput) { - // maintanence mode, we do not support request timeout - return 0; - } - - CommonHeader commonHeader = getCommonHeader(inputObject); - if (commonHeader == null) { - return 0; - } - - Flags inputFlags = commonHeader.getFlags(); - if (inputFlags == null) { - return null; - } - return inputFlags.getRequestTimeout(); - } - /** - * Get service instance using bundle context. - * - * @param _class of the expected service instance - * @param of the expected service instance - * @return service instance of the expected - * @throws APPCException when cannot find service reference or service isntance - */ - public T getService(Class _class) throws APPCException { - BundleContext bctx = FrameworkUtil.getBundle(_class).getBundleContext(); - if (bctx != null) { - ServiceReference sref = bctx.getServiceReference(_class.getName()); - if (sref != null) { - if (logger.isTraceEnabled()) { - logger.debug("Using the BundleContext got the service reference for " + _class.getName()); - } - return (T) bctx.getService(sref); - } - } - - throw new APPCException(String.format(NO_SERVICE_REF_FORMAT, _class.getName())); - } - - /** - * Get next valid state from life cycle manager. - * - * @param operation of the AppcOperation for the state changes - * @param currentState of AppcOamStates - * @return next AppcOamStates based on the currentState and operation - * @throws APPCException If life cycle manager instance cannot be retrieved - * @throws InvalidStateException when the operation is not supported on the currentState - */ - public AppcOamStates getNextState(AppcOamMetaDataReader.AppcOperation operation, AppcOamStates currentState) - throws APPCException, InvalidStateException { - if (lifecycleMgr == null) { - lifecycleMgr = getService(LifecycleManager.class); - } - - try { - String nextState = lifecycleMgr.getNextState("APPC", currentState.name(), operation.toString()); - if (nextState != null) { - return AppcOamStates.valueOf(nextState); - } - } catch (LifecycleException |NoTransitionDefinedException ex) { - logger.error("Invalid next state based on the current state and attempted Operation " + ex.getMessage()); - } - - throw new InvalidStateException(String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, operation, "APPC", currentState)); - } - - /** - * Post notification through MessageAdapter. - * - * @param rpc of REST API RPC - * @param commonHeader of REST API request common header - * @param status of the to be post message - */ - public void sendNotificationMessage(AppcOam.RPC rpc, CommonHeader commonHeader, Status status) { - if (messageAdapter == null) { - messageAdapter = new MessageAdapter(); - messageAdapter.init(); - - } - - OAMContext oamContext = new OAMContext(); - oamContext.setRpcName(rpc); - oamContext.setCommonHeader(commonHeader); - oamContext.setStatus(status); - messageAdapter.post(oamContext); - } -} diff --git a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/StateHelper.java b/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/StateHelper.java deleted file mode 100644 index 871a07676..000000000 --- a/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/StateHelper.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; - -import java.util.Map; - -/* - * Utility class provides general state helps - */ -public class StateHelper { - /** logger inherited from AppcOam */ - private final EELFLogger logger; - private ConfigurationHelper configurationHelper; - /** APP-C OAM current state in AppcOamStates value */ - private volatile AppcOamStates appcOamCurrentState; - - /** - * Constructor - * - * @param eelfLogger of the logger - */ - public StateHelper(EELFLogger eelfLogger, ConfigurationHelper cHelper) { - logger = eelfLogger; - configurationHelper = cHelper; - appcOamCurrentState = AppcOamStates.Unknown; - } - - /** - * Set the passed in state to the class appOamCurrentState. - * - * @param appcOamStates of the new state - */ - public void setState(AppcOamStates appcOamStates) { - appcOamCurrentState = appcOamStates; - } - - /** - * Get the state - * @return the class appOamCurrentState - */ - public AppcOamStates getState() { - return appcOamCurrentState; - } - - /** - * Validate if the passed in state is the same as the class appOamCurrentState. - * - * @param appcOamStates of the to be compared state - * @return true if they are the same, otherwise false - */ - boolean isSameState(AppcOamStates appcOamStates) { - return appcOamCurrentState == appcOamStates; - } - - /** - * Get APP-C OAM current state - * - *

When appcOamCurrentState is null or unknown, reset it with APPC LCM bundle state. - * - * @return AppcOamStates of the current APP-C OAM state - */ - public AppcOamStates getCurrentOamState() { - if (appcOamCurrentState == null || appcOamCurrentState.equals(AppcOamStates.Unknown)) { - appcOamCurrentState = getBundlesState(); - } - return appcOamCurrentState; - } - - /** - * Use getCurrentOamState to get current OAM AppcOamStates and then convert to AppcState of Yang. - * - * @return AppcState of current OAM state - */ - public AppcState getCurrentOamYangState() { - try { - AppcOamStates appcOamStates = getCurrentOamState(); - return AppcState.valueOf(appcOamStates.name()); - } catch (Exception ex) { - logger.error(String.format("Unable to determine the current APP-C OAM state due to %s.", ex.getMessage())); - } - return AppcState.Unknown; - } - - /** - * Get APPC state from the state of the set of APPC LCM bundles. - *

The state of each bundle will be checked and the lowest state will be uses as the returning AppcOamStates. - *

The bundle state order are defined in OSGI bundle (@see org.osgi.framework.Bundle) class - * as the int value assigned to each state as the following:
- * - UNINSTALLED (1)
- * - INSTALLED (2)
- * - RESOLVED (4)
- * - STARTING (8)
- * - STOPPING (16)
- * - ACTIVE (32)
- * - * @return AppcOamStates - */ - public AppcOamStates getBundlesState() { - BundleHelper bundleHelper = new BundleHelper(logger, configurationHelper, this); - Map lcmBundleMap = bundleHelper.getAppcLcmBundles(); - if (lcmBundleMap == null || lcmBundleMap.isEmpty()) { - return AppcOamStates.Unknown; - } - - // As we are picking up the lowest bundle state as general APP-C state, we will start with ACTIVE - int currentState = Bundle.ACTIVE; - for (Bundle bundle : lcmBundleMap.values()) { - int bundleState = bundle.getState(); - logger.trace(String.format("getBundlesState: [%s] has state (%d)", bundle.getSymbolicName(), bundleState)); - if (bundleState < currentState) { - currentState = bundleState; - } - } - return AppcOamStates.getOamStateFromBundleState(currentState); - } - -} diff --git a/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/default.properties b/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..964040a18 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,90 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# This property file supplies the configuration defaults for the APP-C controller +# +# Default values are supplied so that all defined properties have well-known values and are +# valid even if a configuration file is not supplied. This is done to ensure that a runnable, +# stable, and defined configuration exists at all times. The reason the defaults are supplied +# via this property file and not in the code is so that the properties can be changed +# easily if needed in the future. Use of the "getProperty(name, default)" method is +# discouraged because if the default value needs to be changed, everywhere in the code it +# is used would have to be changed. By loading the defaults in this property file, all +# values can be defined in one place and support is easier. This does mean that all +# properties that are defined must have a default value supplied here. Which also means +# this file documents all defined properties (not a bad thing either). +# +#-------------------------------------------------------------------------------------------- +# The path and file used to load user-supplied configuration settings, if any +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. +org.onap.appc.bootstrap.file=appc.properties + +appc.application.name=APPC + +# +# The path to search for logging configuration document, and the name of the document +# +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + + +# +# The properties would be used by OAM's Stop/Start APIs to stop/start the bundles +# +appc.OAM.ToStop.properties=appc.OAM.AppcBundlesToStop\ +,appc.OAM.OtherBundlesToStop +appc.OAM.ToNotStop.properties=appc.OAM.AppcBundlesToNotStop\ +,appc.OAM.OtherBundlesToNotStop + +# These following properties represent the Regular-Expression which would be evaluated against the +# running Bundles's Symbolic-Name: +# - appc.OAM.AppcBundlesToStop +# - appc.OAM.OtherBundlesToStop +# - appc.OAM.AppcBundlesToNotStop +# - appc.OAM.OtherBundlesToNotStop +appc.OAM.AppcBundlesToStop=.*appc.*\ +,domain-model-lib\ +,execution-queue-management-lib\ +,lock-manager-impl\ +,org.openecomp.sdnc.config.params\ +,org.openecomp.sdnc.config.audit\ +,org.openecomp.sdnc.config.generator\ +,org.openecomp.sdnc.dg.loader\ +,transaction-recorder + +appc.OAM.OtherBundlesToStop=.*app-cntrl.*\ +,com.att.sdnctl.sli.adaptor.asyncresponse + +appc.OAM.AppcBundlesToNotStop=.*appc.oam.*\ +,appc-common\ +,appc-command-executor-api\ +,appc-lifecycle-management-api\ +,appc-lifecycle-management-core\ +,appc-metric-bundle\ +,org.onap.appc.listener\ +,state-machine-lib + +appc.OAM.OtherBundlesToNotStop=app-cntrl-message-adapter-factory\ +,app-cntrl-aaf-filters diff --git a/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/logback.xml b/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/logback.xml new file mode 100644 index 000000000..0dffe75e0 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/main/resources/org/onap/appc/logback.xml @@ -0,0 +1,287 @@ + + + + + + + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + + + + + + + ${logDirectory}/cdp.log + + ${logDirectory}/cdp.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-security.log + + ${logDirectory}/cdp-security.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + 0 + + + + + + ${logDirectory}/cdp-performance.log + + ${logDirectory}/cdp-performance.%i.log.zip + + 1 + 9 + + + 5MB + + + true + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-server.log + + ${logDirectory}/cdp-server.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-coordinator.log + + ${logDirectory}/cdp-coordinator.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-policy.log + + ${logDirectory}/cdp-policy.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + 256 + + + + ${debugLogDirectory}/appc-debug.log + + ${logDirectory}/command-executor.%i.log.zip + + 1 + 9 + + + 5MB + + + + + %d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%X{InstanceUUID}|%-5.5p|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%c{3}]|%m%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 964040a18..000000000 --- a/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,90 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# -# This property file supplies the configuration defaults for the APP-C controller -# -# Default values are supplied so that all defined properties have well-known values and are -# valid even if a configuration file is not supplied. This is done to ensure that a runnable, -# stable, and defined configuration exists at all times. The reason the defaults are supplied -# via this property file and not in the code is so that the properties can be changed -# easily if needed in the future. Use of the "getProperty(name, default)" method is -# discouraged because if the default value needs to be changed, everywhere in the code it -# is used would have to be changed. By loading the defaults in this property file, all -# values can be defined in one place and support is easier. This does mean that all -# properties that are defined must have a default value supplied here. Which also means -# this file documents all defined properties (not a bad thing either). -# -#-------------------------------------------------------------------------------------------- -# The path and file used to load user-supplied configuration settings, if any -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. -org.onap.appc.bootstrap.file=appc.properties - -appc.application.name=APPC - -# -# The path to search for logging configuration document, and the name of the document -# -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - - -# -# The properties would be used by OAM's Stop/Start APIs to stop/start the bundles -# -appc.OAM.ToStop.properties=appc.OAM.AppcBundlesToStop\ -,appc.OAM.OtherBundlesToStop -appc.OAM.ToNotStop.properties=appc.OAM.AppcBundlesToNotStop\ -,appc.OAM.OtherBundlesToNotStop - -# These following properties represent the Regular-Expression which would be evaluated against the -# running Bundles's Symbolic-Name: -# - appc.OAM.AppcBundlesToStop -# - appc.OAM.OtherBundlesToStop -# - appc.OAM.AppcBundlesToNotStop -# - appc.OAM.OtherBundlesToNotStop -appc.OAM.AppcBundlesToStop=.*appc.*\ -,domain-model-lib\ -,execution-queue-management-lib\ -,lock-manager-impl\ -,org.openecomp.sdnc.config.params\ -,org.openecomp.sdnc.config.audit\ -,org.openecomp.sdnc.config.generator\ -,org.openecomp.sdnc.dg.loader\ -,transaction-recorder - -appc.OAM.OtherBundlesToStop=.*app-cntrl.*\ -,com.att.sdnctl.sli.adaptor.asyncresponse - -appc.OAM.AppcBundlesToNotStop=.*appc.oam.*\ -,appc-common\ -,appc-command-executor-api\ -,appc-lifecycle-management-api\ -,appc-lifecycle-management-core\ -,appc-metric-bundle\ -,org.onap.appc.listener\ -,state-machine-lib - -appc.OAM.OtherBundlesToNotStop=app-cntrl-message-adapter-factory\ -,app-cntrl-aaf-filters diff --git a/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/logback.xml b/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/logback.xml deleted file mode 100644 index 0dffe75e0..000000000 --- a/appc-oam/appc-oam-bundle/src/main/resources/org/openecomp/appc/logback.xml +++ /dev/null @@ -1,287 +0,0 @@ - - - - - - - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - - - - - - - ${logDirectory}/cdp.log - - ${logDirectory}/cdp.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-security.log - - ${logDirectory}/cdp-security.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - 0 - - - - - - ${logDirectory}/cdp-performance.log - - ${logDirectory}/cdp-performance.%i.log.zip - - 1 - 9 - - - 5MB - - - true - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-server.log - - ${logDirectory}/cdp-server.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-coordinator.log - - ${logDirectory}/cdp-coordinator.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-policy.log - - ${logDirectory}/cdp-policy.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - 256 - - - - ${debugLogDirectory}/appc-debug.log - - ${logDirectory}/command-executor.%i.log.zip - - 1 - 9 - - - 5MB - - - - - %d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%X{InstanceUUID}|%-5.5p|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%c{3}]|%m%n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java new file mode 100644 index 000000000..110198370 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.oam.processor.OamMmodeProcessor; +import org.onap.appc.oam.processor.OamRestartProcessor; +import org.onap.appc.oam.processor.OamStartProcessor; +import org.onap.appc.oam.processor.OamStopProcessor; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AppcOam.class, FrameworkUtil.class, Executors.class}) +public class AppcOamTest { + + private AppcOam appcOam; + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + private Status mockStatus = mock(Status.class); + private OperationHelper mockOperationHelper = mock(OperationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + + @Before + public void setUp() throws Exception { + appcOam = spy(new AppcOam(null, null, null)); + + Whitebox.setInternalState(appcOam, "stateHelper", mockStateHelper); + Whitebox.setInternalState(appcOam, "operationHelper", mockOperationHelper); + } + + @Test + public void testMaintenanceMode() throws Exception { + // mock processor creation + OamMmodeProcessor mockProcessor = mock(OamMmodeProcessor.class); + PowerMockito.mockStatic(OamMmodeProcessor.class); + PowerMockito.whenNew(OamMmodeProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future> response = appcOam.maintenanceMode(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testStart() throws Exception { + // mock processor creation + OamStartProcessor mockProcessor = mock(OamStartProcessor.class); + PowerMockito.mockStatic(OamStartProcessor.class); + PowerMockito.whenNew(OamStartProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future> response = appcOam.start(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testStop() throws Exception { + // mock processor creation + OamStopProcessor mockProcessor = mock(OamStopProcessor.class); + PowerMockito.mockStatic(OamStopProcessor.class); + PowerMockito.whenNew(OamStopProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + StopInput mockInput = mock(StopInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future> response = appcOam.stop(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testRestart() throws Exception { + // mock processor creation + OamRestartProcessor mockProcessor = mock(OamRestartProcessor.class); + PowerMockito.mockStatic(OamRestartProcessor.class); + PowerMockito.whenNew(OamRestartProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + RestartInput mockInput = mock(RestartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future> response = appcOam.restart(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testGetAppcState() throws Exception { + AppcState appcState = AppcState.Started; + Mockito.doReturn(appcState).when(mockStateHelper).getCurrentOamYangState(); + + Future> state = appcOam.getAppcState(); + Assert.assertEquals("Should return the same state", + appcState, state.get().getResult().getState()); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java new file mode 100644 index 000000000..269c4f811 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.executor.objects.Params; + +import java.util.HashMap; +import java.util.Map; + +public class OAMCommandStatusTest { + private Map CODE_MAP = new HashMap() { + { + put(OAMCommandStatus.ABORT, 304); + put(OAMCommandStatus.ACCEPTED, 100); + put(OAMCommandStatus.INVALID_PARAMETER, 302); + put(OAMCommandStatus.REJECTED, 300); + put(OAMCommandStatus.SUCCESS, 400); + put(OAMCommandStatus.TIMEOUT, 303); + put(OAMCommandStatus.UNEXPECTED_ERROR, 200); + } + }; + private Map MSG_MAP = new HashMap() { + { + put(OAMCommandStatus.ABORT, "OPERATION ABORT - ${errorMsg}"); + put(OAMCommandStatus.ACCEPTED, "ACCEPTED - request accepted"); + put(OAMCommandStatus.INVALID_PARAMETER, "INVALID PARAMETER - ${errorMsg}"); + put(OAMCommandStatus.REJECTED, "REJECTED - ${errorMsg}"); + put(OAMCommandStatus.SUCCESS, "SUCCESS - request has been processed successfully"); + put(OAMCommandStatus.TIMEOUT, "OPERATION TIMEOUT REACHED - ${errorMsg}"); + put(OAMCommandStatus.UNEXPECTED_ERROR, "UNEXPECTED ERROR - ${errorMsg}"); + } + }; + + @Test + public void testGetResponseMessage() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedMsg = MSG_MAP.get(oamCommandStatus); + Assert.assertEquals(String.format("Should have message (%s).", expectedMsg), + expectedMsg, oamCommandStatus.getResponseMessage()); + } + } + + @Test + public void testGetResponseCode() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + Integer expectedCode = CODE_MAP.get(oamCommandStatus); + Assert.assertEquals(String.format("Should have code (%d).", expectedCode), + expectedCode, Integer.valueOf(oamCommandStatus.getResponseCode())); + } + } + + @Test + public void testGetFormattedMessage() throws Exception { + String message = "test message"; + Params params = new Params().addParam("errorMsg", message); + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedMsg1 = MSG_MAP.get(oamCommandStatus); + String expectedMsg2 = expectedMsg1.replaceAll("\\$\\{errorMsg\\}", message); + Assert.assertEquals("Should returned " + expectedMsg1, + expectedMsg1, oamCommandStatus.getFormattedMessage(null)); + Assert.assertEquals("Should returned " + expectedMsg2, + expectedMsg2, oamCommandStatus.getFormattedMessage(params)); + } + } + + @Test + public void testToString() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedString = String.format(oamCommandStatus.TO_STRING_FORMAT, + CODE_MAP.get(oamCommandStatus), MSG_MAP.get(oamCommandStatus)); + Assert.assertEquals(String.format("Should have string (%s).", expectedString), + expectedString, oamCommandStatus.toString()); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java new file mode 100644 index 000000000..d3ebfda51 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.messageadapter; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; + +import org.mockito.Mockito; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.HashSet; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MessageAdapter.class, FrameworkUtil.class}) +public class MessageAdapterTest { + + private Producer fakeProducer; + + private MessageAdapter messageAdapter; + + + @Before + public final void setup() throws Exception { + fakeProducer = mock(Producer.class); + messageAdapter = new MessageAdapter(); + } + + @Test + public void testGetProducerReturnsNull() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Mockito.doNothing().when(maSpy).createProducer(); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() did not return null", producer == null); + Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); + Assert.assertTrue("MessageAdapter producer is not null", mySpyProducer == null); + Mockito.verify(maSpy, Mockito.times(1)).createProducer(); + } + + @Test + public void testGetProducerWithExistingProducer() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Whitebox.setInternalState(maSpy, "producer", fakeProducer); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() returned null", producer == fakeProducer); + Mockito.verify(maSpy, Mockito.times(0)).createProducer(); + } + + @Test + public void testGetProducerWithCreateProducer() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Whitebox.setInternalState(maSpy, "producer", (Object) null); + HashSet pool = new HashSet<>(); + Whitebox.setInternalState(maSpy, "pool", pool); + + // Prepare all mocks + mockStatic(FrameworkUtil.class); + Bundle maBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(MessageAdapter.class)).thenReturn(maBundle); + + BundleContext maBundleContext = mock(BundleContext.class); + Mockito.when(maBundle.getBundleContext()).thenReturn(maBundleContext); + + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(maBundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(svcRef); + + MessageAdapterFactory maFactory = mock(MessageAdapterFactory.class); + Mockito.when(maBundleContext.getService(svcRef)).thenReturn(maFactory); + Mockito.when(maFactory.createProducer(pool, (String) null, null, null)).thenReturn(fakeProducer); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() result does not match", producer == fakeProducer); + Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); + Assert.assertTrue("MessageAdapter producer does not match",mySpyProducer == fakeProducer); + Mockito.verify(maSpy, Mockito.times(1)).createProducer(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java new file mode 100644 index 000000000..daf0f6e07 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java @@ -0,0 +1,293 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.BundleHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +import java.util.Date; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +public class BaseActionRunnableTest { + private AppcOam.RPC testRpc = AppcOam.RPC.maintenance_mode; + private AppcOamStates targetState = AppcOamStates.MaintenanceMode; + + private class TestProcessor extends BaseProcessor { + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param asyncTaskHelperIn for scheduling async task + * @param operationHelperIn for operational helper + */ + TestProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + AsyncTaskHelper asyncTaskHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); + + // must set rpc and auditMsg + rpc = testRpc; + auditMsg = Msg.OAM_OPERATION_STARTING; + startTime = new Date(); + } + } + + class TestAbc extends BaseActionRunnable { + boolean doActionResult; + + TestAbc(BaseProcessor parent) { + super(parent); + + actionName = "testing"; + auditMsg = Msg.OAM_OPERATION_MAINTENANCE_MODE; + finalState = targetState; + } + + @Override + boolean doAction() { + return doActionResult; + } + } + + private TestAbc testBaseAcionRunnable; + private BaseProcessor testProcessor; + private StateHelper mockStateHelper = mock(StateHelper.class); + private OperationHelper mockOperHelper = mock(OperationHelper.class); + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private BundleHelper mockBundleHelper = mock(BundleHelper.class); + + @SuppressWarnings("ResultOfMethodCallIgnored") + @Before + public void setUp() throws Exception { + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + + testProcessor = spy( + new TestProcessor(mockLogger, mockConfigHelper, mockStateHelper, null, mockOperHelper)); + Whitebox.setInternalState(testProcessor, "bundleHelper", mockBundleHelper); + + testBaseAcionRunnable = spy(new TestAbc(testProcessor)); + Whitebox.setInternalState(testBaseAcionRunnable, "commonHeader", mock(CommonHeader.class)); + } + + @Test + public void testSetTimeoutValues() throws Exception { + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + long expectedTimeout = 10000L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); + Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); + + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + expectedTimeout = 20000L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); + Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); + + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + expectedTimeout = 0L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should not set start time MS", testBaseAcionRunnable.startTimeMs == 0); + Assert.assertFalse("Should not do check", testBaseAcionRunnable.doTimeoutChecking); + } + + @Test + public void testRun() throws Exception { + // test doAction failed + Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", false); + testBaseAcionRunnable.run(); + Assert.assertFalse("isWaiting should still be false", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // test doAction success + Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", true); + + // with checkState return true + Mockito.doReturn(true).when(testBaseAcionRunnable).checkState(); + testBaseAcionRunnable.run(); + Assert.assertFalse("isWaiting should still be false", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // with checkState return false + Mockito.doReturn(false).when(testBaseAcionRunnable).checkState(); + testBaseAcionRunnable.run(); + Assert.assertTrue("isWaiting should still be true", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // should stay + testBaseAcionRunnable.run(); + Mockito.verify(testBaseAcionRunnable, times(1)).keepWaiting(); + } + + @Test + public void testSetAbortStatus() throws Exception { + testBaseAcionRunnable.setAbortStatus(); + Assert.assertEquals("Should return abort code", OAMCommandStatus.ABORT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set abort due to execution error message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, + testRpc.name(), testBaseAcionRunnable.DUE_TO_EXECUTION_ERROR))); + } + + @Test + public void testCheckState() throws Exception { + // 1. with isTimeout true + Mockito.doReturn(true).when(testBaseAcionRunnable).isTimeout("checkState"); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + // 2. with isTimeout false and + Mockito.doReturn(false).when(testBaseAcionRunnable).isTimeout("checkState"); + + // 2.1 with task not all done + Mockito.doReturn(false).when(mockBundleHelper).isAllTaskDone(any()); + Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); + + // 2. 2 with task all done + Mockito.doReturn(true).when(mockBundleHelper).isAllTaskDone(any()); + + // 2.2.1 with has bundle failure + Mockito.doReturn(true).when(testBaseAcionRunnable).hasBundleOperationFailure(); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + // 2.2.2 with no bundle failure + Mockito.doReturn(false).when(testBaseAcionRunnable).hasBundleOperationFailure(); + + Mockito.doReturn(targetState).when(mockStateHelper).getBundlesState(); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getBundlesState(); + Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); + } + + @Test + public void testPostAction() throws Exception { + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + // set status to avoid NPE when using status + testBaseAcionRunnable.setAbortStatus(); + + // test no parameter + testBaseAcionRunnable.postAction(null); + Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(mockStateHelper, times(0)).setState(any()); + Mockito.verify(testProcessor, times(1)).cancelAsyncTask(); + + // test with parameter + testBaseAcionRunnable.postAction(AppcOamStates.Error); + Mockito.verify(mockOperHelper, times(2)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(mockStateHelper, times(1)).setState(any()); + Mockito.verify(testProcessor, times(2)).cancelAsyncTask(); + } + + @Test + public void testIsTimeout() throws Exception { + String parentName = "testing"; + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); + + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", true); + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", System.currentTimeMillis() + 100); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); + Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); + + long timeoutMs = 1; + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", timeoutMs); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); + Assert.assertTrue("Should be timeout", testBaseAcionRunnable.isTimeout(parentName)); + Mockito.verify(testBaseAcionRunnable, times(1)).postAction(any()); + Assert.assertEquals("Should return timeout code", OAMCommandStatus.TIMEOUT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set timeout message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.TIMEOUT_MESSAGE_FORMAT, testRpc.name(), timeoutMs))); + } + + @SuppressWarnings("unchecked") + @Test + public void testHasBundleOperationFailure() throws Exception { + Mockito.when(mockBundleHelper.getFailedMetrics(anyMap())).thenReturn(Long.valueOf("0")); + Assert.assertFalse("should return false", testBaseAcionRunnable.hasBundleOperationFailure()); + + Mockito.when(mockStateHelper.getCurrentOamState()).thenReturn(AppcOamStates.Restarting); + long failedNumber = 1; + Mockito.doReturn(failedNumber).when(mockBundleHelper).getFailedMetrics(anyMap()); + Assert.assertTrue("should return true", testBaseAcionRunnable.hasBundleOperationFailure()); + Mockito.verify(testBaseAcionRunnable, times(1)).setStatus(OAMCommandStatus.UNEXPECTED_ERROR, + String.format(testBaseAcionRunnable.BUNDLE_OPERATION_FAILED_FORMAT, failedNumber)); + Mockito.verify(testBaseAcionRunnable, times(1)).postAction(AppcOamStates.Error); + } + + @Test + public void testAbortRunnable() throws Exception { + Mockito.doReturn(AppcOamStates.Restarting).when(mockStateHelper).getCurrentOamState(); + AppcOam.RPC newRpc = AppcOam.RPC.restart; + testBaseAcionRunnable.abortRunnable(newRpc); + Assert.assertEquals("Should return abort code", OAMCommandStatus.ABORT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set abort due to new request message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, testRpc.name(), + String.format(testBaseAcionRunnable.NEW_RPC_OPERATION_REQUEST, newRpc.name())))); + Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(false); + Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(true); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java new file mode 100644 index 000000000..59bddb0e4 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.slf4j.MDC; + +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({BaseCommon.class, MDC.class}) +public class BaseCommonTest { + private class TestAbc extends BaseCommon { + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param operationHelperIn for operational helper + */ + TestAbc(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, operationHelperIn); + } + } + + private TestAbc testBaseCommon; + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Before + public void setUp() throws Exception { + testBaseCommon = spy(new TestAbc(null, mockConfigHelper, mockStateHelper, null)); + + Whitebox.setInternalState(testBaseCommon, "commonHeader", mockCommonHeader); + Whitebox.setInternalState(testBaseCommon, "rpc", AppcOam.RPC.maintenance_mode); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(testBaseCommon, "logger", mockLogger); + } + + @Test + public void testSetStatus() throws Exception { + OAMCommandStatus oamCommandStatus = OAMCommandStatus.ACCEPTED; + testBaseCommon.setStatus(oamCommandStatus); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Assert.assertEquals("Should have message", oamCommandStatus.getResponseMessage(), status.getMessage()); + } + + @Test + public void testSetStatusWithParams() throws Exception { + String message = "testing"; + OAMCommandStatus oamCommandStatus = OAMCommandStatus.REJECTED; + testBaseCommon.setStatus(oamCommandStatus, message); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Assert.assertTrue("Should have message", status.getMessage().endsWith(message)); + } + + @Test + public void testSetErrorStatus() throws Exception { + Mockito.doReturn("testName").when(mockConfigHelper).getAppcName(); + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + Mockito.doReturn("testRequestId").when(mockCommonHeader).getRequestId(); + Mockito.doReturn("testOrigId").when(mockCommonHeader).getOriginatorId(); + + String exceptionMessage = "testing"; + + OAMCommandStatus oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER; + Throwable t = new InvalidInputException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Mockito.verify(testBaseCommon, times(1)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(1)).resetLogProperties(true); + + oamCommandStatus = OAMCommandStatus.REJECTED; + t = new InvalidStateException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Mockito.verify(testBaseCommon, times(2)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(2)).resetLogProperties(true); + + oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; + t = new NullPointerException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Mockito.verify(testBaseCommon, times(3)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(3)).resetLogProperties(true); + } + + @Test + public void testSetInitialLogProperties() throws Exception { + mockStatic(MDC.class); + testBaseCommon.setInitialLogProperties(); + PowerMockito.verifyStatic(times(5)); + } + + @Test + public void testClearRequestLogProperties() throws Exception { + mockStatic(MDC.class); + testBaseCommon.clearRequestLogProperties(); + PowerMockito.verifyStatic(times(5)); + } + + @Test + public void testResetLogProperties() throws Exception { + testBaseCommon.setInitialLogProperties(); + + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(2)).getRequestId(); + Mockito.verify(mockCommonHeader, times(2)).getOriginatorId(); + Map oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); + Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); + + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(3)).getRequestId(); + Mockito.verify(mockCommonHeader, times(3)).getOriginatorId(); + + // test oldMdcMap is cleared + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(4)).getRequestId(); + Mockito.verify(mockCommonHeader, times(4)).getOriginatorId(); + oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); + Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java new file mode 100644 index 000000000..6769352c6 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +@SuppressWarnings("ResultOfMethodCallIgnored") +public class BaseProcessorTest { + private AppcOam.RPC testRpc = AppcOam.RPC.start; + private AppcOamStates currentState = AppcOamStates.Stopped; + + private class TestAbc extends BaseProcessor { + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param asyncTaskHelperIn for scheduling async task + * @param operationHelperIn for operational helper + */ + TestAbc(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + AsyncTaskHelper asyncTaskHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); + + // must set rpc and auditMsg + rpc = testRpc; + auditMsg = Msg.OAM_OPERATION_STARTING; + } + } + + private TestAbc testBaseProcessor; + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); + private OperationHelper mockOperHelper = mock(OperationHelper.class); + + private StartInput mockInput = mock(StartInput.class); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Before + public void setUp() throws Exception { + Mockito.doReturn(mockCommonHeader).when(mockOperHelper).getCommonHeader(mockInput); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + + testBaseProcessor = spy( + new TestAbc(null, mockConfigHelper, mockStateHelper, mockTaskHelper, mockOperHelper)); + + Whitebox.setInternalState(testBaseProcessor, "commonHeader", mockCommonHeader); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(testBaseProcessor, "logger", mockLogger); + } + + @Test + public void testProcessRequestError() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); + Status status = testBaseProcessor.processRequest(mockInput); + Assert.assertEquals("Should return reject", + OAMCommandStatus.INVALID_PARAMETER.getResponseCode(), status.getCode().intValue()); + } + + @Test + public void testProcessRequest() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doReturn(AppcOamStates.Starting).when(mockOperHelper).getNextState(any(), any()); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Status status = testBaseProcessor.processRequest(mockInput); + Assert.assertEquals("Should return success", + OAMCommandStatus.ACCEPTED.getResponseCode(), status.getCode().intValue()); + } + + @Test(expected = InvalidInputException.class) + public void testPreProcessWithInvalidInput() throws Exception { + Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); + testBaseProcessor.preProcess(mockInput); + } + + @Test(expected = InvalidStateException.class) + public void testPreProcessWithInvalidState() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new InvalidStateException("test")) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + } + + @Test(expected = APPCException.class) + public void testPreProcessWithAppcException() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new APPCException("test")) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + } + + @Test + public void testPreProcess() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + AppcOamStates nextState = AppcOamStates.Starting; + Mockito.doReturn(nextState) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + Mockito.verify(mockOperHelper, times(1)).isInputValid(mockInput); + Mockito.verify(mockOperHelper, times(1)).getNextState(testRpc.getAppcOperation(), currentState); + Mockito.verify(mockStateHelper, times(1)).setState(nextState); + } + + @Test + public void testScheduleAsyncTask() throws Exception { + // test no runnable + testBaseProcessor.scheduleAsyncTask(); + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "runnable") == null); + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); + + BaseActionRunnable mockRunnable = mock(BaseActionRunnable.class); + Whitebox.setInternalState(testBaseProcessor, "runnable", mockRunnable); + testBaseProcessor.scheduleAsyncTask(); + // scheduledRunnable should still be null, there's no mock done + // as I have trouble to make mockTaskHelper.scheduleBaseRunnable to return a proper Future + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java new file mode 100644 index 000000000..ddeb99440 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java @@ -0,0 +1,665 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.LinkedList; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class AsyncTaskHelperTest { + private AsyncTaskHelper asyncTaskHelper; + + private long initialDelayMillis = 0; + private long delayMillis = 10; + + + @Before + public void setUp() throws Exception { + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + + + mockStatic(FrameworkUtil.class); + Bundle myBundle = mock(Bundle.class); + Mockito.doReturn("TestBundle").when(myBundle).getSymbolicName(); + PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); + + asyncTaskHelper = new AsyncTaskHelper(mockLogger); + + + } + + + @After + public void shutdown(){ + asyncTaskHelper.close(); + } + + + /** + * Test that Base Runnable + * + * Runs at a fix rate; + * Only one Base Runnable can be scheduled at time; + * Future.cancle stops the Base Runnable; + * That another Base Runnable can be scheduled once the previous isDone. + */ + @Test + public void test_scheduleBaseRunnable_Base_isDone() throws Exception{ + + + + //loop is to test we can run consecutive Base Runnable + for(int testIteration = 0; testIteration < 3;testIteration++){ + final ExecuteTest et = new ExecuteTest(); + + Future future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + //make sure it is running at a fix rate + Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + + //make sure a seconds Runnable cannot be scheduled when one is already running + try { + asyncTaskHelper.scheduleBaseRunnable(et::test + , s -> {} + ,initialDelayMillis + ,delayMillis + ); + Assert.fail("scheduling should have been prevented. "); + } catch (IllegalStateException e) { + //IllegalStateException means the second scheduling was not allowed. + } + + + //let it cancel itself + et.cancelSelfOnNextExecution(future); + + //it should be done after it executes itself one more time. + Assert.assertTrue("it should be done", waitFor(future::isDone, 5000)); + Assert.assertTrue("The test failed to execute", et.isExecuted); + } + + + } + + + /** + * Makes sure the Future.isDone one only returns true if its runnable is not currently executing and will not + * execute in the future. Default implementation of isDone() returns true immediately after the future is + * canceled -- Even if is there is still a thread actively executing the runnable + */ + @Test + public void test_scheduleBaseRunnable_Base_isDone_Ignore_Interrupt() throws Exception{ + + + final ExecuteTest et = new ExecuteTest(); + + //configure test to run long and ignore interrupt + et.isContinuous = true; + et.isIgnoreInterrupt = true; + + + + Future future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s->{} + ,initialDelayMillis + ,delayMillis + ); + + //make sure it is running + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + Assert.assertTrue("It should be running",et.waitForTestExec(1000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + //cancel it and make sure it is still running + future.cancel(true); + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + Assert.assertTrue("It should be running",et.waitForTestExec(1000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + //let the thread die and then make sure its done + et.isContinuous = false; + Assert.assertTrue("It should not be running",waitForNot(et::isExecuting,1000)); + Assert.assertTrue("It Should be Done", future.isDone()); + + } + + + + + /** + * Make sure the base Future.isDone returns false until the sub callable has completed execution. + */ + @Test + public void test_scheduleBaseRunnable_SubTask_isDone_Ignore_Interrupt() throws Exception{ + + + final ExecuteTest baseET = new ExecuteTest(); + final ExecuteTest subET = new ExecuteTest(); + + //configure sub test to run long and ignore interrupt + subET.isContinuous = true; + subET.isIgnoreInterrupt = true; + + + //schedule the Base test to run and make sure it is running. + Future baseFuture = asyncTaskHelper.scheduleBaseRunnable( + baseET::test + ,s->{} + ,initialDelayMillis + ,delayMillis + ); + Assert.assertTrue("baseET should be running",waitFor(baseET::isExecuted,1000)); + Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); + + + //schedule the sub task and make sure it is running + Future subFuture = asyncTaskHelper.submitBaseSubCallable(subET::test); + Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); + Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", subFuture.isDone()); + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + //cancel the base task and make sure isDone is still false + baseFuture.cancel(true); + Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); + Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done",subFuture.isDone()); + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + + //let the sub task die and and make sure the base is now finally done + subET.isContinuous = false; + Assert.assertTrue("subET should not be running",waitForNot(subET::isExecuting,1000)); + Assert.assertTrue("subET Should be Done", subFuture.isDone()); + Assert.assertTrue("baseET Should be Done", baseFuture.isDone()); + + } + + + /** + * Make sure the base Future.isDone returns false until the 3 sub callable has completed execution. + * Each sub callable will be shutdown one at a time. + */ + @Test + public void test_scheduleBaseRunnable_SubTasks_isDone() throws Exception { + + + //loop is to test we can run consecutive Base Runnable + for (int testIteration = 0; testIteration < 3; testIteration++) { + final ExecuteTest baseET = new ExecuteTest(); + final LinkedList subList = new LinkedList<>(); + for (int i = 0; i < 3; i++) { + Sub sub = new Sub(); + sub.et.isContinuous = true; + subList.add(sub); + } + + + //schedule the base runnable and make sure it is running + Future baseFuture = asyncTaskHelper.scheduleBaseRunnable( + baseET::test + , s -> { + } + , initialDelayMillis + , delayMillis + ); + Assert.assertTrue("baseET should be running", waitFor(baseET::isExecuted, 1000)); + Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); + + + //schedule the sub Callables and make sure these are running + subList.forEach(sub -> sub.future = asyncTaskHelper.submitBaseSubCallable(sub.et::test)); + for (Sub sub : subList) { + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 100)); + Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", sub.future.isDone()); + } + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + + //On each iteration shut down a sub callable. Make sure it stops, the others are still running and the + // //base is still running. + while (!subList.isEmpty()) { + + //stop one sub and make sure it stopped + { + Sub sub = subList.removeFirst(); + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); + sub.et.isContinuous = false; + Assert.assertTrue("subET should not be running", waitForNot(sub.et::isExecuting,1000)); + Assert.assertTrue("subET Should not be Done", sub.future.isDone()); + } + + //make sure the other are still running + for (Sub sub : subList) { + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); + Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", sub.future.isDone()); + } + + //Make sure the Base is still running + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + } + + //let the base cancel itself and make sure it stops + baseET.cancelSelfOnNextExecution(baseFuture); + Assert.assertTrue("baseET should be done", waitFor(baseFuture::isDone, 1000)); + } + } + + + /** + * Make sure SubCallable cannot be scheduled when there is not BaseRunnable + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailWhenNoBase() throws Exception { + asyncTaskHelper.submitBaseSubCallable(()->null); + } + + + + /** + * Make sure SubCallable cannot be scheduled when BaseRunnable is cancelled but is still actively running. + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailWhenBaseCanceledBeforeisDone() throws Exception { + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + + Future future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + future.cancel(false); + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + + try { + asyncTaskHelper.submitBaseSubCallable(() -> null); + } finally { + et.isContinuous = false; + } + + + + } + + + /** + * Make sure SubCallable cannot be scheduled after a BaseRunnable has completed + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailAfterBaseDone() throws Exception { + + final ExecuteTest et = new ExecuteTest(); + + Future future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + + future.cancel(false); + Assert.assertTrue("It should not be running",waitFor(future::isDone,1000)); + + try { + asyncTaskHelper.submitBaseSubCallable(() -> null); + } finally { + et.isContinuous = false; + } + + } + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does not block when BaseRunnable is not scheduled + */ + @Test + public void test_cancel_noBlockingWhenBaseRunnableNotScheduled() throws Exception{ + //nothing is running so this should return immediately without TimeoutException + asyncTaskHelper.cancelBaseActionRunnable(AppcOam.RPC.stop , AppcOamStates.Started , 1, TimeUnit.MILLISECONDS); + } + + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does blocks until BaseRunnable is done scheduled + */ + @Test() + public void test_cancel_BlockingWhenBaseRunnableNotDone() throws Exception { + + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + et.isIgnoreInterrupt = true; + asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { + } + , initialDelayMillis + , delayMillis + ); + + Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); + + + //we should get a timeout + try { + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1, + TimeUnit.MILLISECONDS); + Assert.fail("Should have gotten TimeoutException"); + } catch (TimeoutException e) { + //just ignore as it is expected + } + + + //release the test thread + et.isContinuous = false; + + + //we should not get a timeout + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1000, + TimeUnit.MILLISECONDS); + + } + + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does not block when BaseRunnable is not scheduled + */ + @Test + public void test_BaseRunnableCancelCallback() throws Exception{ + + AtomicReference cancelCallback = new AtomicReference<>(null); + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + Future future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , cancelCallback::set + , initialDelayMillis + , delayMillis + ); + + Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); + Assert.assertTrue("It should be running", waitForNot(future::isDone, 1000)); + + + try { + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1, + TimeUnit.MILLISECONDS); + Assert.fail("Should have gotten TimeoutException"); + } catch (TimeoutException e) { + //just ignore as it is expected + } + + + Assert.assertEquals("Unexpected rpc in call back",AppcOam.RPC.stop,cancelCallback.get()); + } + + + + + + + + + /** + * @return true if the negation of the expected value is returned from the supplier within the specified + * amount of time + */ + private static boolean waitForNot(Supplier s,long timeoutMillis)throws Exception{ + return waitFor(()->!s.get(),timeoutMillis); + } + + + /** + * @return true if the expected value is returned from the supplier within the specified + * amount of time + */ + private static boolean waitFor(Supplier s,long timeoutMillis) throws Exception { + long timeout = TimeUnit.MILLISECONDS.toMillis(timeoutMillis); + long expiryTime = System.currentTimeMillis() + timeout; + long elapsedTime; + while(!s.get()){ + elapsedTime = expiryTime - System.currentTimeMillis(); + if(elapsedTime < 1) { + break; + } + Thread.sleep(10); + } + return s.get(); + } + + + /** + * This class is used control a thread executed in th {@link #test()} + */ + @SuppressWarnings("unused") + private static class ExecuteTest { + + + /** A fail safe to insure this TEst does not run indefinitely */ + private final long EXPIRY_TIME = System.currentTimeMillis() + 10000; + + + + /** A thread sets this value to true when it has completed the execution the of executes {@link #test()} */ + private volatile boolean isExecuted = false; + + /** + * A thread sets this value to true when it is actively executing {@link #test()} and back to false when + * it is not + */ + private volatile boolean isExecuting = false; + + /** + * While this value is true, a thread will not be allowed to return from {@link #test()} It will simulate a + * long execution. + */ + private volatile boolean isContinuous = false; + + /** + * When this value is set to true, an ongoing simulation of a long execution of {@link #test()} cannot be force + * to abort via a {@link Thread#interrupt()} + */ + private volatile boolean isIgnoreInterrupt = false; + + + + /** Use to send a signal to the thread executing {@link #notifyTestExcuted(long)} */ + private Semaphore inner = new Semaphore(0); + + /** Use to send a signal to the thread executing {@link #waitForTestExec(long)} */ + private Semaphore outer = new Semaphore(0); + + /** The {@link Future} of the Thread executing {@link #test()}*/ + private volatile Future future; + + /** + * When set the Thread executing {@link #test()} will cancel itself + * @param future - The {@link Future} of the Thread executing {@link #test()} + */ + private void cancelSelfOnNextExecution(Future future) { + this.future = future; + } + + + private boolean isExecuted() { + return isExecuted; + } + + private boolean isExecuting() { + return isExecuting; + } + + + private boolean isContinuous() { + return isContinuous; + } + + + private boolean isIgnoreInterrupt() { + return isIgnoreInterrupt; + } + + + + /** + * The thread executing this method if blocked from returning until the thread executing + * {@link #test()} invokes {@link #notifyTestExcuted(long)} or the specified time elapses + * @param timeoutMillis - the amount of time to wait for a execution iteration. + * @return true if the Thread is released because of an invocation of {@link #notifyTestExcuted(long)} + * @throws InterruptedException - If the Caller thread is interrupted. + */ + private boolean waitForTestExec(long timeoutMillis) throws InterruptedException { + inner.release(); + return outer.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); + } + + + /** + * Test simulator + * @return Always returns true. + */ + private Boolean test() { + isTestExpired(); + System.out.println("started"); + isExecuting = true; + try { + if (future != null) { + future.cancel(false); + } + if(!isContinuous){ + notifyTestExcuted(1); + } + + while(isContinuous){ + notifyTestExcuted(100); + isTestExpired(); + } + + } finally { + isExecuting = false; + isExecuted = true; + } + return true; + } + + + /** @throws RuntimeException if the test has bee running too long */ + private void isTestExpired(){ + if(System.currentTimeMillis() > EXPIRY_TIME){ + throw new RuntimeException("Something went wrong the test expired."); + } + } + + + /** + * The thread executing {@link #test()} if blocked from returning until another thread invokes + * {@link #waitForTestExec(long)} or the specified time elapses + * @param timeoutMillis - the amount of time to wait for a execution iteration. + * @return true if the Thread is released because of an invocation of {@link #waitForTestExec(long)} + */ + private boolean notifyTestExcuted(long timeoutMillis){ + try { + boolean acquire = inner.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); + if(acquire){ + outer.release(); + System.out.println("release"); + } + } catch (InterruptedException e) { + if(!isIgnoreInterrupt){ + return false; + } + } + return true; + } + } + + + static class Sub { + ExecuteTest et = new ExecuteTest(); + Future future = null; + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java new file mode 100644 index 000000000..433e87517 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang.ArrayUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.membermodification.MemberMatcher; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; + +@SuppressWarnings("ResultOfMethodCallIgnored") +@RunWith(PowerMockRunner.class) +@PrepareForTest({BundleHelper.class, FrameworkUtil.class}) +public class BundleHelperTest { + private BundleHelper bundleHelper; + private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); + + @Before + public void setUp() throws Exception { + bundleHelper = spy(new BundleHelper(null, null, null)); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(bundleHelper, "logger", mockLogger); + } + + @Test + public void testBundleOperations() throws Exception { + // spy mocked bundle for calls to method statr or stop. + // Note: the time of method calls are accumulated in this test method. + Bundle mockBundle = spy(Mockito.mock(Bundle.class)); + Map mapFromGetAppcLcmBundles = new HashMap<>(); + mapFromGetAppcLcmBundles.put("BundleString", mockBundle); + + PowerMockito.doReturn(mapFromGetAppcLcmBundles).when(bundleHelper, MemberMatcher.method( + BundleHelper.class, "getAppcLcmBundles")).withNoArguments(); + + StateHelper mockStateHelper = mock(StateHelper.class); + Whitebox.setInternalState(bundleHelper, "stateHelper", mockStateHelper); + + AppcOamStates appcOamStates = AppcOamStates.Stopped; + Mockito.doReturn(appcOamStates).when(mockStateHelper).getState(); + + // test start + Mockito.doReturn(true).when(mockStateHelper).isSameState(appcOamStates); + boolean result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); + + // test start aborted + Mockito.doReturn(false).when(mockStateHelper).isSameState(appcOamStates); + result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null); + Assert.assertFalse("Should be abort", result); + Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); + + // test stop + result = bundleHelper.bundleOperations(AppcOam.RPC.stop, new HashMap<>(), mockTaskHelper,null); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(2)).submitBaseSubCallable(any()); + } + + @Test(expected = APPCException.class) + public void testBundleOperationsRpcException() throws Exception { + bundleHelper.bundleOperations(AppcOam.RPC.maintenance_mode, new HashMap<>(), mockTaskHelper,null); + } + + @Test + public void testGetBundleList() throws Exception { + mockStatic(FrameworkUtil.class); + Bundle myBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); + + // test bundle context is null + Mockito.when(myBundle.getBundleContext()).thenReturn(null); + Assert.assertTrue("Should return null", bundleHelper.getBundleList() == null); + + BundleContext myBundleContext = mock(BundleContext.class); + Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext); + + // test bundle list is empty + Bundle[] bundleArray = {}; + Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); + Bundle[] results = bundleHelper.getBundleList(); + Assert.assertTrue("Should not be null", results != null); + Assert.assertTrue("Should not have any element", results.length == 0); + + // test bundle list has at one bundle + bundleArray = new Bundle[] { myBundle }; + Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); + results = bundleHelper.getBundleList(); + Assert.assertTrue("Should not be null", results != null); + Assert.assertTrue("Should have one element", results.length == 1); + Assert.assertEquals("Should be the mock bundle", myBundle, results[0]); + } + + @Test + public void testReadPropsFromPropListName() throws Exception { + // mock configuarion helper + ConfigurationHelper configurationHelper = new ConfigurationHelper(null); + EELFLogger fakeLogger = mock(EELFLogger.class); + Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); + Configuration fakeConf = mock(Configuration.class); + Whitebox.setInternalState(configurationHelper, "configuration", fakeConf); + + Whitebox.setInternalState(bundleHelper, "configurationHelper", configurationHelper); + + String propKey = "testing"; + // Property does not exist + Mockito.doReturn(null).when(fakeConf).getProperty(propKey); + String[] propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertArrayEquals("PropertyResult should be empty string array", + ArrayUtils.EMPTY_STRING_ARRAY, propResult); + // Property has one entry + String propValue1 = "1234"; + String propValue2 = "5678"; + Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); + Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); + propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); + Assert.assertEquals("PropertyResult should martch propertyValue", propValue2, propResult[0]); + // Property has two entries + propValue1 = "1234\n,4321"; + String propValue3 = "8765"; + Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); + Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); + Mockito.doReturn(propValue3).when(fakeConf).getProperty("4321"); + propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertTrue("PropertyResult should have two elements", propResult.length == 2); + List propResultList = Arrays.asList(propResult); + Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue2)); + Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue3)); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/ConfigurationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/ConfigurationHelperTest.java new file mode 100644 index 000000000..348517b72 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/ConfigurationHelperTest.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.configuration.Configuration; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; + +public class ConfigurationHelperTest { + private ConfigurationHelper configurationHelper; + + private Configuration mockConf; + private Configuration origConf; + + @Before + public void setUp() throws Exception { + mockConf = mock(Configuration.class); + + configurationHelper = new ConfigurationHelper(null); + + // to avoid operation on logger fail, mock up the logger + EELFLogger fakeLogger = mock(EELFLogger.class); + Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); + } + + private void setMockConf() { + origConf = Whitebox.getInternalState(configurationHelper, "configuration"); + Whitebox.setInternalState(configurationHelper, "configuration", mockConf); + } + + private void resetOrigConfig() { + Whitebox.setInternalState(configurationHelper, "configuration", origConf); + origConf = null; + } + + @Test + public void getAppcName() throws Exception { + // test with existing properties file + Assert.assertEquals("Should return value(APPC).", "APPC", configurationHelper.getAppcName()); + + // test with mockup + setMockConf(); + + String propValue = "testing"; + Mockito.doReturn(propValue).when(mockConf).getProperty(ConfigurationHelper.PROP_KEY_APPC_NAME); + Assert.assertEquals(String.format("Should return value(%s).", propValue), propValue, + configurationHelper.getAppcName()); + + resetOrigConfig(); + } + + @Test + public void isMetricEnabled() throws Exception { + // test with mockup + setMockConf(); + + Mockito.doReturn(false).when(mockConf).getBooleanProperty( + ConfigurationHelper.PROP_KEY_METRIC_STATE, false); + Assert.assertFalse("Should return false", configurationHelper.isMetricEnabled()); + + Mockito.doReturn(true).when(mockConf).getBooleanProperty( + ConfigurationHelper.PROP_KEY_METRIC_STATE, false); + Assert.assertTrue("Should return true", configurationHelper.isMetricEnabled()); + } + + @Test + public void testReadPropertyNotStop() throws Exception { + String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToNotStop"); + Assert.assertTrue(str.length > 0); + Assert.assertTrue(str[0].equals(".*appc.oam.*")); + } + + @Test + public void testReadPropertyStop() throws Exception { + String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToStop"); + Assert.assertTrue(str.length > 0); + Assert.assertTrue(str[0].equals(".*appc.*")); + } + + @Test + public void testReadPropertyWithMockup() throws Exception { + setMockConf(); + + String propKey = "testing"; + // Property does not exist + Mockito.doReturn(null).when(mockConf).getProperty(propKey); + String[] propResult = configurationHelper.readProperty(propKey); + Assert.assertArrayEquals("PropertyResult should be empty string array", + ArrayUtils.EMPTY_STRING_ARRAY, propResult); + // Property has one entry + String propValue = "1234"; + Mockito.doReturn(propValue).when(mockConf).getProperty(propKey); + propResult = configurationHelper.readProperty(propKey); + Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); + Assert.assertEquals("PropertyResult should martch propertyValue", propValue, propResult[0]); + + resetOrigConfig(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/OperationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/OperationHelperTest.java new file mode 100644 index 000000000..77edd1701 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/OperationHelperTest.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.common.header.Flags; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class OperationHelperTest { + private OperationHelper operationHelper; + private LifecycleManager lifecycleManager = mock(LifecycleManager.class); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + operationHelper = new OperationHelper(); + Whitebox.setInternalState(operationHelper, "lifecycleMgr", lifecycleManager); + } + + @Test + public void testIsInputValidWithMissingInput() throws Exception { + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); + + operationHelper.isInputValid(null); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingCommonHeader() throws Exception { + StartInput mockInput = mock(StartInput.class); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingOid() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn(null).when(mockCommonHeader).getOriginatorId(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingRid() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn(null).when(mockCommonHeader).getRequestId(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMmodeFlags() throws Exception { + MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); + Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.NOT_SUPPORT_FLAG); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidPass() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); + + //with Flags + Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); + operationHelper.isInputValid(mockInput); + + //without Flags + Mockito.doReturn(null).when(mockCommonHeader).getFlags(); + operationHelper.isInputValid(mockInput); + + // MaintenanceMode without Flags + MaintenanceModeInput mockInput1 = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput1).getCommonHeader(); + operationHelper.isInputValid(mockInput1); + } + + @Test + public void testGetCommonHeader() throws Exception { + CommonHeader commonHeader = mock(CommonHeader.class); + // for StartInput + StartInput startInput = mock(StartInput.class); + Mockito.doReturn(commonHeader).when(startInput).getCommonHeader(); + Assert.assertEquals("Should return startInput commonHeader", commonHeader, + operationHelper.getCommonHeader(startInput)); + + // for StopInput + StopInput stopInput = mock(StopInput.class); + Mockito.doReturn(commonHeader).when(stopInput).getCommonHeader(); + Assert.assertEquals("Should return stopInput commonHeader", commonHeader, + operationHelper.getCommonHeader(stopInput)); + + // for MaintenanceModeInput + MaintenanceModeInput mmInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(commonHeader).when(mmInput).getCommonHeader(); + Assert.assertEquals("Should return MaintenanceModeInput commonHeader", commonHeader, + operationHelper.getCommonHeader(mmInput)); + + // unsupported type + Assert.assertTrue("should return null", + operationHelper.getCommonHeader(new Object()) == null); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetService() throws Exception { + Class operationHelperClass = OperationHelper.class; + String className = operationHelperClass.getName(); + String exceptionMsg = String.format(operationHelper.NO_SERVICE_REF_FORMAT, className); + + mockStatic(FrameworkUtil.class); + Bundle bundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(operationHelperClass)).thenReturn(bundle); + + // No bundle context + Mockito.when(bundle.getBundleContext()).thenReturn(null); + expectedException.expect(APPCException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getService(operationHelperClass); + + // No service reference + BundleContext bundleContext = mock(BundleContext.class); + Mockito.when(bundle.getBundleContext()).thenReturn(bundleContext); + Mockito.when(bundleContext.getServiceReference(className)).thenReturn(null); + expectedException.expect(APPCException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getService(operationHelperClass); + + // Success path + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(bundleContext.getServiceReference(className)).thenReturn(svcRef); + expectedException = ExpectedException.none(); + Assert.assertTrue("should not be null", operationHelper.getService(operationHelperClass) != null); + } + + @Test + public void testGetNextState() throws Exception { + AppcOamMetaDataReader.AppcOperation operation = AppcOamMetaDataReader.AppcOperation.Start; + AppcOamStates currentState = AppcOamStates.Stopped; + String exceptionMsg = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, operation, "APPC", currentState); + + // got LifecycleException + Mockito.doThrow(LifecycleException.class).when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + expectedException.expect(InvalidStateException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getNextState(operation, currentState); + + // got NoTransitionDefinedException + Mockito.doThrow(NoTransitionDefinedException.class).when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + expectedException.expect(InvalidStateException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getNextState(operation, currentState); + + // Success path + expectedException = ExpectedException.none(); + Mockito.doReturn("starting").when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + Assert.assertEquals("Should return proper Starting state", AppcOamStates.Starting, + operationHelper.getNextState(operation, currentState)); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/StateHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/StateHelperTest.java new file mode 100644 index 000000000..9a3050e84 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/StateHelperTest.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({StateHelper.class}) +public class StateHelperTest { + private StateHelper stateHelper; + + @Before + public void setUp() throws Exception { + stateHelper = PowerMockito.spy(new StateHelper(null, null)); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(stateHelper, "logger", mockLogger); + } + + @Test + public void testSetState() throws Exception { + AppcOamStates appcOamStates = AppcOamStates.Started; + stateHelper.setState(appcOamStates); + Assert.assertEquals("Should have the new value", appcOamStates, + Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); + // reest to default value + stateHelper.setState(AppcOamStates.Unknown); + } + + @Test + public void testGetState() throws Exception { + AppcOamStates appcOamStates = stateHelper.getState(); + Assert.assertEquals("Should have the class value", appcOamStates, + Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); + } + + @Test + public void testIsSameState() throws Exception { + AppcOamStates classValue = Whitebox.getInternalState(stateHelper, "appcOamCurrentState"); + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + boolean isSame = stateHelper.isSameState(appcOamStates); + if (appcOamStates == classValue) { + Assert.assertTrue("Should be the same", isSame); + } else { + Assert.assertFalse("Should not be the same", isSame); + } + } + } + + @Test + public void testGetCurrentOamState() throws Exception { + AppcOamStates mockResult = AppcOamStates.Started; + // mock getBundlesState, as we are testin it separately + PowerMockito.doReturn(mockResult).when(stateHelper, "getBundlesState"); + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); + Assert.assertEquals("Should call deriveStatte and return mockeResult", + mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(1)).getBundlesState(); + + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); + Assert.assertEquals("Should call deriveStatte and return mockeResult", + mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(2)).getBundlesState(); + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", mockResult); + Assert.assertEquals("Should just return mockeResult", mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(2)).getBundlesState(); + } + + @Test + public void testGetCurrentOamYangState() throws Exception { + Map stateMap = new HashMap() { + { + put(AppcOamStates.EnteringMaintenanceMode, AppcState.EnteringMaintenanceMode); + put(AppcOamStates.MaintenanceMode, AppcState.MaintenanceMode); + put(AppcOamStates.Instantiated, AppcState.Instantiated); + put(AppcOamStates.NotInstantiated, AppcState.NotInstantiated); + put(AppcOamStates.Restarting, AppcState.Restarting); + put(AppcOamStates.Started, AppcState.Started); + put(AppcOamStates.Starting, AppcState.Starting); + put(AppcOamStates.Stopped, AppcState.Stopped); + put(AppcOamStates.Stopping, AppcState.Stopping); + put(AppcOamStates.Error, AppcState.Error); + put(AppcOamStates.Unknown, AppcState.Unknown); + } + }; + for (Map.Entry aEntry : stateMap.entrySet()) { + AppcOamStates aState = aEntry.getKey(); + AppcState appcState = aEntry.getValue(); + + PowerMockito.doReturn(aState).when(stateHelper, "getCurrentOamState"); + + AppcState resultState = stateHelper.getCurrentOamYangState(); + Assert.assertEquals( + String.format("%s state, returned(%s),should return(%s) state", aState, resultState, appcState), + appcState, resultState); + + } + } + + @Test + public void testGetBundlesState() throws Exception { + BundleHelper mockBundlerHelper = mock(BundleHelper.class); + PowerMockito.whenNew(BundleHelper.class).withAnyArguments().thenReturn(mockBundlerHelper); + + // test null bundle map + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(null); + Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); + + // tet empty bundle map + Map bundleMap = new HashMap<>(); + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); + Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); + + Bundle mockBundle1 = mock(Bundle.class); + Bundle mockBundle2 = mock(Bundle.class); + bundleMap.put("1", mockBundle1); + bundleMap.put("2", mockBundle2); + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); + + // test bundles have differnt states + Mockito.doReturn(Bundle.RESOLVED).when(mockBundle1).getState(); + Mockito.doReturn(Bundle.ACTIVE).when(mockBundle2).getState(); + Assert.assertEquals("Should return lower state", AppcOamStates.Stopped, stateHelper.getBundlesState()); + + // test bundles have the same state + Mockito.doReturn(Bundle.ACTIVE).when(mockBundle1).getState(); + Assert.assertEquals("Should return the state", AppcOamStates.Started, stateHelper.getBundlesState()); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java deleted file mode 100644 index 110198370..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.onap.appc.oam.processor.OamMmodeProcessor; -import org.onap.appc.oam.processor.OamRestartProcessor; -import org.onap.appc.oam.processor.OamStartProcessor; -import org.onap.appc.oam.processor.OamStopProcessor; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.spy; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({AppcOam.class, FrameworkUtil.class, Executors.class}) -public class AppcOamTest { - - private AppcOam appcOam; - private CommonHeader mockCommonHeader = mock(CommonHeader.class); - private Status mockStatus = mock(Status.class); - private OperationHelper mockOperationHelper = mock(OperationHelper.class); - private StateHelper mockStateHelper = mock(StateHelper.class); - - @Before - public void setUp() throws Exception { - appcOam = spy(new AppcOam(null, null, null)); - - Whitebox.setInternalState(appcOam, "stateHelper", mockStateHelper); - Whitebox.setInternalState(appcOam, "operationHelper", mockOperationHelper); - } - - @Test - public void testMaintenanceMode() throws Exception { - // mock processor creation - OamMmodeProcessor mockProcessor = mock(OamMmodeProcessor.class); - PowerMockito.mockStatic(OamMmodeProcessor.class); - PowerMockito.whenNew(OamMmodeProcessor.class).withAnyArguments().thenReturn(mockProcessor); - // mock input - MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - // mock processor result - Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); - - Future> response = appcOam.maintenanceMode(mockInput); - - Assert.assertEquals("Should have common header", mockCommonHeader, - response.get().getResult().getCommonHeader()); - Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); - } - - @Test - public void testStart() throws Exception { - // mock processor creation - OamStartProcessor mockProcessor = mock(OamStartProcessor.class); - PowerMockito.mockStatic(OamStartProcessor.class); - PowerMockito.whenNew(OamStartProcessor.class).withAnyArguments().thenReturn(mockProcessor); - // mock input - StartInput mockInput = mock(StartInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - // mock processor result - Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); - - Future> response = appcOam.start(mockInput); - - Assert.assertEquals("Should have common header", mockCommonHeader, - response.get().getResult().getCommonHeader()); - Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); - } - - @Test - public void testStop() throws Exception { - // mock processor creation - OamStopProcessor mockProcessor = mock(OamStopProcessor.class); - PowerMockito.mockStatic(OamStopProcessor.class); - PowerMockito.whenNew(OamStopProcessor.class).withAnyArguments().thenReturn(mockProcessor); - // mock input - StopInput mockInput = mock(StopInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - // mock processor result - Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); - - Future> response = appcOam.stop(mockInput); - - Assert.assertEquals("Should have common header", mockCommonHeader, - response.get().getResult().getCommonHeader()); - Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); - } - - @Test - public void testRestart() throws Exception { - // mock processor creation - OamRestartProcessor mockProcessor = mock(OamRestartProcessor.class); - PowerMockito.mockStatic(OamRestartProcessor.class); - PowerMockito.whenNew(OamRestartProcessor.class).withAnyArguments().thenReturn(mockProcessor); - // mock input - RestartInput mockInput = mock(RestartInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - // mock processor result - Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); - - Future> response = appcOam.restart(mockInput); - - Assert.assertEquals("Should have common header", mockCommonHeader, - response.get().getResult().getCommonHeader()); - Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); - } - - @Test - public void testGetAppcState() throws Exception { - AppcState appcState = AppcState.Started; - Mockito.doReturn(appcState).when(mockStateHelper).getCurrentOamYangState(); - - Future> state = appcOam.getAppcState(); - Assert.assertEquals("Should return the same state", - appcState, state.get().getResult().getState()); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/OAMCommandStatusTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/OAMCommandStatusTest.java deleted file mode 100644 index 269c4f811..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/OAMCommandStatusTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.executor.objects.Params; - -import java.util.HashMap; -import java.util.Map; - -public class OAMCommandStatusTest { - private Map CODE_MAP = new HashMap() { - { - put(OAMCommandStatus.ABORT, 304); - put(OAMCommandStatus.ACCEPTED, 100); - put(OAMCommandStatus.INVALID_PARAMETER, 302); - put(OAMCommandStatus.REJECTED, 300); - put(OAMCommandStatus.SUCCESS, 400); - put(OAMCommandStatus.TIMEOUT, 303); - put(OAMCommandStatus.UNEXPECTED_ERROR, 200); - } - }; - private Map MSG_MAP = new HashMap() { - { - put(OAMCommandStatus.ABORT, "OPERATION ABORT - ${errorMsg}"); - put(OAMCommandStatus.ACCEPTED, "ACCEPTED - request accepted"); - put(OAMCommandStatus.INVALID_PARAMETER, "INVALID PARAMETER - ${errorMsg}"); - put(OAMCommandStatus.REJECTED, "REJECTED - ${errorMsg}"); - put(OAMCommandStatus.SUCCESS, "SUCCESS - request has been processed successfully"); - put(OAMCommandStatus.TIMEOUT, "OPERATION TIMEOUT REACHED - ${errorMsg}"); - put(OAMCommandStatus.UNEXPECTED_ERROR, "UNEXPECTED ERROR - ${errorMsg}"); - } - }; - - @Test - public void testGetResponseMessage() throws Exception { - for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { - String expectedMsg = MSG_MAP.get(oamCommandStatus); - Assert.assertEquals(String.format("Should have message (%s).", expectedMsg), - expectedMsg, oamCommandStatus.getResponseMessage()); - } - } - - @Test - public void testGetResponseCode() throws Exception { - for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { - Integer expectedCode = CODE_MAP.get(oamCommandStatus); - Assert.assertEquals(String.format("Should have code (%d).", expectedCode), - expectedCode, Integer.valueOf(oamCommandStatus.getResponseCode())); - } - } - - @Test - public void testGetFormattedMessage() throws Exception { - String message = "test message"; - Params params = new Params().addParam("errorMsg", message); - for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { - String expectedMsg1 = MSG_MAP.get(oamCommandStatus); - String expectedMsg2 = expectedMsg1.replaceAll("\\$\\{errorMsg\\}", message); - Assert.assertEquals("Should returned " + expectedMsg1, - expectedMsg1, oamCommandStatus.getFormattedMessage(null)); - Assert.assertEquals("Should returned " + expectedMsg2, - expectedMsg2, oamCommandStatus.getFormattedMessage(params)); - } - } - - @Test - public void testToString() throws Exception { - for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { - String expectedString = String.format(oamCommandStatus.TO_STRING_FORMAT, - CODE_MAP.get(oamCommandStatus), MSG_MAP.get(oamCommandStatus)); - Assert.assertEquals(String.format("Should have string (%s).", expectedString), - expectedString, oamCommandStatus.toString()); - } - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java deleted file mode 100644 index d3ebfda51..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.messageadapter; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; - -import org.mockito.Mockito; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.HashSet; - -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MessageAdapter.class, FrameworkUtil.class}) -public class MessageAdapterTest { - - private Producer fakeProducer; - - private MessageAdapter messageAdapter; - - - @Before - public final void setup() throws Exception { - fakeProducer = mock(Producer.class); - messageAdapter = new MessageAdapter(); - } - - @Test - public void testGetProducerReturnsNull() throws Exception { - MessageAdapter maSpy = Mockito.spy(messageAdapter); - Mockito.doNothing().when(maSpy).createProducer(); - - Producer producer = maSpy.getProducer(); - Assert.assertTrue("getProducer() did not return null", producer == null); - Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); - Assert.assertTrue("MessageAdapter producer is not null", mySpyProducer == null); - Mockito.verify(maSpy, Mockito.times(1)).createProducer(); - } - - @Test - public void testGetProducerWithExistingProducer() throws Exception { - MessageAdapter maSpy = Mockito.spy(messageAdapter); - Whitebox.setInternalState(maSpy, "producer", fakeProducer); - - Producer producer = maSpy.getProducer(); - Assert.assertTrue("getProducer() returned null", producer == fakeProducer); - Mockito.verify(maSpy, Mockito.times(0)).createProducer(); - } - - @Test - public void testGetProducerWithCreateProducer() throws Exception { - MessageAdapter maSpy = Mockito.spy(messageAdapter); - Whitebox.setInternalState(maSpy, "producer", (Object) null); - HashSet pool = new HashSet<>(); - Whitebox.setInternalState(maSpy, "pool", pool); - - // Prepare all mocks - mockStatic(FrameworkUtil.class); - Bundle maBundle = mock(Bundle.class); - PowerMockito.when(FrameworkUtil.getBundle(MessageAdapter.class)).thenReturn(maBundle); - - BundleContext maBundleContext = mock(BundleContext.class); - Mockito.when(maBundle.getBundleContext()).thenReturn(maBundleContext); - - ServiceReference svcRef = mock(ServiceReference.class); - Mockito.when(maBundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(svcRef); - - MessageAdapterFactory maFactory = mock(MessageAdapterFactory.class); - Mockito.when(maBundleContext.getService(svcRef)).thenReturn(maFactory); - Mockito.when(maFactory.createProducer(pool, (String) null, null, null)).thenReturn(fakeProducer); - - Producer producer = maSpy.getProducer(); - Assert.assertTrue("getProducer() result does not match", producer == fakeProducer); - Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); - Assert.assertTrue("MessageAdapter producer does not match",mySpyProducer == fakeProducer); - Mockito.verify(maSpy, Mockito.times(1)).createProducer(); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java deleted file mode 100644 index daf0f6e07..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java +++ /dev/null @@ -1,293 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.BundleHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.powermock.reflect.Whitebox; - -import java.util.Date; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; - -public class BaseActionRunnableTest { - private AppcOam.RPC testRpc = AppcOam.RPC.maintenance_mode; - private AppcOamStates targetState = AppcOamStates.MaintenanceMode; - - private class TestProcessor extends BaseProcessor { - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelperIn for property reading - * @param stateHelperIn for APP-C OAM state checking - * @param asyncTaskHelperIn for scheduling async task - * @param operationHelperIn for operational helper - */ - TestProcessor(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn, - AsyncTaskHelper asyncTaskHelperIn, - OperationHelper operationHelperIn) { - super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); - - // must set rpc and auditMsg - rpc = testRpc; - auditMsg = Msg.OAM_OPERATION_STARTING; - startTime = new Date(); - } - } - - class TestAbc extends BaseActionRunnable { - boolean doActionResult; - - TestAbc(BaseProcessor parent) { - super(parent); - - actionName = "testing"; - auditMsg = Msg.OAM_OPERATION_MAINTENANCE_MODE; - finalState = targetState; - } - - @Override - boolean doAction() { - return doActionResult; - } - } - - private TestAbc testBaseAcionRunnable; - private BaseProcessor testProcessor; - private StateHelper mockStateHelper = mock(StateHelper.class); - private OperationHelper mockOperHelper = mock(OperationHelper.class); - private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); - private BundleHelper mockBundleHelper = mock(BundleHelper.class); - - @SuppressWarnings("ResultOfMethodCallIgnored") - @Before - public void setUp() throws Exception { - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - - testProcessor = spy( - new TestProcessor(mockLogger, mockConfigHelper, mockStateHelper, null, mockOperHelper)); - Whitebox.setInternalState(testProcessor, "bundleHelper", mockBundleHelper); - - testBaseAcionRunnable = spy(new TestAbc(testProcessor)); - Whitebox.setInternalState(testBaseAcionRunnable, "commonHeader", mock(CommonHeader.class)); - } - - @Test - public void testSetTimeoutValues() throws Exception { - Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); - long expectedTimeout = 10000L; - Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); - testBaseAcionRunnable.setTimeoutValues(); - Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); - Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); - Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); - - Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); - expectedTimeout = 20000L; - Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); - testBaseAcionRunnable.setTimeoutValues(); - Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); - Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); - Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); - - Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); - Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); - expectedTimeout = 0L; - Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); - testBaseAcionRunnable.setTimeoutValues(); - Assert.assertEquals("Should set timeoutMs", expectedTimeout, testBaseAcionRunnable.timeoutMs); - Assert.assertTrue("Should not set start time MS", testBaseAcionRunnable.startTimeMs == 0); - Assert.assertFalse("Should not do check", testBaseAcionRunnable.doTimeoutChecking); - } - - @Test - public void testRun() throws Exception { - // test doAction failed - Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", false); - testBaseAcionRunnable.run(); - Assert.assertFalse("isWaiting should still be false", - Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); - - // test doAction success - Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", true); - - // with checkState return true - Mockito.doReturn(true).when(testBaseAcionRunnable).checkState(); - testBaseAcionRunnable.run(); - Assert.assertFalse("isWaiting should still be false", - Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); - - // with checkState return false - Mockito.doReturn(false).when(testBaseAcionRunnable).checkState(); - testBaseAcionRunnable.run(); - Assert.assertTrue("isWaiting should still be true", - Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); - - // should stay - testBaseAcionRunnable.run(); - Mockito.verify(testBaseAcionRunnable, times(1)).keepWaiting(); - } - - @Test - public void testSetAbortStatus() throws Exception { - testBaseAcionRunnable.setAbortStatus(); - Assert.assertEquals("Should return abort code", OAMCommandStatus.ABORT.getResponseCode(), - testBaseAcionRunnable.status.getCode().intValue()); - Assert.assertTrue("Should set abort due to execution error message", - testBaseAcionRunnable.status.getMessage().endsWith( - String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, - testRpc.name(), testBaseAcionRunnable.DUE_TO_EXECUTION_ERROR))); - } - - @Test - public void testCheckState() throws Exception { - // 1. with isTimeout true - Mockito.doReturn(true).when(testBaseAcionRunnable).isTimeout("checkState"); - Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); - - // 2. with isTimeout false and - Mockito.doReturn(false).when(testBaseAcionRunnable).isTimeout("checkState"); - - // 2.1 with task not all done - Mockito.doReturn(false).when(mockBundleHelper).isAllTaskDone(any()); - Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); - - // 2. 2 with task all done - Mockito.doReturn(true).when(mockBundleHelper).isAllTaskDone(any()); - - // 2.2.1 with has bundle failure - Mockito.doReturn(true).when(testBaseAcionRunnable).hasBundleOperationFailure(); - Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); - - // 2.2.2 with no bundle failure - Mockito.doReturn(false).when(testBaseAcionRunnable).hasBundleOperationFailure(); - - Mockito.doReturn(targetState).when(mockStateHelper).getBundlesState(); - Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); - - Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getBundlesState(); - Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); - } - - @Test - public void testPostAction() throws Exception { - Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); - // set status to avoid NPE when using status - testBaseAcionRunnable.setAbortStatus(); - - // test no parameter - testBaseAcionRunnable.postAction(null); - Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); - Mockito.verify(mockStateHelper, times(0)).setState(any()); - Mockito.verify(testProcessor, times(1)).cancelAsyncTask(); - - // test with parameter - testBaseAcionRunnable.postAction(AppcOamStates.Error); - Mockito.verify(mockOperHelper, times(2)).sendNotificationMessage(any(), any(), any()); - Mockito.verify(mockStateHelper, times(1)).setState(any()); - Mockito.verify(testProcessor, times(2)).cancelAsyncTask(); - } - - @Test - public void testIsTimeout() throws Exception { - String parentName = "testing"; - Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); - Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); - - Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); - Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", true); - Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", System.currentTimeMillis() + 100); - Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); - Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); - - long timeoutMs = 1; - Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", timeoutMs); - Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); - Assert.assertTrue("Should be timeout", testBaseAcionRunnable.isTimeout(parentName)); - Mockito.verify(testBaseAcionRunnable, times(1)).postAction(any()); - Assert.assertEquals("Should return timeout code", OAMCommandStatus.TIMEOUT.getResponseCode(), - testBaseAcionRunnable.status.getCode().intValue()); - Assert.assertTrue("Should set timeout message", - testBaseAcionRunnable.status.getMessage().endsWith( - String.format(testBaseAcionRunnable.TIMEOUT_MESSAGE_FORMAT, testRpc.name(), timeoutMs))); - } - - @SuppressWarnings("unchecked") - @Test - public void testHasBundleOperationFailure() throws Exception { - Mockito.when(mockBundleHelper.getFailedMetrics(anyMap())).thenReturn(Long.valueOf("0")); - Assert.assertFalse("should return false", testBaseAcionRunnable.hasBundleOperationFailure()); - - Mockito.when(mockStateHelper.getCurrentOamState()).thenReturn(AppcOamStates.Restarting); - long failedNumber = 1; - Mockito.doReturn(failedNumber).when(mockBundleHelper).getFailedMetrics(anyMap()); - Assert.assertTrue("should return true", testBaseAcionRunnable.hasBundleOperationFailure()); - Mockito.verify(testBaseAcionRunnable, times(1)).setStatus(OAMCommandStatus.UNEXPECTED_ERROR, - String.format(testBaseAcionRunnable.BUNDLE_OPERATION_FAILED_FORMAT, failedNumber)); - Mockito.verify(testBaseAcionRunnable, times(1)).postAction(AppcOamStates.Error); - } - - @Test - public void testAbortRunnable() throws Exception { - Mockito.doReturn(AppcOamStates.Restarting).when(mockStateHelper).getCurrentOamState(); - AppcOam.RPC newRpc = AppcOam.RPC.restart; - testBaseAcionRunnable.abortRunnable(newRpc); - Assert.assertEquals("Should return abort code", OAMCommandStatus.ABORT.getResponseCode(), - testBaseAcionRunnable.status.getCode().intValue()); - Assert.assertTrue("Should set abort due to new request message", - testBaseAcionRunnable.status.getMessage().endsWith( - String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, testRpc.name(), - String.format(testBaseAcionRunnable.NEW_RPC_OPERATION_REQUEST, newRpc.name())))); - Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); - Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(false); - Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(true); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java deleted file mode 100644 index 59bddb0e4..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java +++ /dev/null @@ -1,182 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.slf4j.MDC; - -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({BaseCommon.class, MDC.class}) -public class BaseCommonTest { - private class TestAbc extends BaseCommon { - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelperIn for property reading - * @param stateHelperIn for APP-C OAM state checking - * @param operationHelperIn for operational helper - */ - TestAbc(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn, - OperationHelper operationHelperIn) { - super(eelfLogger, configurationHelperIn, stateHelperIn, operationHelperIn); - } - } - - private TestAbc testBaseCommon; - private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); - private StateHelper mockStateHelper = mock(StateHelper.class); - private CommonHeader mockCommonHeader = mock(CommonHeader.class); - - @Before - public void setUp() throws Exception { - testBaseCommon = spy(new TestAbc(null, mockConfigHelper, mockStateHelper, null)); - - Whitebox.setInternalState(testBaseCommon, "commonHeader", mockCommonHeader); - Whitebox.setInternalState(testBaseCommon, "rpc", AppcOam.RPC.maintenance_mode); - - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - Whitebox.setInternalState(testBaseCommon, "logger", mockLogger); - } - - @Test - public void testSetStatus() throws Exception { - OAMCommandStatus oamCommandStatus = OAMCommandStatus.ACCEPTED; - testBaseCommon.setStatus(oamCommandStatus); - Status status = testBaseCommon.status; - Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); - Assert.assertEquals("Should have message", oamCommandStatus.getResponseMessage(), status.getMessage()); - } - - @Test - public void testSetStatusWithParams() throws Exception { - String message = "testing"; - OAMCommandStatus oamCommandStatus = OAMCommandStatus.REJECTED; - testBaseCommon.setStatus(oamCommandStatus, message); - Status status = testBaseCommon.status; - Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); - Assert.assertTrue("Should have message", status.getMessage().endsWith(message)); - } - - @Test - public void testSetErrorStatus() throws Exception { - Mockito.doReturn("testName").when(mockConfigHelper).getAppcName(); - Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); - Mockito.doReturn("testRequestId").when(mockCommonHeader).getRequestId(); - Mockito.doReturn("testOrigId").when(mockCommonHeader).getOriginatorId(); - - String exceptionMessage = "testing"; - - OAMCommandStatus oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER; - Throwable t = new InvalidInputException(exceptionMessage); - testBaseCommon.setErrorStatus(t); - Status status = testBaseCommon.status; - Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); - Mockito.verify(testBaseCommon, times(1)).resetLogProperties(false); - Mockito.verify(testBaseCommon, times(1)).resetLogProperties(true); - - oamCommandStatus = OAMCommandStatus.REJECTED; - t = new InvalidStateException(exceptionMessage); - testBaseCommon.setErrorStatus(t); - status = testBaseCommon.status; - Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); - Mockito.verify(testBaseCommon, times(2)).resetLogProperties(false); - Mockito.verify(testBaseCommon, times(2)).resetLogProperties(true); - - oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; - t = new NullPointerException(exceptionMessage); - testBaseCommon.setErrorStatus(t); - status = testBaseCommon.status; - Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); - Mockito.verify(testBaseCommon, times(3)).resetLogProperties(false); - Mockito.verify(testBaseCommon, times(3)).resetLogProperties(true); - } - - @Test - public void testSetInitialLogProperties() throws Exception { - mockStatic(MDC.class); - testBaseCommon.setInitialLogProperties(); - PowerMockito.verifyStatic(times(5)); - } - - @Test - public void testClearRequestLogProperties() throws Exception { - mockStatic(MDC.class); - testBaseCommon.clearRequestLogProperties(); - PowerMockito.verifyStatic(times(5)); - } - - @Test - public void testResetLogProperties() throws Exception { - testBaseCommon.setInitialLogProperties(); - - testBaseCommon.resetLogProperties(false); - Mockito.verify(mockCommonHeader, times(2)).getRequestId(); - Mockito.verify(mockCommonHeader, times(2)).getOriginatorId(); - Map oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); - Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); - - testBaseCommon.resetLogProperties(false); - Mockito.verify(mockCommonHeader, times(3)).getRequestId(); - Mockito.verify(mockCommonHeader, times(3)).getOriginatorId(); - - // test oldMdcMap is cleared - testBaseCommon.resetLogProperties(false); - Mockito.verify(mockCommonHeader, times(4)).getRequestId(); - Mockito.verify(mockCommonHeader, times(4)).getOriginatorId(); - oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); - Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java deleted file mode 100644 index 6769352c6..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.processor; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.oam.OAMCommandStatus; -import org.onap.appc.oam.util.AsyncTaskHelper; -import org.onap.appc.oam.util.ConfigurationHelper; -import org.onap.appc.oam.util.OperationHelper; -import org.onap.appc.oam.util.StateHelper; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.powermock.reflect.Whitebox; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; - -@SuppressWarnings("ResultOfMethodCallIgnored") -public class BaseProcessorTest { - private AppcOam.RPC testRpc = AppcOam.RPC.start; - private AppcOamStates currentState = AppcOamStates.Stopped; - - private class TestAbc extends BaseProcessor { - - /** - * Constructor - * - * @param eelfLogger for logging - * @param configurationHelperIn for property reading - * @param stateHelperIn for APP-C OAM state checking - * @param asyncTaskHelperIn for scheduling async task - * @param operationHelperIn for operational helper - */ - TestAbc(EELFLogger eelfLogger, - ConfigurationHelper configurationHelperIn, - StateHelper stateHelperIn, - AsyncTaskHelper asyncTaskHelperIn, - OperationHelper operationHelperIn) { - super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); - - // must set rpc and auditMsg - rpc = testRpc; - auditMsg = Msg.OAM_OPERATION_STARTING; - } - } - - private TestAbc testBaseProcessor; - private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); - private StateHelper mockStateHelper = mock(StateHelper.class); - private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); - private OperationHelper mockOperHelper = mock(OperationHelper.class); - - private StartInput mockInput = mock(StartInput.class); - private CommonHeader mockCommonHeader = mock(CommonHeader.class); - - @Before - public void setUp() throws Exception { - Mockito.doReturn(mockCommonHeader).when(mockOperHelper).getCommonHeader(mockInput); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - - testBaseProcessor = spy( - new TestAbc(null, mockConfigHelper, mockStateHelper, mockTaskHelper, mockOperHelper)); - - Whitebox.setInternalState(testBaseProcessor, "commonHeader", mockCommonHeader); - - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - Whitebox.setInternalState(testBaseProcessor, "logger", mockLogger); - } - - @Test - public void testProcessRequestError() throws Exception { - Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); - Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); - Status status = testBaseProcessor.processRequest(mockInput); - Assert.assertEquals("Should return reject", - OAMCommandStatus.INVALID_PARAMETER.getResponseCode(), status.getCode().intValue()); - } - - @Test - public void testProcessRequest() throws Exception { - Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); - Mockito.doReturn(AppcOamStates.Starting).when(mockOperHelper).getNextState(any(), any()); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - Status status = testBaseProcessor.processRequest(mockInput); - Assert.assertEquals("Should return success", - OAMCommandStatus.ACCEPTED.getResponseCode(), status.getCode().intValue()); - } - - @Test(expected = InvalidInputException.class) - public void testPreProcessWithInvalidInput() throws Exception { - Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); - testBaseProcessor.preProcess(mockInput); - } - - @Test(expected = InvalidStateException.class) - public void testPreProcessWithInvalidState() throws Exception { - Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); - Mockito.doThrow(new InvalidStateException("test")) - .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); - testBaseProcessor.preProcess(mockInput); - } - - @Test(expected = APPCException.class) - public void testPreProcessWithAppcException() throws Exception { - Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); - Mockito.doThrow(new APPCException("test")) - .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); - testBaseProcessor.preProcess(mockInput); - } - - @Test - public void testPreProcess() throws Exception { - Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); - AppcOamStates nextState = AppcOamStates.Starting; - Mockito.doReturn(nextState) - .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); - testBaseProcessor.preProcess(mockInput); - Mockito.verify(mockOperHelper, times(1)).isInputValid(mockInput); - Mockito.verify(mockOperHelper, times(1)).getNextState(testRpc.getAppcOperation(), currentState); - Mockito.verify(mockStateHelper, times(1)).setState(nextState); - } - - @Test - public void testScheduleAsyncTask() throws Exception { - // test no runnable - testBaseProcessor.scheduleAsyncTask(); - Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "runnable") == null); - Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); - - BaseActionRunnable mockRunnable = mock(BaseActionRunnable.class); - Whitebox.setInternalState(testBaseProcessor, "runnable", mockRunnable); - testBaseProcessor.scheduleAsyncTask(); - // scheduledRunnable should still be null, there's no mock done - // as I have trouble to make mockTaskHelper.scheduleBaseRunnable to return a proper Future - Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); - } - -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java deleted file mode 100644 index ddeb99440..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java +++ /dev/null @@ -1,665 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.LinkedList; -import java.util.concurrent.Future; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({FrameworkUtil.class}) -public class AsyncTaskHelperTest { - private AsyncTaskHelper asyncTaskHelper; - - private long initialDelayMillis = 0; - private long delayMillis = 10; - - - @Before - public void setUp() throws Exception { - - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - - - mockStatic(FrameworkUtil.class); - Bundle myBundle = mock(Bundle.class); - Mockito.doReturn("TestBundle").when(myBundle).getSymbolicName(); - PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); - - asyncTaskHelper = new AsyncTaskHelper(mockLogger); - - - } - - - @After - public void shutdown(){ - asyncTaskHelper.close(); - } - - - /** - * Test that Base Runnable - * - * Runs at a fix rate; - * Only one Base Runnable can be scheduled at time; - * Future.cancle stops the Base Runnable; - * That another Base Runnable can be scheduled once the previous isDone. - */ - @Test - public void test_scheduleBaseRunnable_Base_isDone() throws Exception{ - - - - //loop is to test we can run consecutive Base Runnable - for(int testIteration = 0; testIteration < 3;testIteration++){ - final ExecuteTest et = new ExecuteTest(); - - Future future = asyncTaskHelper.scheduleBaseRunnable( - et::test - , s -> { } - ,initialDelayMillis - ,delayMillis - ); - - //make sure it is running at a fix rate - Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); - Assert.assertFalse("It Should not be Done", future.isDone()); - Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); - Assert.assertFalse("It Should not be Done", future.isDone()); - - - //make sure a seconds Runnable cannot be scheduled when one is already running - try { - asyncTaskHelper.scheduleBaseRunnable(et::test - , s -> {} - ,initialDelayMillis - ,delayMillis - ); - Assert.fail("scheduling should have been prevented. "); - } catch (IllegalStateException e) { - //IllegalStateException means the second scheduling was not allowed. - } - - - //let it cancel itself - et.cancelSelfOnNextExecution(future); - - //it should be done after it executes itself one more time. - Assert.assertTrue("it should be done", waitFor(future::isDone, 5000)); - Assert.assertTrue("The test failed to execute", et.isExecuted); - } - - - } - - - /** - * Makes sure the Future.isDone one only returns true if its runnable is not currently executing and will not - * execute in the future. Default implementation of isDone() returns true immediately after the future is - * canceled -- Even if is there is still a thread actively executing the runnable - */ - @Test - public void test_scheduleBaseRunnable_Base_isDone_Ignore_Interrupt() throws Exception{ - - - final ExecuteTest et = new ExecuteTest(); - - //configure test to run long and ignore interrupt - et.isContinuous = true; - et.isIgnoreInterrupt = true; - - - - Future future = asyncTaskHelper.scheduleBaseRunnable( - et::test - , s->{} - ,initialDelayMillis - ,delayMillis - ); - - //make sure it is running - Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); - Assert.assertTrue("It should be running",et.waitForTestExec(1000)); - Assert.assertFalse("It Should not be Done", future.isDone()); - - //cancel it and make sure it is still running - future.cancel(true); - Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); - Assert.assertTrue("It should be running",et.waitForTestExec(1000)); - Assert.assertFalse("It Should not be Done", future.isDone()); - - //let the thread die and then make sure its done - et.isContinuous = false; - Assert.assertTrue("It should not be running",waitForNot(et::isExecuting,1000)); - Assert.assertTrue("It Should be Done", future.isDone()); - - } - - - - - /** - * Make sure the base Future.isDone returns false until the sub callable has completed execution. - */ - @Test - public void test_scheduleBaseRunnable_SubTask_isDone_Ignore_Interrupt() throws Exception{ - - - final ExecuteTest baseET = new ExecuteTest(); - final ExecuteTest subET = new ExecuteTest(); - - //configure sub test to run long and ignore interrupt - subET.isContinuous = true; - subET.isIgnoreInterrupt = true; - - - //schedule the Base test to run and make sure it is running. - Future baseFuture = asyncTaskHelper.scheduleBaseRunnable( - baseET::test - ,s->{} - ,initialDelayMillis - ,delayMillis - ); - Assert.assertTrue("baseET should be running",waitFor(baseET::isExecuted,1000)); - Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); - - - //schedule the sub task and make sure it is running - Future subFuture = asyncTaskHelper.submitBaseSubCallable(subET::test); - Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); - Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); - Assert.assertFalse("subET Should not be Done", subFuture.isDone()); - Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); - - //cancel the base task and make sure isDone is still false - baseFuture.cancel(true); - Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); - Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); - Assert.assertFalse("subET Should not be Done",subFuture.isDone()); - Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); - - - //let the sub task die and and make sure the base is now finally done - subET.isContinuous = false; - Assert.assertTrue("subET should not be running",waitForNot(subET::isExecuting,1000)); - Assert.assertTrue("subET Should be Done", subFuture.isDone()); - Assert.assertTrue("baseET Should be Done", baseFuture.isDone()); - - } - - - /** - * Make sure the base Future.isDone returns false until the 3 sub callable has completed execution. - * Each sub callable will be shutdown one at a time. - */ - @Test - public void test_scheduleBaseRunnable_SubTasks_isDone() throws Exception { - - - //loop is to test we can run consecutive Base Runnable - for (int testIteration = 0; testIteration < 3; testIteration++) { - final ExecuteTest baseET = new ExecuteTest(); - final LinkedList subList = new LinkedList<>(); - for (int i = 0; i < 3; i++) { - Sub sub = new Sub(); - sub.et.isContinuous = true; - subList.add(sub); - } - - - //schedule the base runnable and make sure it is running - Future baseFuture = asyncTaskHelper.scheduleBaseRunnable( - baseET::test - , s -> { - } - , initialDelayMillis - , delayMillis - ); - Assert.assertTrue("baseET should be running", waitFor(baseET::isExecuted, 1000)); - Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); - - - //schedule the sub Callables and make sure these are running - subList.forEach(sub -> sub.future = asyncTaskHelper.submitBaseSubCallable(sub.et::test)); - for (Sub sub : subList) { - Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 100)); - Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); - Assert.assertFalse("subET Should not be Done", sub.future.isDone()); - } - Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); - - - //On each iteration shut down a sub callable. Make sure it stops, the others are still running and the - // //base is still running. - while (!subList.isEmpty()) { - - //stop one sub and make sure it stopped - { - Sub sub = subList.removeFirst(); - Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); - sub.et.isContinuous = false; - Assert.assertTrue("subET should not be running", waitForNot(sub.et::isExecuting,1000)); - Assert.assertTrue("subET Should not be Done", sub.future.isDone()); - } - - //make sure the other are still running - for (Sub sub : subList) { - Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); - Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); - Assert.assertFalse("subET Should not be Done", sub.future.isDone()); - } - - //Make sure the Base is still running - Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); - } - - //let the base cancel itself and make sure it stops - baseET.cancelSelfOnNextExecution(baseFuture); - Assert.assertTrue("baseET should be done", waitFor(baseFuture::isDone, 1000)); - } - } - - - /** - * Make sure SubCallable cannot be scheduled when there is not BaseRunnable - */ - @Test(expected=IllegalStateException.class) - public void test_SubTasksScheduleFailWhenNoBase() throws Exception { - asyncTaskHelper.submitBaseSubCallable(()->null); - } - - - - /** - * Make sure SubCallable cannot be scheduled when BaseRunnable is cancelled but is still actively running. - */ - @Test(expected=IllegalStateException.class) - public void test_SubTasksScheduleFailWhenBaseCanceledBeforeisDone() throws Exception { - - final ExecuteTest et = new ExecuteTest(); - et.isContinuous = true; - - Future future = asyncTaskHelper.scheduleBaseRunnable( - et::test - , s -> { } - ,initialDelayMillis - ,delayMillis - ); - - Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); - future.cancel(false); - Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); - - try { - asyncTaskHelper.submitBaseSubCallable(() -> null); - } finally { - et.isContinuous = false; - } - - - - } - - - /** - * Make sure SubCallable cannot be scheduled after a BaseRunnable has completed - */ - @Test(expected=IllegalStateException.class) - public void test_SubTasksScheduleFailAfterBaseDone() throws Exception { - - final ExecuteTest et = new ExecuteTest(); - - Future future = asyncTaskHelper.scheduleBaseRunnable( - et::test - , s -> { } - ,initialDelayMillis - ,delayMillis - ); - - - future.cancel(false); - Assert.assertTrue("It should not be running",waitFor(future::isDone,1000)); - - try { - asyncTaskHelper.submitBaseSubCallable(() -> null); - } finally { - et.isContinuous = false; - } - - } - - - /** - * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} - * Test cancel does not block when BaseRunnable is not scheduled - */ - @Test - public void test_cancel_noBlockingWhenBaseRunnableNotScheduled() throws Exception{ - //nothing is running so this should return immediately without TimeoutException - asyncTaskHelper.cancelBaseActionRunnable(AppcOam.RPC.stop , AppcOamStates.Started , 1, TimeUnit.MILLISECONDS); - } - - - - /** - * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} - * Test cancel does blocks until BaseRunnable is done scheduled - */ - @Test() - public void test_cancel_BlockingWhenBaseRunnableNotDone() throws Exception { - - - final ExecuteTest et = new ExecuteTest(); - et.isContinuous = true; - et.isIgnoreInterrupt = true; - asyncTaskHelper.scheduleBaseRunnable( - et::test - , s -> { - } - , initialDelayMillis - , delayMillis - ); - - Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); - - - //we should get a timeout - try { - asyncTaskHelper.cancelBaseActionRunnable( - AppcOam.RPC.stop, - AppcOamStates.Started, - 1, - TimeUnit.MILLISECONDS); - Assert.fail("Should have gotten TimeoutException"); - } catch (TimeoutException e) { - //just ignore as it is expected - } - - - //release the test thread - et.isContinuous = false; - - - //we should not get a timeout - asyncTaskHelper.cancelBaseActionRunnable( - AppcOam.RPC.stop, - AppcOamStates.Started, - 1000, - TimeUnit.MILLISECONDS); - - } - - - - /** - * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} - * Test cancel does not block when BaseRunnable is not scheduled - */ - @Test - public void test_BaseRunnableCancelCallback() throws Exception{ - - AtomicReference cancelCallback = new AtomicReference<>(null); - - final ExecuteTest et = new ExecuteTest(); - et.isContinuous = true; - Future future = asyncTaskHelper.scheduleBaseRunnable( - et::test - , cancelCallback::set - , initialDelayMillis - , delayMillis - ); - - Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); - Assert.assertTrue("It should be running", waitForNot(future::isDone, 1000)); - - - try { - asyncTaskHelper.cancelBaseActionRunnable( - AppcOam.RPC.stop, - AppcOamStates.Started, - 1, - TimeUnit.MILLISECONDS); - Assert.fail("Should have gotten TimeoutException"); - } catch (TimeoutException e) { - //just ignore as it is expected - } - - - Assert.assertEquals("Unexpected rpc in call back",AppcOam.RPC.stop,cancelCallback.get()); - } - - - - - - - - - /** - * @return true if the negation of the expected value is returned from the supplier within the specified - * amount of time - */ - private static boolean waitForNot(Supplier s,long timeoutMillis)throws Exception{ - return waitFor(()->!s.get(),timeoutMillis); - } - - - /** - * @return true if the expected value is returned from the supplier within the specified - * amount of time - */ - private static boolean waitFor(Supplier s,long timeoutMillis) throws Exception { - long timeout = TimeUnit.MILLISECONDS.toMillis(timeoutMillis); - long expiryTime = System.currentTimeMillis() + timeout; - long elapsedTime; - while(!s.get()){ - elapsedTime = expiryTime - System.currentTimeMillis(); - if(elapsedTime < 1) { - break; - } - Thread.sleep(10); - } - return s.get(); - } - - - /** - * This class is used control a thread executed in th {@link #test()} - */ - @SuppressWarnings("unused") - private static class ExecuteTest { - - - /** A fail safe to insure this TEst does not run indefinitely */ - private final long EXPIRY_TIME = System.currentTimeMillis() + 10000; - - - - /** A thread sets this value to true when it has completed the execution the of executes {@link #test()} */ - private volatile boolean isExecuted = false; - - /** - * A thread sets this value to true when it is actively executing {@link #test()} and back to false when - * it is not - */ - private volatile boolean isExecuting = false; - - /** - * While this value is true, a thread will not be allowed to return from {@link #test()} It will simulate a - * long execution. - */ - private volatile boolean isContinuous = false; - - /** - * When this value is set to true, an ongoing simulation of a long execution of {@link #test()} cannot be force - * to abort via a {@link Thread#interrupt()} - */ - private volatile boolean isIgnoreInterrupt = false; - - - - /** Use to send a signal to the thread executing {@link #notifyTestExcuted(long)} */ - private Semaphore inner = new Semaphore(0); - - /** Use to send a signal to the thread executing {@link #waitForTestExec(long)} */ - private Semaphore outer = new Semaphore(0); - - /** The {@link Future} of the Thread executing {@link #test()}*/ - private volatile Future future; - - /** - * When set the Thread executing {@link #test()} will cancel itself - * @param future - The {@link Future} of the Thread executing {@link #test()} - */ - private void cancelSelfOnNextExecution(Future future) { - this.future = future; - } - - - private boolean isExecuted() { - return isExecuted; - } - - private boolean isExecuting() { - return isExecuting; - } - - - private boolean isContinuous() { - return isContinuous; - } - - - private boolean isIgnoreInterrupt() { - return isIgnoreInterrupt; - } - - - - /** - * The thread executing this method if blocked from returning until the thread executing - * {@link #test()} invokes {@link #notifyTestExcuted(long)} or the specified time elapses - * @param timeoutMillis - the amount of time to wait for a execution iteration. - * @return true if the Thread is released because of an invocation of {@link #notifyTestExcuted(long)} - * @throws InterruptedException - If the Caller thread is interrupted. - */ - private boolean waitForTestExec(long timeoutMillis) throws InterruptedException { - inner.release(); - return outer.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); - } - - - /** - * Test simulator - * @return Always returns true. - */ - private Boolean test() { - isTestExpired(); - System.out.println("started"); - isExecuting = true; - try { - if (future != null) { - future.cancel(false); - } - if(!isContinuous){ - notifyTestExcuted(1); - } - - while(isContinuous){ - notifyTestExcuted(100); - isTestExpired(); - } - - } finally { - isExecuting = false; - isExecuted = true; - } - return true; - } - - - /** @throws RuntimeException if the test has bee running too long */ - private void isTestExpired(){ - if(System.currentTimeMillis() > EXPIRY_TIME){ - throw new RuntimeException("Something went wrong the test expired."); - } - } - - - /** - * The thread executing {@link #test()} if blocked from returning until another thread invokes - * {@link #waitForTestExec(long)} or the specified time elapses - * @param timeoutMillis - the amount of time to wait for a execution iteration. - * @return true if the Thread is released because of an invocation of {@link #waitForTestExec(long)} - */ - private boolean notifyTestExcuted(long timeoutMillis){ - try { - boolean acquire = inner.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); - if(acquire){ - outer.release(); - System.out.println("release"); - } - } catch (InterruptedException e) { - if(!isIgnoreInterrupt){ - return false; - } - } - return true; - } - } - - - static class Sub { - ExecuteTest et = new ExecuteTest(); - Future future = null; - } - -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java deleted file mode 100644 index 433e87517..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.apache.commons.lang.ArrayUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.membermodification.MemberMatcher; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; - -@SuppressWarnings("ResultOfMethodCallIgnored") -@RunWith(PowerMockRunner.class) -@PrepareForTest({BundleHelper.class, FrameworkUtil.class}) -public class BundleHelperTest { - private BundleHelper bundleHelper; - private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); - - @Before - public void setUp() throws Exception { - bundleHelper = spy(new BundleHelper(null, null, null)); - - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - Whitebox.setInternalState(bundleHelper, "logger", mockLogger); - } - - @Test - public void testBundleOperations() throws Exception { - // spy mocked bundle for calls to method statr or stop. - // Note: the time of method calls are accumulated in this test method. - Bundle mockBundle = spy(Mockito.mock(Bundle.class)); - Map mapFromGetAppcLcmBundles = new HashMap<>(); - mapFromGetAppcLcmBundles.put("BundleString", mockBundle); - - PowerMockito.doReturn(mapFromGetAppcLcmBundles).when(bundleHelper, MemberMatcher.method( - BundleHelper.class, "getAppcLcmBundles")).withNoArguments(); - - StateHelper mockStateHelper = mock(StateHelper.class); - Whitebox.setInternalState(bundleHelper, "stateHelper", mockStateHelper); - - AppcOamStates appcOamStates = AppcOamStates.Stopped; - Mockito.doReturn(appcOamStates).when(mockStateHelper).getState(); - - // test start - Mockito.doReturn(true).when(mockStateHelper).isSameState(appcOamStates); - boolean result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null); - Assert.assertTrue("Should be completed", result); - Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); - - // test start aborted - Mockito.doReturn(false).when(mockStateHelper).isSameState(appcOamStates); - result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null); - Assert.assertFalse("Should be abort", result); - Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); - - // test stop - result = bundleHelper.bundleOperations(AppcOam.RPC.stop, new HashMap<>(), mockTaskHelper,null); - Assert.assertTrue("Should be completed", result); - Mockito.verify(mockTaskHelper, times(2)).submitBaseSubCallable(any()); - } - - @Test(expected = APPCException.class) - public void testBundleOperationsRpcException() throws Exception { - bundleHelper.bundleOperations(AppcOam.RPC.maintenance_mode, new HashMap<>(), mockTaskHelper,null); - } - - @Test - public void testGetBundleList() throws Exception { - mockStatic(FrameworkUtil.class); - Bundle myBundle = mock(Bundle.class); - PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); - - // test bundle context is null - Mockito.when(myBundle.getBundleContext()).thenReturn(null); - Assert.assertTrue("Should return null", bundleHelper.getBundleList() == null); - - BundleContext myBundleContext = mock(BundleContext.class); - Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext); - - // test bundle list is empty - Bundle[] bundleArray = {}; - Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); - Bundle[] results = bundleHelper.getBundleList(); - Assert.assertTrue("Should not be null", results != null); - Assert.assertTrue("Should not have any element", results.length == 0); - - // test bundle list has at one bundle - bundleArray = new Bundle[] { myBundle }; - Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); - results = bundleHelper.getBundleList(); - Assert.assertTrue("Should not be null", results != null); - Assert.assertTrue("Should have one element", results.length == 1); - Assert.assertEquals("Should be the mock bundle", myBundle, results[0]); - } - - @Test - public void testReadPropsFromPropListName() throws Exception { - // mock configuarion helper - ConfigurationHelper configurationHelper = new ConfigurationHelper(null); - EELFLogger fakeLogger = mock(EELFLogger.class); - Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); - Configuration fakeConf = mock(Configuration.class); - Whitebox.setInternalState(configurationHelper, "configuration", fakeConf); - - Whitebox.setInternalState(bundleHelper, "configurationHelper", configurationHelper); - - String propKey = "testing"; - // Property does not exist - Mockito.doReturn(null).when(fakeConf).getProperty(propKey); - String[] propResult = bundleHelper.readPropsFromPropListName(propKey); - Assert.assertArrayEquals("PropertyResult should be empty string array", - ArrayUtils.EMPTY_STRING_ARRAY, propResult); - // Property has one entry - String propValue1 = "1234"; - String propValue2 = "5678"; - Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); - Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); - propResult = bundleHelper.readPropsFromPropListName(propKey); - Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); - Assert.assertEquals("PropertyResult should martch propertyValue", propValue2, propResult[0]); - // Property has two entries - propValue1 = "1234\n,4321"; - String propValue3 = "8765"; - Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); - Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); - Mockito.doReturn(propValue3).when(fakeConf).getProperty("4321"); - propResult = bundleHelper.readPropsFromPropListName(propKey); - Assert.assertTrue("PropertyResult should have two elements", propResult.length == 2); - List propResultList = Arrays.asList(propResult); - Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue2)); - Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue3)); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java deleted file mode 100644 index 348517b72..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.configuration.Configuration; -import org.powermock.reflect.Whitebox; - -import static org.mockito.Mockito.mock; - -public class ConfigurationHelperTest { - private ConfigurationHelper configurationHelper; - - private Configuration mockConf; - private Configuration origConf; - - @Before - public void setUp() throws Exception { - mockConf = mock(Configuration.class); - - configurationHelper = new ConfigurationHelper(null); - - // to avoid operation on logger fail, mock up the logger - EELFLogger fakeLogger = mock(EELFLogger.class); - Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); - } - - private void setMockConf() { - origConf = Whitebox.getInternalState(configurationHelper, "configuration"); - Whitebox.setInternalState(configurationHelper, "configuration", mockConf); - } - - private void resetOrigConfig() { - Whitebox.setInternalState(configurationHelper, "configuration", origConf); - origConf = null; - } - - @Test - public void getAppcName() throws Exception { - // test with existing properties file - Assert.assertEquals("Should return value(APPC).", "APPC", configurationHelper.getAppcName()); - - // test with mockup - setMockConf(); - - String propValue = "testing"; - Mockito.doReturn(propValue).when(mockConf).getProperty(ConfigurationHelper.PROP_KEY_APPC_NAME); - Assert.assertEquals(String.format("Should return value(%s).", propValue), propValue, - configurationHelper.getAppcName()); - - resetOrigConfig(); - } - - @Test - public void isMetricEnabled() throws Exception { - // test with mockup - setMockConf(); - - Mockito.doReturn(false).when(mockConf).getBooleanProperty( - ConfigurationHelper.PROP_KEY_METRIC_STATE, false); - Assert.assertFalse("Should return false", configurationHelper.isMetricEnabled()); - - Mockito.doReturn(true).when(mockConf).getBooleanProperty( - ConfigurationHelper.PROP_KEY_METRIC_STATE, false); - Assert.assertTrue("Should return true", configurationHelper.isMetricEnabled()); - } - - @Test - public void testReadPropertyNotStop() throws Exception { - String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToNotStop"); - Assert.assertTrue(str.length > 0); - Assert.assertTrue(str[0].equals(".*appc.oam.*")); - } - - @Test - public void testReadPropertyStop() throws Exception { - String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToStop"); - Assert.assertTrue(str.length > 0); - Assert.assertTrue(str[0].equals(".*appc.*")); - } - - @Test - public void testReadPropertyWithMockup() throws Exception { - setMockConf(); - - String propKey = "testing"; - // Property does not exist - Mockito.doReturn(null).when(mockConf).getProperty(propKey); - String[] propResult = configurationHelper.readProperty(propKey); - Assert.assertArrayEquals("PropertyResult should be empty string array", - ArrayUtils.EMPTY_STRING_ARRAY, propResult); - // Property has one entry - String propValue = "1234"; - Mockito.doReturn(propValue).when(mockConf).getProperty(propKey); - propResult = configurationHelper.readProperty(propKey); - Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); - Assert.assertEquals("PropertyResult should martch propertyValue", propValue, propResult[0]); - - resetOrigConfig(); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java deleted file mode 100644 index 77edd1701..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.common.header.Flags; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.InvalidInputException; -import org.onap.appc.exceptions.InvalidStateException; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.oam.AppcOam; -import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({FrameworkUtil.class}) -public class OperationHelperTest { - private OperationHelper operationHelper; - private LifecycleManager lifecycleManager = mock(LifecycleManager.class); - private CommonHeader mockCommonHeader = mock(CommonHeader.class); - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - operationHelper = new OperationHelper(); - Whitebox.setInternalState(operationHelper, "lifecycleMgr", lifecycleManager); - } - - @Test - public void testIsInputValidWithMissingInput() throws Exception { - expectedException.expect(InvalidInputException.class); - expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); - - operationHelper.isInputValid(null); - expectedException = ExpectedException.none(); - } - - @Test - public void testIsInputValidWithMissingCommonHeader() throws Exception { - StartInput mockInput = mock(StartInput.class); - expectedException.expect(InvalidInputException.class); - expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); - - operationHelper.isInputValid(mockInput); - expectedException = ExpectedException.none(); - } - - @Test - public void testIsInputValidWithMissingOid() throws Exception { - StartInput mockInput = mock(StartInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - Mockito.doReturn(null).when(mockCommonHeader).getOriginatorId(); - expectedException.expect(InvalidInputException.class); - expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); - - operationHelper.isInputValid(mockInput); - expectedException = ExpectedException.none(); - } - - @Test - public void testIsInputValidWithMissingRid() throws Exception { - StartInput mockInput = mock(StartInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); - Mockito.doReturn(null).when(mockCommonHeader).getRequestId(); - expectedException.expect(InvalidInputException.class); - expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); - - operationHelper.isInputValid(mockInput); - expectedException = ExpectedException.none(); - } - - @Test - public void testIsInputValidWithMmodeFlags() throws Exception { - MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); - Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); - Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); - expectedException.expect(InvalidInputException.class); - expectedException.expectMessage(operationHelper.NOT_SUPPORT_FLAG); - - operationHelper.isInputValid(mockInput); - expectedException = ExpectedException.none(); - } - - @Test - public void testIsInputValidPass() throws Exception { - StartInput mockInput = mock(StartInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); - Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); - Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); - - //with Flags - Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); - operationHelper.isInputValid(mockInput); - - //without Flags - Mockito.doReturn(null).when(mockCommonHeader).getFlags(); - operationHelper.isInputValid(mockInput); - - // MaintenanceMode without Flags - MaintenanceModeInput mockInput1 = mock(MaintenanceModeInput.class); - Mockito.doReturn(mockCommonHeader).when(mockInput1).getCommonHeader(); - operationHelper.isInputValid(mockInput1); - } - - @Test - public void testGetCommonHeader() throws Exception { - CommonHeader commonHeader = mock(CommonHeader.class); - // for StartInput - StartInput startInput = mock(StartInput.class); - Mockito.doReturn(commonHeader).when(startInput).getCommonHeader(); - Assert.assertEquals("Should return startInput commonHeader", commonHeader, - operationHelper.getCommonHeader(startInput)); - - // for StopInput - StopInput stopInput = mock(StopInput.class); - Mockito.doReturn(commonHeader).when(stopInput).getCommonHeader(); - Assert.assertEquals("Should return stopInput commonHeader", commonHeader, - operationHelper.getCommonHeader(stopInput)); - - // for MaintenanceModeInput - MaintenanceModeInput mmInput = mock(MaintenanceModeInput.class); - Mockito.doReturn(commonHeader).when(mmInput).getCommonHeader(); - Assert.assertEquals("Should return MaintenanceModeInput commonHeader", commonHeader, - operationHelper.getCommonHeader(mmInput)); - - // unsupported type - Assert.assertTrue("should return null", - operationHelper.getCommonHeader(new Object()) == null); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetService() throws Exception { - Class operationHelperClass = OperationHelper.class; - String className = operationHelperClass.getName(); - String exceptionMsg = String.format(operationHelper.NO_SERVICE_REF_FORMAT, className); - - mockStatic(FrameworkUtil.class); - Bundle bundle = mock(Bundle.class); - PowerMockito.when(FrameworkUtil.getBundle(operationHelperClass)).thenReturn(bundle); - - // No bundle context - Mockito.when(bundle.getBundleContext()).thenReturn(null); - expectedException.expect(APPCException.class); - expectedException.expectMessage(exceptionMsg); - operationHelper.getService(operationHelperClass); - - // No service reference - BundleContext bundleContext = mock(BundleContext.class); - Mockito.when(bundle.getBundleContext()).thenReturn(bundleContext); - Mockito.when(bundleContext.getServiceReference(className)).thenReturn(null); - expectedException.expect(APPCException.class); - expectedException.expectMessage(exceptionMsg); - operationHelper.getService(operationHelperClass); - - // Success path - ServiceReference svcRef = mock(ServiceReference.class); - Mockito.when(bundleContext.getServiceReference(className)).thenReturn(svcRef); - expectedException = ExpectedException.none(); - Assert.assertTrue("should not be null", operationHelper.getService(operationHelperClass) != null); - } - - @Test - public void testGetNextState() throws Exception { - AppcOamMetaDataReader.AppcOperation operation = AppcOamMetaDataReader.AppcOperation.Start; - AppcOamStates currentState = AppcOamStates.Stopped; - String exceptionMsg = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, operation, "APPC", currentState); - - // got LifecycleException - Mockito.doThrow(LifecycleException.class).when(lifecycleManager) - .getNextState("APPC", operation.name(), currentState.name()); - expectedException.expect(InvalidStateException.class); - expectedException.expectMessage(exceptionMsg); - operationHelper.getNextState(operation, currentState); - - // got NoTransitionDefinedException - Mockito.doThrow(NoTransitionDefinedException.class).when(lifecycleManager) - .getNextState("APPC", operation.name(), currentState.name()); - expectedException.expect(InvalidStateException.class); - expectedException.expectMessage(exceptionMsg); - operationHelper.getNextState(operation, currentState); - - // Success path - expectedException = ExpectedException.none(); - Mockito.doReturn("starting").when(lifecycleManager) - .getNextState("APPC", operation.name(), currentState.name()); - Assert.assertEquals("Should return proper Starting state", AppcOamStates.Starting, - operationHelper.getNextState(operation, currentState)); - } -} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java deleted file mode 100644 index 9a3050e84..000000000 --- a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.oam.util; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState; -import org.onap.appc.statemachine.impl.readers.AppcOamStates; -import org.osgi.framework.Bundle; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({StateHelper.class}) -public class StateHelperTest { - private StateHelper stateHelper; - - @Before - public void setUp() throws Exception { - stateHelper = PowerMockito.spy(new StateHelper(null, null)); - - // to avoid operation on logger fail, mock up the logger - EELFLogger mockLogger = mock(EELFLogger.class); - Whitebox.setInternalState(stateHelper, "logger", mockLogger); - } - - @Test - public void testSetState() throws Exception { - AppcOamStates appcOamStates = AppcOamStates.Started; - stateHelper.setState(appcOamStates); - Assert.assertEquals("Should have the new value", appcOamStates, - Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); - // reest to default value - stateHelper.setState(AppcOamStates.Unknown); - } - - @Test - public void testGetState() throws Exception { - AppcOamStates appcOamStates = stateHelper.getState(); - Assert.assertEquals("Should have the class value", appcOamStates, - Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); - } - - @Test - public void testIsSameState() throws Exception { - AppcOamStates classValue = Whitebox.getInternalState(stateHelper, "appcOamCurrentState"); - for (AppcOamStates appcOamStates : AppcOamStates.values()) { - boolean isSame = stateHelper.isSameState(appcOamStates); - if (appcOamStates == classValue) { - Assert.assertTrue("Should be the same", isSame); - } else { - Assert.assertFalse("Should not be the same", isSame); - } - } - } - - @Test - public void testGetCurrentOamState() throws Exception { - AppcOamStates mockResult = AppcOamStates.Started; - // mock getBundlesState, as we are testin it separately - PowerMockito.doReturn(mockResult).when(stateHelper, "getBundlesState"); - - Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); - Assert.assertEquals("Should call deriveStatte and return mockeResult", - mockResult, stateHelper.getCurrentOamState()); - Mockito.verify(stateHelper, times(1)).getBundlesState(); - - - Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); - Assert.assertEquals("Should call deriveStatte and return mockeResult", - mockResult, stateHelper.getCurrentOamState()); - Mockito.verify(stateHelper, times(2)).getBundlesState(); - - Whitebox.setInternalState(stateHelper, "appcOamCurrentState", mockResult); - Assert.assertEquals("Should just return mockeResult", mockResult, stateHelper.getCurrentOamState()); - Mockito.verify(stateHelper, times(2)).getBundlesState(); - } - - @Test - public void testGetCurrentOamYangState() throws Exception { - Map stateMap = new HashMap() { - { - put(AppcOamStates.EnteringMaintenanceMode, AppcState.EnteringMaintenanceMode); - put(AppcOamStates.MaintenanceMode, AppcState.MaintenanceMode); - put(AppcOamStates.Instantiated, AppcState.Instantiated); - put(AppcOamStates.NotInstantiated, AppcState.NotInstantiated); - put(AppcOamStates.Restarting, AppcState.Restarting); - put(AppcOamStates.Started, AppcState.Started); - put(AppcOamStates.Starting, AppcState.Starting); - put(AppcOamStates.Stopped, AppcState.Stopped); - put(AppcOamStates.Stopping, AppcState.Stopping); - put(AppcOamStates.Error, AppcState.Error); - put(AppcOamStates.Unknown, AppcState.Unknown); - } - }; - for (Map.Entry aEntry : stateMap.entrySet()) { - AppcOamStates aState = aEntry.getKey(); - AppcState appcState = aEntry.getValue(); - - PowerMockito.doReturn(aState).when(stateHelper, "getCurrentOamState"); - - AppcState resultState = stateHelper.getCurrentOamYangState(); - Assert.assertEquals( - String.format("%s state, returned(%s),should return(%s) state", aState, resultState, appcState), - appcState, resultState); - - } - } - - @Test - public void testGetBundlesState() throws Exception { - BundleHelper mockBundlerHelper = mock(BundleHelper.class); - PowerMockito.whenNew(BundleHelper.class).withAnyArguments().thenReturn(mockBundlerHelper); - - // test null bundle map - Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(null); - Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); - - // tet empty bundle map - Map bundleMap = new HashMap<>(); - Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); - Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); - - Bundle mockBundle1 = mock(Bundle.class); - Bundle mockBundle2 = mock(Bundle.class); - bundleMap.put("1", mockBundle1); - bundleMap.put("2", mockBundle2); - Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); - - // test bundles have differnt states - Mockito.doReturn(Bundle.RESOLVED).when(mockBundle1).getState(); - Mockito.doReturn(Bundle.ACTIVE).when(mockBundle2).getState(); - Assert.assertEquals("Should return lower state", AppcOamStates.Stopped, stateHelper.getBundlesState()); - - // test bundles have the same state - Mockito.doReturn(Bundle.ACTIVE).when(mockBundle1).getState(); - Assert.assertEquals("Should return the state", AppcOamStates.Started, stateHelper.getBundlesState()); - } -} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientActivator.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientActivator.java new file mode 100644 index 000000000..ab66af512 --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientActivator.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.appc.aai.client.node.AAIResourceNode; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class AppcAaiClientActivator implements BundleActivator { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(AppcAaiClientActivator.class); + private List registrations = new LinkedList(); + + @Override + public void start(BundleContext ctx) throws Exception { + + + + AAIResourceNode aaiResourceNode = new AAIResourceNode(); + log.info("Registering service-- " + aaiResourceNode.getClass().getName()); + registrations.add(ctx.registerService(aaiResourceNode.getClass().getName(), aaiResourceNode, null)); + + + } + + @Override + public void stop(BundleContext arg0) throws Exception { + for (ServiceRegistration registration : registrations) { + registration.unregister(); + registration = null; + } + } +} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientConstant.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientConstant.java new file mode 100644 index 000000000..772488876 --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/AppcAaiClientConstant.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client; + +public class AppcAaiClientConstant { + + + + + public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + + + public static final String INPUT_PARAM_VM_INSTANCE = "vmInstance"; + + + public static final Object INPUT_PARAM_VNF_ID = "vnfId"; + public static final Object INPUT_PARAM_VM_NAME = "vmName"; + + public static final String INPUT_PARAM_FILE_ID = "fileId"; + + + + +} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/aai/AaiService.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/aai/AaiService.java new file mode 100644 index 000000000..f03e7f319 --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/aai/AaiService.java @@ -0,0 +1,775 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client.aai; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; + +import org.onap.appc.aai.client.AppcAaiClientConstant; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +public class AaiService { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(AaiService.class); + private AAIClient aaiClient; + + + public AaiService(AAIClient aaiClient) { + this.aaiClient = aaiClient; + } + + public AaiService() { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(AAIService.class); + aaiClient = (AAIClient) bctx.getService(sref); + } + + public void getGenericVnfInfo(Map params, SvcLogicContext ctx) throws Exception { + + + String vnfId = params.get("vnfId"); + if(StringUtils.isBlank(vnfId)){ + throw new Exception("VnfId is missing"); + } + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + + //String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "' AND relationship-key = 'vserver.vserver-id'"; + + String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "'"; + + String resourceType = "generic-vnf"; + String queryPrefix = "vnfInfo"; + SvcLogicContext vnfCtx = readResource(resourceKey,queryPrefix,resourceType); + + + + + ctx.setAttribute(prefix + "vnf.vnf-name", vnfCtx.getAttribute("vnfInfo.vnf-name")); + ctx.setAttribute(prefix + "vnf.vnf-type", vnfCtx.getAttribute("vnfInfo.vnf-type")); + ctx.setAttribute(prefix + "vnf.prov-status", vnfCtx.getAttribute("vnfInfo.prov-status")); + ctx.setAttribute(prefix + "vnf.orchestration-status", vnfCtx.getAttribute("vnfInfo.orchestration-status")); + + + + int vmCount = 0; + + + String relLen = vnfCtx.getAttribute("vnfInfo.relationship-list.relationship_length"); + int relationshipLength = 0; + if ( relLen != null ) + relationshipLength = Integer.parseInt(relLen); + + log.info("RELLEN " + relationshipLength); + for ( int i=0; i < relationshipLength; i++ ) { + + String vserverId = getRelationshipValue(i, vnfCtx, "vserver", "vserver.vserver-id", "vnfInfo"); + String tenantId = getRelationshipValue(i, vnfCtx, "vserver", "tenant.tenant-id", "vnfInfo"); + String cloudOwner = getRelationshipValue(i, vnfCtx, "vserver", "cloud-region.cloud-owner", "vnfInfo"); + String cloudRegionId = getRelationshipValue(i, vnfCtx, "vserver", "cloud-region.cloud-region-id", "vnfInfo"); + + if ( vserverId != null ) { + + log.info("VSERVER KEYS " + vserverId + " " + tenantId + " " + cloudOwner + " " + cloudRegionId); + String vnfPrefix = prefix + "vm[" + vmCount + "]."; + + ctx.setAttribute(vnfPrefix + "vserver-id", vserverId); + ctx.setAttribute(vnfPrefix + "tenant-id", tenantId); + ctx.setAttribute(vnfPrefix + "cloud-owner", cloudOwner); + ctx.setAttribute(vnfPrefix + "cloud-region-id", cloudRegionId); + + vmCount++; + } + } + + + + ctx.setAttribute(prefix + "vm-count", String.valueOf(vmCount)); + + log.info("VMCOUNT FROM VNF INFO " + ctx.getAttribute(prefix + "vm-count")); + + + + + } + + + + public void getVMInfo(Map params,SvcLogicContext ctx ) throws Exception { + log.info("Received getVmInfo call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + int vnfcCount = 0; + ctx.setAttribute(prefix + "vm.vnfc-count", String.valueOf(vnfcCount)); // Incase no vnfcs are found + + String vserverId = params.get("vserverId"); + if(StringUtils.isBlank(vserverId)){ + throw new Exception("VServerId is missing"); + } + + String tenantId = params.get("tenantId"); + if(StringUtils.isBlank(tenantId)){ + throw new Exception("TenantId is missing"); + } + + String cloudOwner = params.get("cloudOwner"); + if(StringUtils.isBlank(cloudOwner)){ + throw new Exception("Cloud Owner is missing"); + } + + String cloudRegionId = params.get("cloudRegionId"); + if(StringUtils.isBlank(cloudRegionId)){ + throw new Exception("Cloud region Id is missing"); + } + + + + String resourceKey = "vserver.vserver-id = '" +vserverId + "' AND tenant.tenant-id = '" + tenantId + + "' AND cloud-region.cloud-owner = '" +cloudOwner + + "' AND cloud-region.cloud-region-id = '" +cloudRegionId + "'"; + + + String queryPrefix = "vmInfo"; + + String resourceType = "vserver"; + SvcLogicContext vmCtx = readResource(resourceKey,queryPrefix,resourceType); + + + + + + ctx.setAttribute(prefix+ "vm.prov-status", vmCtx.getAttribute("vmInfo.prov-status")); + + ctx.setAttribute(prefix+ "vm.vserver-name", vmCtx.getAttribute("vmInfo.vserver-name")); + + + + String relLen = vmCtx.getAttribute("vmInfo.relationship-list.relationship_length"); + + + int relationshipLength = 0; + if ( relLen != null ) + relationshipLength = Integer.parseInt(relLen); + + log.info("RELLEN" + relationshipLength); + for ( int i=0; i < relationshipLength; i++ ) { + + String vfModuleId = getRelationshipValue(i, vmCtx, "vf-module", "vf-module.vf-module-id", "vmInfo"); + + if ( vfModuleId != null ) + ctx.setAttribute(prefix + "vm.vf-module-id", vfModuleId); + + + String vnfcName = getRelationshipValue(i, vmCtx, "vnfc", "vnfc.vnfc-name", "vmInfo"); + + if ( vnfcName != null ) { + + ctx.setAttribute(prefix + "vm.vnfc[" + vnfcCount + "].vnfc-name", vnfcName); + vnfcCount++; + } + + + + + } //relationshipLength + ctx.setAttribute(prefix + "vm.vnfc-count", String.valueOf(vnfcCount)); + + log.info("VSERVERNAME " + ctx.getAttribute(prefix+ "vm.vserver-name") + " HAS NUM VNFCS = " + ctx.getAttribute(prefix+ "vm.vnfc-count")); + + } + + + + private String getRelationshipValue(int i, SvcLogicContext ctx, String relatedTo, String relationshipKey, String prefix) throws Exception { + + + if ( relatedTo.equals(ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].related-to")) ) { + + + log.info("RELATEDTO " + relatedTo); + int relationshipDataLength = 0; + String relDataLen = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data_length"); + + if ( relDataLen != null ) + relationshipDataLength = Integer.parseInt(relDataLen); + + + + for ( int j =0 ; j < relationshipDataLength ; j++) { + + String key = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-key"); + + String value = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-value"); + + log.info("GENERIC KEY " + key); + log.info("GENERIC VALUE " + value); + + if (relationshipKey.equals(key)) { + return value; + + } + + } // relationshipDataLength + + + } // if related-To + + + return null; + + + } + + + public void getVnfcInfo(Map params,SvcLogicContext ctx ) throws Exception { + log.info("Received getVnfc call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + String vnfcName = params.get("vnfcName"); + if(StringUtils.isBlank(vnfcName)){ + throw new Exception("Vnfc Name is missing"); + } + + String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; + + String queryPrefix = "vnfcInfo"; + String resourceType = "vnfc"; + SvcLogicContext vnfcCtx = readResource(resourceKey,queryPrefix,resourceType); + + // Changes for US 315820 for 1710 vnfc-type renamed to nfc-function,vnfc-function-code renamed to nfc-naming-code + + /*ctx.setAttribute(prefix+ "vnfc.vnfc-type", vnfcCtx.getAttribute("vnfcInfo.vnfc-type")); + ctx.setAttribute(prefix+ "vnfc.vnfc-function-code", vnfcCtx.getAttribute("vnfcInfo.vnfc-function-code")); + ctx.setAttribute(prefix+ "vnfc.group-notation", vnfcCtx.getAttribute("vnfcInfo.group-notation"));*/ + + ctx.setAttribute(prefix+ "vnfc.vnfc-type", vnfcCtx.getAttribute("vnfcInfo.nfc-function")); + ctx.setAttribute(prefix+ "vnfc.vnfc-function-code", vnfcCtx.getAttribute("vnfcInfo.nfc-naming-code")); + ctx.setAttribute(prefix+ "vnfc.group-notation", vnfcCtx.getAttribute("vnfcInfo.group-notation")); + + + } + + public void insertVnfcs(Map params,SvcLogicContext ctx, int vnfcRefLen, int vmCount) throws Exception { + log.info("Received insertVnfcs call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + + + int vnfcRefIndx =-1; + for ( int i = 0; i < vmCount ; i++ ) { + String aaiRefKey = prefix + "vm[" + i + "]."; + + log.info("VNFCNAME IN INSERTVNFCS " + ctx.getAttribute(aaiRefKey + "vnfc-name")); + String numVnfcsStr = ctx.getAttribute(aaiRefKey + "vnfc-count"); + + + //if ( numVnfcsStr != null || Integer.parseInt(numVnfcsStr) >= 1 ) + + + if ( ctx.getAttribute(aaiRefKey + "vnfc-name") != null ) + continue; + else + vnfcRefIndx++; + + + // Get Vnfc_reference data + String vnfcRefKey = "vnfcReference[" + vnfcRefIndx + "]."; + + log.info("VNFCREFKEY " + vnfcRefKey); + log.info("AAIREFKEY " + aaiRefKey); + + String vmInstance = ctx.getAttribute(vnfcRefKey+ "VM-INSTANCE"); + String vnfcInstance = ctx.getAttribute(vnfcRefKey+ "VNFC-INSTANCE"); + + String groupNotationType = ctx.getAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE"); + String groupNotationValue = ctx.getAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE"); + + String vnfcType = ctx.getAttribute(vnfcRefKey+ "VNFC-TYPE"); + + String vnfcFuncCode = ctx.getAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE"); + + String populateIpAddressV4OamVip = ctx.getAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP"); + + + // Get vnfc Data to be added + String vserverName = ctx.getAttribute(aaiRefKey + "vserver-name"); + String vnfcName = vserverName + vnfcFuncCode + "001"; + + String groupNotation = getGroupNotation(groupNotationType, groupNotationValue, vnfcName, vserverName,prefix, ctx, vnfcType); + + + String ipAddressV4OamVip = null; + if ( "Y".equals(populateIpAddressV4OamVip)) + ipAddressV4OamVip = ctx.getAttribute("vnf-host-ip-address"); // from input + + + Map vnfcParams = populateVnfcParams(ctx, aaiRefKey, ipAddressV4OamVip, groupNotation, vnfcType, vnfcFuncCode); + + + addVnfc( vnfcName, vnfcParams, prefix); + + // Add VNFC Info to context for current added VNFC + ctx.setAttribute(aaiRefKey + "vnfc-name", vnfcName); + ctx.setAttribute(aaiRefKey + "vnfc-type", vnfcType); + ctx.setAttribute(aaiRefKey + "vnfc-function-code", vnfcFuncCode); + ctx.setAttribute(aaiRefKey + "group-notation", groupNotation); + + } + + + } + + + + public Map populateVnfcParams(SvcLogicContext ctx, String aaiRefKey, + String ipAddressV4OamVip, String groupNotation, String vnfcType, String vnfcFuncCode) throws Exception { + + + Map vnfcParams = new HashMap(); + + // Changes for US 315820 for 1710 vnfc-type renamed to nfc-function,vnfc-function-code renamed to nfc-naming-code + + /* + vnfcParams.put("vnfc-function-code", vnfcFuncCode); + vnfcParams.put("vnfc-type", vnfcType); + */ + vnfcParams.put("nfc-naming-code", vnfcFuncCode); + vnfcParams.put("nfc-function", vnfcType); + + // + + vnfcParams.put("ipaddress-v4-oam-vip", ipAddressV4OamVip); + + vnfcParams.put("prov-status", "NVTPROV"); + vnfcParams.put("orchestration-status", "CONFIGURED"); + vnfcParams.put("in-maint", "false"); + vnfcParams.put("is-closed-loop", "false"); + vnfcParams.put("group-notation",groupNotation); + + + vnfcParams.put("relationship-list.relationship[0].related-to","vserver"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-key","vserver.vserver-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-value",ctx.getAttribute(aaiRefKey + "vserver-id")); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-key","tenant.tenant-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-value",ctx.getAttribute(aaiRefKey + "tenant-id")); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-key","cloud-region.cloud-owner"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-value",ctx.getAttribute(aaiRefKey + "cloud-owner")); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-key","cloud-region.cloud-region-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-value",ctx.getAttribute(aaiRefKey + "cloud-region-id")); + + + + vnfcParams.put("relationship-list.relationship[1].related-to","generic-vnf"); + vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-key","generic-vnf.vnf-id"); + vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-value",ctx.getAttribute("vnf-id")); + + + vnfcParams.put("relationship-list.relationship[2].related-to","vf-module"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-key","generic-vnf.vnf-id"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-value",ctx.getAttribute("vnf-id")); + + + vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-key","vf-module.vf-module-id"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-value",ctx.getAttribute(aaiRefKey + "vf-module-id")); + + + return vnfcParams; + } + + public void addVnfc(String vnfcName, Map params, String prefix) throws Exception { + + log.info("Received addVnfc call with vnfcName : " +vnfcName); + log.info("Received addVnfc call with params : " + params); + String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; + + log.info("Received addVnfc call with resourceKey : " + resourceKey); + + + SvcLogicContext vnfcCtx = new SvcLogicContext(); + SvcLogicResource.QueryStatus response = aaiClient.save("vnfc", true, false, resourceKey, params, prefix, vnfcCtx) ; + + if (SvcLogicResource.QueryStatus.SUCCESS.equals(response)) { + log.info("Added VNFC SUCCESSFULLY " + vnfcName); + + } + else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + throw new Exception("VNFC Add failed for for vnfc_name " + vnfcName); + + } + + + } + + public String getGroupNotation(String groupNotationType, String groupNotationValue, String vnfcName, + String vserverName, String prefix, SvcLogicContext ctx, String vnfcRefVnfcType) throws Exception { + + String grpNotation = null; + + if ( "fixed-value".equals(groupNotationType)) { + grpNotation = groupNotationValue; + + } + else if ( "first-vnfc-name".equals(groupNotationType) ) { + + /*If the group-notation-type value = ?first-vnfc-name?, + * then populate the group-notation value with the concatenation of + * [vnfc name associated with the first vnfc for the vnfc-type (e.g., *******)] + * and [the value in group-notation-value (e.g., pair)]. + * There may be several vnfc-types associated with the VM?s. + */ + /* Vnfc-type should be from refrence data */ + + /* vDBE has 2 VNFCs with same VNFC type . The pair name should be same for both . */ + /* When first VNFC is added details should be added to context so FirstVnfcName doesnt return null second time. */ + String tmpVnfcName = getFirstVnfcNameForVnfcType(ctx, prefix, vnfcRefVnfcType); + + log.info("RETURNED FIRSTVNFCNAME" + tmpVnfcName); + log.info("CURRENTVNFCNAME" + vnfcName); + if ( tmpVnfcName == null ) { + log.info("CURRENTVNFCNAME" + vnfcName); + // No Vnfcs currently exist. Use Current vnfcName + grpNotation = vnfcName + groupNotationValue; + } + else + grpNotation = tmpVnfcName + groupNotationValue; + + + } + else if ( "relative-value".equals(groupNotationType) ) { + + /*If the group-notation-type = ?relative-value?, then find the group-notation value + * from the prior vnfc (where prior means the vnfc with where the last three digits of the + * vm-name is one lower than the current one; note that this vnfc may have been previously configured.) + 1. If the group-notation-value = next, then add 1 to the group-notation value from the prior vnfc and use this value + 2. If the group-notation-value = same, then use the group-notation-value from the prior vnfc record*/ + + // next and same cant be defined for first VM. if next will not generate grpNotation if Prior is not a number + String tmpVserverName = null; + if ( vserverName != null ) { + + String vmNamePrefix = vserverName.substring(0,vserverName.length()-3); + + String lastThreeChars = vserverName.substring(vserverName.length() - 3); + + if ( NumberUtils.isDigits(lastThreeChars)) { + int vmNum = Integer.parseInt(lastThreeChars) - 1; + String formatted = String.format("%03d", vmNum); + + log.info("FORMATTED " + formatted); + + tmpVserverName = vmNamePrefix + formatted; + + + String priorGroupNotation = getGroupNotationForVServer(ctx, prefix, tmpVserverName); + + if ( "same".equals(groupNotationValue)) + grpNotation = priorGroupNotation; + else if ( "next".equals(groupNotationValue)) { + if ( priorGroupNotation != null && NumberUtils.isDigits(priorGroupNotation)) { + int nextGrpNotation = Integer.parseInt(priorGroupNotation) + 1; + grpNotation = String.valueOf(nextGrpNotation); + } + } + } + + } + + + + } + + + log.info("RETURNED GROUPNOTATION " + grpNotation); + return grpNotation; + } + + public String getGroupNotationForVServer(SvcLogicContext ctx, String prefix, String vserverName) throws Exception { + + + String vmCountStr = ctx.getAttribute(prefix+"vnf.vm-count"); + + if ( vmCountStr == null ) + return null; + + int vmCount = Integer.valueOf(vmCountStr); + for ( int i = 0; i < vmCount ; i++ ) { + + String tmpVserver = ctx.getAttribute(prefix+ "vm[" + i + "].vserver-name"); + + if (vserverName.equals(tmpVserver)) + return ctx.getAttribute(prefix+ "vm[" + i + "].group-notation"); + + } // vmCount + + return null; + + } + + + + + public String getFirstVnfcNameForVnfcType(SvcLogicContext ctx, String prefix, String vnfcRefVnfcType) throws Exception { + + + + /*if(StringUtils.isBlank(vnfcRefVnfcType)){ + throw new Exception("Vnfc Reference : VNFC Type is missing"); + }*/ + + + String vmCountStr = ctx.getAttribute(prefix+"vnf.vm-count"); + + if ( vmCountStr == null ) + return null; + + int vmCount = Integer.valueOf(vmCountStr); + for ( int i = 0; i < vmCount ; i++ ) { + + String tmpvnfcType = ctx.getAttribute(prefix+ "vm[" + i + "].vnfc-type"); + + if (vnfcRefVnfcType.equals(tmpvnfcType)) + return ctx.getAttribute(prefix+ "vm[" + i + "].vnfc-name"); + + } // vmCount + + + + return null; + + } + + public void updateVServerStatus(Map params,SvcLogicContext ctx, int vmCount) throws Exception { + log.info("Received updateVServerStatus call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + + Map vServerParams = new HashMap(); + + + // TODO - Should this just update prov-status or both? What about generic-vnf status? Will that be updated by Dispatcher? + + vServerParams.put("prov-status", "NVTPROV"); + //vServerParams.put("orchestration-status", "CONFIGURED"); + + + for ( int i = 0; i < vmCount ; i++ ) { + String aaiRefKey = prefix + "vm[" + i + "]."; + + log.info("VNFCNAME IN UpdateVServer " + ctx.getAttribute(aaiRefKey + "vnfc-name")); + + if ( ctx.getAttribute(aaiRefKey + "vnfc-name") != null ) + continue; + + + + String resourceKey = "vserver.vserver-id = '" + ctx.getAttribute(aaiRefKey + "vserver-id") + "'" + + " AND tenant.tenant-id = '" + ctx.getAttribute(aaiRefKey + "tenant-id") + "'" + + " AND cloud-region.cloud-owner = '" + ctx.getAttribute(aaiRefKey + "cloud-owner") + "'" + + " AND cloud-region.cloud-region-id = '" + ctx.getAttribute(aaiRefKey + "cloud-region-id") + "'"; + + + updateResource( "vserver", resourceKey, vServerParams); + + } + + + } + + + + public void updateVnfStatus(Map params,SvcLogicContext ctx) throws Exception { + log.info("Received updateVnfStatus call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + + Map vnfParams = new HashMap(); + + + // TODO - Should this just update prov-status or both? What about generic-vnf status? Will that be updated by Dispatcher? + + vnfParams.put("prov-status", "NVTPROV"); + //vnfParams.put("orchestration-status", "CONFIGURED"); + + + String resourceKey = "generic-vnf.vnf-id = '" + ctx.getAttribute("vnf-id") + "'"; + + updateResource( "generic-vnf" , resourceKey, vnfParams); + + + + + } + + public void updateResource( String resource, String resourceKey, Map params) throws Exception { + + log.info("Received updateResource call with Key : " +resourceKey); + + + SvcLogicContext ctx = new SvcLogicContext(); + + + SvcLogicResource.QueryStatus response = aaiClient.update(resource, resourceKey , params, "tmp.update", ctx); + + + + if (SvcLogicResource.QueryStatus.SUCCESS.equals(response)) { + log.info("Updated " + resource + " SUCCESSFULLY for " + resourceKey); + + } + else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + throw new Exception(resource + " Update failed for " + resourceKey); + + } + } + + public SvcLogicContext readResource(String query, String prefix, String resourceType) throws Exception { + SvcLogicContext resourceContext = new SvcLogicContext(); + + SvcLogicResource.QueryStatus response = aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); + log.info("AAIResponse: " + response.toString()); + if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ + throw new Exception("Error Retrieving " + resourceType + " from A&AI"); + } + + return resourceContext; + + + + } + + //Added 1710 & Backward Compatibility + + public void checkAndUpdateVnfc(Map params,SvcLogicContext ctx, int vnfcRefLen, int vmCount) throws Exception { + log.info("Received checkAndUpdateVnfcStatus call with params : " + params); + + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + + for ( int i = 0; i < vmCount ; i++ ) { + String aaiRefKey = prefix + "vm[" + i + "]."; + + log.info("VNFCNAME IN INSERTVNFCS "+ aaiRefKey+"vnfc-name:" + ctx.getAttribute(aaiRefKey + "vnfc-name")); + + String numVnfcsStr = ctx.getAttribute(aaiRefKey + "vnfc-count"); + String vnfcNameAai = ctx.getAttribute(aaiRefKey + "vnfc-name"); + + if (StringUtils.isNotBlank(vnfcNameAai)) { + // Get Vnfc_reference data + for(int vnfcRefIndx=0;vnfcRefIndx < vnfcRefLen;vnfcRefIndx++ ) { + + String vnfcRefKey = "vnfcReference[" + vnfcRefIndx + "]."; + + log.info("VNFCREFKEY " + vnfcRefKey); + log.info("AAIREFKEY " + aaiRefKey); + + String vnfcFuncCode = ctx.getAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE"); + String vserverName = ctx.getAttribute(aaiRefKey + "vserver-name"); + String vnfcNameReference = vserverName + vnfcFuncCode + "001"; + + if(vnfcNameAai.equals(vnfcNameReference)) { + + updateVnfcStatus( vnfcNameAai, params, prefix); + } + + + } + } + + + + + + + } + + + } + + public void updateVnfcStatus(String vnfcName, Map params, String prefix) throws Exception { + + log.info("Received updateVnfcStatus call with vnfcName : " +vnfcName); + log.info("Received updateVnfcStatus call with params : " + params); + + String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; + log.info("Received updateVnfcStatus call with resourceKey : " + resourceKey); + + + Map vnfcParams = new HashMap(); + vnfcParams.put("prov-status", "NVTPROV"); + vnfcParams.put("orchestration-status", "CONFIGURED"); + + log.info("In updateVnfcStatus call with vnfcParams : " + vnfcParams); + + updateResource( "vnfc" , resourceKey, vnfcParams); + + log.info("End of updateVnfcStatus"); + + + } + + + + //Added for 1710 + + +} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/node/AAIResourceNode.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/node/AAIResourceNode.java new file mode 100644 index 000000000..250508358 --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/main/java/org/onap/appc/aai/client/node/AAIResourceNode.java @@ -0,0 +1,514 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client.node; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import org.onap.appc.aai.client.AppcAaiClientConstant; +import org.onap.appc.aai.client.aai.AaiService; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +//import com.fasterxml.jackson.databind.ObjectMapper; + + +public class AAIResourceNode implements SvcLogicJavaPlugin { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(AAIResourceNode.class); + + + public AaiService getAaiService() { + return new AaiService(); + } + /* Gets VNF Info and All VServers associated with Vnf */ + public void getVnfInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getVnfInfo call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + AaiService aai = getAaiService(); + + + + aai.getGenericVnfInfo(inParams,ctx); + + + + + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); + log.info("getVnfInfo Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getVnfInfo " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + + public void getAllVServersVnfcsInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getAllVServersVnfcsInfo call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + AaiService aai = getAaiService(); + + + + ArrayList> vservers = new ArrayList>(); + + int vmWithNoVnfcsCount = 0; + String vmCountStr = ctx.getAttribute(responsePrefix + "vm-count"); + + if ( vmCountStr == null ) + throw new Exception("Unable to get VServers for the VNF"); + + int vmCount = Integer.parseInt(vmCountStr); + for ( int i = 0; i < vmCount; i++ ) { + + SvcLogicContext vmServerCtx = new SvcLogicContext(); + + Map paramsVm = new HashMap(); + paramsVm.put("vserverId", ctx.getAttribute(responsePrefix + "vm[" + i + "].vserver-id")); + paramsVm.put("tenantId", ctx.getAttribute(responsePrefix +"vm[" + i + "].tenant-id")); + paramsVm.put("cloudOwner", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-owner")); + paramsVm.put("cloudRegionId", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-region-id")); + paramsVm.put(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX, inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX)); + + + + aai.getVMInfo(paramsVm, vmServerCtx); + + HashMap vserverMap = new HashMap(); + vserverMap.put("vserver-id", ctx.getAttribute(responsePrefix + "vm[" + i + "].vserver-id")); + vserverMap.put("tenant-id", ctx.getAttribute(responsePrefix +"vm[" + i + "].tenant-id")); + vserverMap.put("cloud-owner", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-owner")); + vserverMap.put("cloud-region-id", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-region-id")); + + // Parameters returned by getVMInfo + vserverMap.put("vserver-name", vmServerCtx.getAttribute(responsePrefix + "vm.vserver-name")); + vserverMap.put("vf-module-id", vmServerCtx.getAttribute(responsePrefix + "vm.vf-module-id")); + + + // as Per 17.07 requirements we are supporting only one VNFC per VM. + + String vnfcName = vmServerCtx.getAttribute(responsePrefix + "vm.vnfc[0].vnfc-name"); + vserverMap.put("vnfc-name", vnfcName); + + + String vnfcCount = vmServerCtx.getAttribute(responsePrefix + "vm.vnfc-count"); + if ( vnfcCount == null ) + vnfcCount = "0"; + + vserverMap.put("vnfc-count", vnfcCount); + + if ( vnfcName != null ) { + Map paramsVnfc = new HashMap(); + paramsVnfc.put("vnfcName", vnfcName); + + paramsVnfc.put(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX, inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX)); + + SvcLogicContext vnfcCtx = new SvcLogicContext(); + + aai.getVnfcInfo(paramsVnfc, vnfcCtx); + + vserverMap.put("vnfc-type", vnfcCtx.getAttribute(responsePrefix + "vnfc.vnfc-type")); + vserverMap.put("vnfc-function-code", vnfcCtx.getAttribute(responsePrefix + "vnfc.vnfc-function-code")); + vserverMap.put("group-notation", vnfcCtx.getAttribute(responsePrefix + "vnfc.group-notation")); + + + } + else + vmWithNoVnfcsCount++; + + + + vservers.add(vserverMap); + + } // vmCount + + + + + Collections.sort(vservers, new Comparator>() { + @Override + public int compare(Map o1, Map o2) { + return o1.get("vserver-name").compareTo(o2.get("vserver-name")); + } + }); + + log.info("SORTED VSERVERS " + vservers.toString()); + + populateContext(vservers, ctx, responsePrefix); + + log.info("VMCOUNT IN GETALLVSERVERS " + vmCount); + log.info("VMSWITHNOVNFCSCOUNT IN GETALLVSERVERS " + vmWithNoVnfcsCount); + ctx.setAttribute(responsePrefix+"vnf.vm-count", String.valueOf(vmCount)); + ctx.setAttribute(responsePrefix+"vnf.vm-with-no-vnfcs-count", String.valueOf(vmWithNoVnfcsCount)); + + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getAllVServersVnfcsInfo " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + + + public void populateContext(ArrayList> vservers, SvcLogicContext ctx, String prefix) { + + + log.info("Populating Final Context"); + int ctr = 0; + + for (Map entry : vservers) { + for (String key : entry.keySet()) { + String value = entry.get(key); + + ctx.setAttribute(prefix+ "vm[" + ctr + "]."+ key, value); + log.info("Populating Context Key = " + prefix+ "vm[" + ctr + "]."+ key + " Value = " + value); + + } + + + ctr++; + } + + String firstVServerName = null; + for ( int i =0; i < ctr; i++ ) { + String vnfcName = ctx.getAttribute(prefix + "vm[" + i + "].vnfc-name"); + log.info("VNFCNAME " + i + vnfcName); + if ( vnfcName == null && firstVServerName == null ) { + firstVServerName = ctx.getAttribute(prefix + "vm[" + i + "].vserver-name"); + ctx.setAttribute("vm-name" , firstVServerName); + log.info("Populating Context Key = " + "vm-name" + " Value = " + firstVServerName); + } + } + } + + + + public void addVnfcs(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received addVnfcs call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + int vnfcRefLen =0 ; + int vmCount = 0; + int vmWithNoVnfcCount = 0; + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + AaiService aai = getAaiService(); + + + + String vnfcRefLenStr = ctx.getAttribute("vnfcReference_length"); + + if ( vnfcRefLenStr == null) { + log.info("Vnfc Reference data is missing"); + throw new Exception("Vnfc Reference data is missing"); + + } + else + vnfcRefLen = Integer.parseInt(vnfcRefLenStr); + + String vmWithNoVnfcCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-with-no-vnfcs-count"); + + //Commented for backward compatibility + + /*if ( vmWithNoVnfcCountStr == null) { + throw new Exception("VNFCs to be added data from A&AI is missing"); + //log.info("VNFCs to be added data from A&AI is missing"); + } + else + vmWithNoVnfcCount = Integer.parseInt(vmWithNoVnfcCountStr); + + if ( vmWithNoVnfcCount!= vnfcRefLen ) + throw new Exception("Unable to Add Vnfcs to A&AI. Reference data mismatch."); + + String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); + + if ( vmCountStr == null) + throw new Exception("VM data from A&AI is missing"); + else + vmCount = Integer.parseInt(vmCountStr); + + + log.info("VMCOUNT " + vmCount); + log.info("VNFCREFLEN " + vnfcRefLen); + aai.insertVnfcs(inParams,ctx, vnfcRefLen, vmCount); + + */ + + + // Modified for 1710 + + if ( vmWithNoVnfcCountStr == null) { + log.info("Parameter VM without VNFCs(vmWithNoVnfcCountStr) from A&AI is Null"); + } + else + vmWithNoVnfcCount = Integer.parseInt(vmWithNoVnfcCountStr); + + log.info("No of VM without VNFCs(vmWithNoVnfcCount) from A&AI is " +vmWithNoVnfcCount); + + String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); + + if ( vmCountStr == null) + throw new Exception("VM data from A&AI is missing"); + else + vmCount = Integer.parseInt(vmCountStr); + + log.info("VMCOUNT " + vmCount); + log.info("VNFCREFLEN " + vnfcRefLen); + + if ( vmWithNoVnfcCount!= vnfcRefLen ) { + //throw new Exception("Unable to Add Vnfcs to A&AI. Reference data mismatch."); + log.info("vmWithNoVnfcCount and vnfcRefLen data from table are not same "); + aai.checkAndUpdateVnfc(inParams,ctx, vnfcRefLen, vmCount); + } + + else { + + aai.insertVnfcs(inParams,ctx, vnfcRefLen, vmCount); + } + + //// Modified 1710 + + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); + + log.info("addVnfcs Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in addVnfcs " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + + public void updateVnfAndVServerStatus(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received updateVnfAndVServerStatus call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + + int vmCount = 0; + + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + AaiService aai = getAaiService(); + + + + String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); + + if ( vmCountStr == null) + throw new Exception("VM data from A&AI is missing"); + else + vmCount = Integer.parseInt(vmCountStr); + + + log.info("VMCOUNT " + vmCount); + + + aai.updateVnfStatus(inParams, ctx); + aai.updateVServerStatus(inParams,ctx, vmCount); + + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); + + log.info("updateVnfAndVServerStatus Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in updateVnfAndVServerStatus " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + } + + /*public void getDummyValues(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getDummyValues call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String instarKeys = inParams.get("instarKeys"); + ObjectMapper mapper = new ObjectMapper(); + if ( instarKeys != null ) { + + List keyList = mapper.readValue(instarKeys, ArrayList.class); + + Map instarParams =new HashMap(); + if(keyList != null){ + //System.out.println(keyList.toString()); + + + for(int i=0;i"+keyList.get(i)); + + //ctx.setAttribute(keyList.get(i), "test" + i); + + instarParams.put( keyList.get(i), "test" + i); + } + + } + log.info("INSTARPARAMMAP " + instarParams); + String jsonString = mapper.writeValueAsString(instarParams); + log.info(jsonString); + ctx.setAttribute(responsePrefix + "configuration-parameters", jsonString); + + } + + log.info("getDummyValues Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getDummyValues " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + + } + + */ + /*public void getRequestKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + log.info("Received getRequestKeys call with params : " + inParams); + + String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + try { + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; + String instarKeys = inParams.get("instarKeys"); + + ObjectMapper mapper = new ObjectMapper(); + if ( instarKeys != null ) { + + List keyList = mapper.readValue(instarKeys, ArrayList.class); + + //Map instarParams =new HashMap(); + if(keyList != null){ + + + for(int i=0;i"+keyList.get(i)); + + + String instarParameter = ctx.getAttribute("INSTAR." + keyList.get(i)); + log.info("INSTARPARAMETER " + instarParameter); + Parameter param = parseParameterContent(instarParameter); + + log.info("PARAMETER KEY SIZE " + param.getRequestKeys().size()); + log.info("RULE TYPE " + param.getClassType()); + + for ( int j =0 ; j < param.getRequestKeys().size() ; j++ ) { + + log.info(" PARAM KEY NAME " + param.getRequestKeys().get(j).getKeyName()); + log.info(" PARAM KEY VALUE " + param.getRequestKeys().get(j).getKeyValue()); + } + + // instarParams.put( keyList.get(i), "test" + i); + } + + } + //log.info("INSTARPARAMMAP " + instarParams); + //String jsonString = mapper.writeValueAsString(instarParams); + //log.info(jsonString); + //ctx.setAttribute(responsePrefix + "configuration-parameters", jsonString); + + } + + log.info("getRequestKeys Successful "); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, + AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed in getRequestKeys " + e.getMessage()); + + throw new SvcLogicException(e.getMessage()); + } + + } + + + public Parameter parseParameterContent(String parameter) throws JsonParseException, JsonMappingException, IOException{ + Parameter parameterDefinition = null; + if(StringUtils.isNotBlank(parameter)){ + ObjectMapper mapper = new ObjectMapper(); + parameterDefinition = mapper.readValue(parameter, Parameter.class); + } + return parameterDefinition; + }*/ +} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientActivator.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientActivator.java deleted file mode 100644 index ab66af512..000000000 --- a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientActivator.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client; - -import java.util.LinkedList; -import java.util.List; - -import org.onap.appc.aai.client.node.AAIResourceNode; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class AppcAaiClientActivator implements BundleActivator { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(AppcAaiClientActivator.class); - private List registrations = new LinkedList(); - - @Override - public void start(BundleContext ctx) throws Exception { - - - - AAIResourceNode aaiResourceNode = new AAIResourceNode(); - log.info("Registering service-- " + aaiResourceNode.getClass().getName()); - registrations.add(ctx.registerService(aaiResourceNode.getClass().getName(), aaiResourceNode, null)); - - - } - - @Override - public void stop(BundleContext arg0) throws Exception { - for (ServiceRegistration registration : registrations) { - registration.unregister(); - registration = null; - } - } -} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientConstant.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientConstant.java deleted file mode 100644 index 772488876..000000000 --- a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/AppcAaiClientConstant.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client; - -public class AppcAaiClientConstant { - - - - - public static String INPUT_PARAM_RESPONSE_PREFIX = "responsePrefix"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - - - public static final String INPUT_PARAM_VM_INSTANCE = "vmInstance"; - - - public static final Object INPUT_PARAM_VNF_ID = "vnfId"; - public static final Object INPUT_PARAM_VM_NAME = "vmName"; - - public static final String INPUT_PARAM_FILE_ID = "fileId"; - - - - -} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/aai/AaiService.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/aai/AaiService.java deleted file mode 100644 index f03e7f319..000000000 --- a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/aai/AaiService.java +++ /dev/null @@ -1,775 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client.aai; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; - -import org.onap.appc.aai.client.AppcAaiClientConstant; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -public class AaiService { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(AaiService.class); - private AAIClient aaiClient; - - - public AaiService(AAIClient aaiClient) { - this.aaiClient = aaiClient; - } - - public AaiService() { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(AAIService.class); - aaiClient = (AAIClient) bctx.getService(sref); - } - - public void getGenericVnfInfo(Map params, SvcLogicContext ctx) throws Exception { - - - String vnfId = params.get("vnfId"); - if(StringUtils.isBlank(vnfId)){ - throw new Exception("VnfId is missing"); - } - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - - //String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "' AND relationship-key = 'vserver.vserver-id'"; - - String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "'"; - - String resourceType = "generic-vnf"; - String queryPrefix = "vnfInfo"; - SvcLogicContext vnfCtx = readResource(resourceKey,queryPrefix,resourceType); - - - - - ctx.setAttribute(prefix + "vnf.vnf-name", vnfCtx.getAttribute("vnfInfo.vnf-name")); - ctx.setAttribute(prefix + "vnf.vnf-type", vnfCtx.getAttribute("vnfInfo.vnf-type")); - ctx.setAttribute(prefix + "vnf.prov-status", vnfCtx.getAttribute("vnfInfo.prov-status")); - ctx.setAttribute(prefix + "vnf.orchestration-status", vnfCtx.getAttribute("vnfInfo.orchestration-status")); - - - - int vmCount = 0; - - - String relLen = vnfCtx.getAttribute("vnfInfo.relationship-list.relationship_length"); - int relationshipLength = 0; - if ( relLen != null ) - relationshipLength = Integer.parseInt(relLen); - - log.info("RELLEN " + relationshipLength); - for ( int i=0; i < relationshipLength; i++ ) { - - String vserverId = getRelationshipValue(i, vnfCtx, "vserver", "vserver.vserver-id", "vnfInfo"); - String tenantId = getRelationshipValue(i, vnfCtx, "vserver", "tenant.tenant-id", "vnfInfo"); - String cloudOwner = getRelationshipValue(i, vnfCtx, "vserver", "cloud-region.cloud-owner", "vnfInfo"); - String cloudRegionId = getRelationshipValue(i, vnfCtx, "vserver", "cloud-region.cloud-region-id", "vnfInfo"); - - if ( vserverId != null ) { - - log.info("VSERVER KEYS " + vserverId + " " + tenantId + " " + cloudOwner + " " + cloudRegionId); - String vnfPrefix = prefix + "vm[" + vmCount + "]."; - - ctx.setAttribute(vnfPrefix + "vserver-id", vserverId); - ctx.setAttribute(vnfPrefix + "tenant-id", tenantId); - ctx.setAttribute(vnfPrefix + "cloud-owner", cloudOwner); - ctx.setAttribute(vnfPrefix + "cloud-region-id", cloudRegionId); - - vmCount++; - } - } - - - - ctx.setAttribute(prefix + "vm-count", String.valueOf(vmCount)); - - log.info("VMCOUNT FROM VNF INFO " + ctx.getAttribute(prefix + "vm-count")); - - - - - } - - - - public void getVMInfo(Map params,SvcLogicContext ctx ) throws Exception { - log.info("Received getVmInfo call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - int vnfcCount = 0; - ctx.setAttribute(prefix + "vm.vnfc-count", String.valueOf(vnfcCount)); // Incase no vnfcs are found - - String vserverId = params.get("vserverId"); - if(StringUtils.isBlank(vserverId)){ - throw new Exception("VServerId is missing"); - } - - String tenantId = params.get("tenantId"); - if(StringUtils.isBlank(tenantId)){ - throw new Exception("TenantId is missing"); - } - - String cloudOwner = params.get("cloudOwner"); - if(StringUtils.isBlank(cloudOwner)){ - throw new Exception("Cloud Owner is missing"); - } - - String cloudRegionId = params.get("cloudRegionId"); - if(StringUtils.isBlank(cloudRegionId)){ - throw new Exception("Cloud region Id is missing"); - } - - - - String resourceKey = "vserver.vserver-id = '" +vserverId + "' AND tenant.tenant-id = '" + tenantId + - "' AND cloud-region.cloud-owner = '" +cloudOwner + - "' AND cloud-region.cloud-region-id = '" +cloudRegionId + "'"; - - - String queryPrefix = "vmInfo"; - - String resourceType = "vserver"; - SvcLogicContext vmCtx = readResource(resourceKey,queryPrefix,resourceType); - - - - - - ctx.setAttribute(prefix+ "vm.prov-status", vmCtx.getAttribute("vmInfo.prov-status")); - - ctx.setAttribute(prefix+ "vm.vserver-name", vmCtx.getAttribute("vmInfo.vserver-name")); - - - - String relLen = vmCtx.getAttribute("vmInfo.relationship-list.relationship_length"); - - - int relationshipLength = 0; - if ( relLen != null ) - relationshipLength = Integer.parseInt(relLen); - - log.info("RELLEN" + relationshipLength); - for ( int i=0; i < relationshipLength; i++ ) { - - String vfModuleId = getRelationshipValue(i, vmCtx, "vf-module", "vf-module.vf-module-id", "vmInfo"); - - if ( vfModuleId != null ) - ctx.setAttribute(prefix + "vm.vf-module-id", vfModuleId); - - - String vnfcName = getRelationshipValue(i, vmCtx, "vnfc", "vnfc.vnfc-name", "vmInfo"); - - if ( vnfcName != null ) { - - ctx.setAttribute(prefix + "vm.vnfc[" + vnfcCount + "].vnfc-name", vnfcName); - vnfcCount++; - } - - - - - } //relationshipLength - ctx.setAttribute(prefix + "vm.vnfc-count", String.valueOf(vnfcCount)); - - log.info("VSERVERNAME " + ctx.getAttribute(prefix+ "vm.vserver-name") + " HAS NUM VNFCS = " + ctx.getAttribute(prefix+ "vm.vnfc-count")); - - } - - - - private String getRelationshipValue(int i, SvcLogicContext ctx, String relatedTo, String relationshipKey, String prefix) throws Exception { - - - if ( relatedTo.equals(ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].related-to")) ) { - - - log.info("RELATEDTO " + relatedTo); - int relationshipDataLength = 0; - String relDataLen = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data_length"); - - if ( relDataLen != null ) - relationshipDataLength = Integer.parseInt(relDataLen); - - - - for ( int j =0 ; j < relationshipDataLength ; j++) { - - String key = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-key"); - - String value = ctx.getAttribute(prefix + ".relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-value"); - - log.info("GENERIC KEY " + key); - log.info("GENERIC VALUE " + value); - - if (relationshipKey.equals(key)) { - return value; - - } - - } // relationshipDataLength - - - } // if related-To - - - return null; - - - } - - - public void getVnfcInfo(Map params,SvcLogicContext ctx ) throws Exception { - log.info("Received getVnfc call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - String vnfcName = params.get("vnfcName"); - if(StringUtils.isBlank(vnfcName)){ - throw new Exception("Vnfc Name is missing"); - } - - String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; - - String queryPrefix = "vnfcInfo"; - String resourceType = "vnfc"; - SvcLogicContext vnfcCtx = readResource(resourceKey,queryPrefix,resourceType); - - // Changes for US 315820 for 1710 vnfc-type renamed to nfc-function,vnfc-function-code renamed to nfc-naming-code - - /*ctx.setAttribute(prefix+ "vnfc.vnfc-type", vnfcCtx.getAttribute("vnfcInfo.vnfc-type")); - ctx.setAttribute(prefix+ "vnfc.vnfc-function-code", vnfcCtx.getAttribute("vnfcInfo.vnfc-function-code")); - ctx.setAttribute(prefix+ "vnfc.group-notation", vnfcCtx.getAttribute("vnfcInfo.group-notation"));*/ - - ctx.setAttribute(prefix+ "vnfc.vnfc-type", vnfcCtx.getAttribute("vnfcInfo.nfc-function")); - ctx.setAttribute(prefix+ "vnfc.vnfc-function-code", vnfcCtx.getAttribute("vnfcInfo.nfc-naming-code")); - ctx.setAttribute(prefix+ "vnfc.group-notation", vnfcCtx.getAttribute("vnfcInfo.group-notation")); - - - } - - public void insertVnfcs(Map params,SvcLogicContext ctx, int vnfcRefLen, int vmCount) throws Exception { - log.info("Received insertVnfcs call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - - - int vnfcRefIndx =-1; - for ( int i = 0; i < vmCount ; i++ ) { - String aaiRefKey = prefix + "vm[" + i + "]."; - - log.info("VNFCNAME IN INSERTVNFCS " + ctx.getAttribute(aaiRefKey + "vnfc-name")); - String numVnfcsStr = ctx.getAttribute(aaiRefKey + "vnfc-count"); - - - //if ( numVnfcsStr != null || Integer.parseInt(numVnfcsStr) >= 1 ) - - - if ( ctx.getAttribute(aaiRefKey + "vnfc-name") != null ) - continue; - else - vnfcRefIndx++; - - - // Get Vnfc_reference data - String vnfcRefKey = "vnfcReference[" + vnfcRefIndx + "]."; - - log.info("VNFCREFKEY " + vnfcRefKey); - log.info("AAIREFKEY " + aaiRefKey); - - String vmInstance = ctx.getAttribute(vnfcRefKey+ "VM-INSTANCE"); - String vnfcInstance = ctx.getAttribute(vnfcRefKey+ "VNFC-INSTANCE"); - - String groupNotationType = ctx.getAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE"); - String groupNotationValue = ctx.getAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE"); - - String vnfcType = ctx.getAttribute(vnfcRefKey+ "VNFC-TYPE"); - - String vnfcFuncCode = ctx.getAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE"); - - String populateIpAddressV4OamVip = ctx.getAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP"); - - - // Get vnfc Data to be added - String vserverName = ctx.getAttribute(aaiRefKey + "vserver-name"); - String vnfcName = vserverName + vnfcFuncCode + "001"; - - String groupNotation = getGroupNotation(groupNotationType, groupNotationValue, vnfcName, vserverName,prefix, ctx, vnfcType); - - - String ipAddressV4OamVip = null; - if ( "Y".equals(populateIpAddressV4OamVip)) - ipAddressV4OamVip = ctx.getAttribute("vnf-host-ip-address"); // from input - - - Map vnfcParams = populateVnfcParams(ctx, aaiRefKey, ipAddressV4OamVip, groupNotation, vnfcType, vnfcFuncCode); - - - addVnfc( vnfcName, vnfcParams, prefix); - - // Add VNFC Info to context for current added VNFC - ctx.setAttribute(aaiRefKey + "vnfc-name", vnfcName); - ctx.setAttribute(aaiRefKey + "vnfc-type", vnfcType); - ctx.setAttribute(aaiRefKey + "vnfc-function-code", vnfcFuncCode); - ctx.setAttribute(aaiRefKey + "group-notation", groupNotation); - - } - - - } - - - - public Map populateVnfcParams(SvcLogicContext ctx, String aaiRefKey, - String ipAddressV4OamVip, String groupNotation, String vnfcType, String vnfcFuncCode) throws Exception { - - - Map vnfcParams = new HashMap(); - - // Changes for US 315820 for 1710 vnfc-type renamed to nfc-function,vnfc-function-code renamed to nfc-naming-code - - /* - vnfcParams.put("vnfc-function-code", vnfcFuncCode); - vnfcParams.put("vnfc-type", vnfcType); - */ - vnfcParams.put("nfc-naming-code", vnfcFuncCode); - vnfcParams.put("nfc-function", vnfcType); - - // - - vnfcParams.put("ipaddress-v4-oam-vip", ipAddressV4OamVip); - - vnfcParams.put("prov-status", "NVTPROV"); - vnfcParams.put("orchestration-status", "CONFIGURED"); - vnfcParams.put("in-maint", "false"); - vnfcParams.put("is-closed-loop", "false"); - vnfcParams.put("group-notation",groupNotation); - - - vnfcParams.put("relationship-list.relationship[0].related-to","vserver"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-key","vserver.vserver-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-value",ctx.getAttribute(aaiRefKey + "vserver-id")); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-key","tenant.tenant-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-value",ctx.getAttribute(aaiRefKey + "tenant-id")); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-key","cloud-region.cloud-owner"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-value",ctx.getAttribute(aaiRefKey + "cloud-owner")); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-key","cloud-region.cloud-region-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-value",ctx.getAttribute(aaiRefKey + "cloud-region-id")); - - - - vnfcParams.put("relationship-list.relationship[1].related-to","generic-vnf"); - vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-key","generic-vnf.vnf-id"); - vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-value",ctx.getAttribute("vnf-id")); - - - vnfcParams.put("relationship-list.relationship[2].related-to","vf-module"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-key","generic-vnf.vnf-id"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-value",ctx.getAttribute("vnf-id")); - - - vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-key","vf-module.vf-module-id"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-value",ctx.getAttribute(aaiRefKey + "vf-module-id")); - - - return vnfcParams; - } - - public void addVnfc(String vnfcName, Map params, String prefix) throws Exception { - - log.info("Received addVnfc call with vnfcName : " +vnfcName); - log.info("Received addVnfc call with params : " + params); - String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; - - log.info("Received addVnfc call with resourceKey : " + resourceKey); - - - SvcLogicContext vnfcCtx = new SvcLogicContext(); - SvcLogicResource.QueryStatus response = aaiClient.save("vnfc", true, false, resourceKey, params, prefix, vnfcCtx) ; - - if (SvcLogicResource.QueryStatus.SUCCESS.equals(response)) { - log.info("Added VNFC SUCCESSFULLY " + vnfcName); - - } - else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - throw new Exception("VNFC Add failed for for vnfc_name " + vnfcName); - - } - - - } - - public String getGroupNotation(String groupNotationType, String groupNotationValue, String vnfcName, - String vserverName, String prefix, SvcLogicContext ctx, String vnfcRefVnfcType) throws Exception { - - String grpNotation = null; - - if ( "fixed-value".equals(groupNotationType)) { - grpNotation = groupNotationValue; - - } - else if ( "first-vnfc-name".equals(groupNotationType) ) { - - /*If the group-notation-type value = ?first-vnfc-name?, - * then populate the group-notation value with the concatenation of - * [vnfc name associated with the first vnfc for the vnfc-type (e.g., *******)] - * and [the value in group-notation-value (e.g., pair)]. - * There may be several vnfc-types associated with the VM?s. - */ - /* Vnfc-type should be from refrence data */ - - /* vDBE has 2 VNFCs with same VNFC type . The pair name should be same for both . */ - /* When first VNFC is added details should be added to context so FirstVnfcName doesnt return null second time. */ - String tmpVnfcName = getFirstVnfcNameForVnfcType(ctx, prefix, vnfcRefVnfcType); - - log.info("RETURNED FIRSTVNFCNAME" + tmpVnfcName); - log.info("CURRENTVNFCNAME" + vnfcName); - if ( tmpVnfcName == null ) { - log.info("CURRENTVNFCNAME" + vnfcName); - // No Vnfcs currently exist. Use Current vnfcName - grpNotation = vnfcName + groupNotationValue; - } - else - grpNotation = tmpVnfcName + groupNotationValue; - - - } - else if ( "relative-value".equals(groupNotationType) ) { - - /*If the group-notation-type = ?relative-value?, then find the group-notation value - * from the prior vnfc (where prior means the vnfc with where the last three digits of the - * vm-name is one lower than the current one; note that this vnfc may have been previously configured.) - 1. If the group-notation-value = next, then add 1 to the group-notation value from the prior vnfc and use this value - 2. If the group-notation-value = same, then use the group-notation-value from the prior vnfc record*/ - - // next and same cant be defined for first VM. if next will not generate grpNotation if Prior is not a number - String tmpVserverName = null; - if ( vserverName != null ) { - - String vmNamePrefix = vserverName.substring(0,vserverName.length()-3); - - String lastThreeChars = vserverName.substring(vserverName.length() - 3); - - if ( NumberUtils.isDigits(lastThreeChars)) { - int vmNum = Integer.parseInt(lastThreeChars) - 1; - String formatted = String.format("%03d", vmNum); - - log.info("FORMATTED " + formatted); - - tmpVserverName = vmNamePrefix + formatted; - - - String priorGroupNotation = getGroupNotationForVServer(ctx, prefix, tmpVserverName); - - if ( "same".equals(groupNotationValue)) - grpNotation = priorGroupNotation; - else if ( "next".equals(groupNotationValue)) { - if ( priorGroupNotation != null && NumberUtils.isDigits(priorGroupNotation)) { - int nextGrpNotation = Integer.parseInt(priorGroupNotation) + 1; - grpNotation = String.valueOf(nextGrpNotation); - } - } - } - - } - - - - } - - - log.info("RETURNED GROUPNOTATION " + grpNotation); - return grpNotation; - } - - public String getGroupNotationForVServer(SvcLogicContext ctx, String prefix, String vserverName) throws Exception { - - - String vmCountStr = ctx.getAttribute(prefix+"vnf.vm-count"); - - if ( vmCountStr == null ) - return null; - - int vmCount = Integer.valueOf(vmCountStr); - for ( int i = 0; i < vmCount ; i++ ) { - - String tmpVserver = ctx.getAttribute(prefix+ "vm[" + i + "].vserver-name"); - - if (vserverName.equals(tmpVserver)) - return ctx.getAttribute(prefix+ "vm[" + i + "].group-notation"); - - } // vmCount - - return null; - - } - - - - - public String getFirstVnfcNameForVnfcType(SvcLogicContext ctx, String prefix, String vnfcRefVnfcType) throws Exception { - - - - /*if(StringUtils.isBlank(vnfcRefVnfcType)){ - throw new Exception("Vnfc Reference : VNFC Type is missing"); - }*/ - - - String vmCountStr = ctx.getAttribute(prefix+"vnf.vm-count"); - - if ( vmCountStr == null ) - return null; - - int vmCount = Integer.valueOf(vmCountStr); - for ( int i = 0; i < vmCount ; i++ ) { - - String tmpvnfcType = ctx.getAttribute(prefix+ "vm[" + i + "].vnfc-type"); - - if (vnfcRefVnfcType.equals(tmpvnfcType)) - return ctx.getAttribute(prefix+ "vm[" + i + "].vnfc-name"); - - } // vmCount - - - - return null; - - } - - public void updateVServerStatus(Map params,SvcLogicContext ctx, int vmCount) throws Exception { - log.info("Received updateVServerStatus call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - - Map vServerParams = new HashMap(); - - - // TODO - Should this just update prov-status or both? What about generic-vnf status? Will that be updated by Dispatcher? - - vServerParams.put("prov-status", "NVTPROV"); - //vServerParams.put("orchestration-status", "CONFIGURED"); - - - for ( int i = 0; i < vmCount ; i++ ) { - String aaiRefKey = prefix + "vm[" + i + "]."; - - log.info("VNFCNAME IN UpdateVServer " + ctx.getAttribute(aaiRefKey + "vnfc-name")); - - if ( ctx.getAttribute(aaiRefKey + "vnfc-name") != null ) - continue; - - - - String resourceKey = "vserver.vserver-id = '" + ctx.getAttribute(aaiRefKey + "vserver-id") + "'" + - " AND tenant.tenant-id = '" + ctx.getAttribute(aaiRefKey + "tenant-id") + "'" + - " AND cloud-region.cloud-owner = '" + ctx.getAttribute(aaiRefKey + "cloud-owner") + "'" + - " AND cloud-region.cloud-region-id = '" + ctx.getAttribute(aaiRefKey + "cloud-region-id") + "'"; - - - updateResource( "vserver", resourceKey, vServerParams); - - } - - - } - - - - public void updateVnfStatus(Map params,SvcLogicContext ctx) throws Exception { - log.info("Received updateVnfStatus call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - - Map vnfParams = new HashMap(); - - - // TODO - Should this just update prov-status or both? What about generic-vnf status? Will that be updated by Dispatcher? - - vnfParams.put("prov-status", "NVTPROV"); - //vnfParams.put("orchestration-status", "CONFIGURED"); - - - String resourceKey = "generic-vnf.vnf-id = '" + ctx.getAttribute("vnf-id") + "'"; - - updateResource( "generic-vnf" , resourceKey, vnfParams); - - - - - } - - public void updateResource( String resource, String resourceKey, Map params) throws Exception { - - log.info("Received updateResource call with Key : " +resourceKey); - - - SvcLogicContext ctx = new SvcLogicContext(); - - - SvcLogicResource.QueryStatus response = aaiClient.update(resource, resourceKey , params, "tmp.update", ctx); - - - - if (SvcLogicResource.QueryStatus.SUCCESS.equals(response)) { - log.info("Updated " + resource + " SUCCESSFULLY for " + resourceKey); - - } - else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - throw new Exception(resource + " Update failed for " + resourceKey); - - } - } - - public SvcLogicContext readResource(String query, String prefix, String resourceType) throws Exception { - SvcLogicContext resourceContext = new SvcLogicContext(); - - SvcLogicResource.QueryStatus response = aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); - log.info("AAIResponse: " + response.toString()); - if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ - throw new Exception("Error Retrieving " + resourceType + " from A&AI"); - } - - return resourceContext; - - - - } - - //Added 1710 & Backward Compatibility - - public void checkAndUpdateVnfc(Map params,SvcLogicContext ctx, int vnfcRefLen, int vmCount) throws Exception { - log.info("Received checkAndUpdateVnfcStatus call with params : " + params); - - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - - for ( int i = 0; i < vmCount ; i++ ) { - String aaiRefKey = prefix + "vm[" + i + "]."; - - log.info("VNFCNAME IN INSERTVNFCS "+ aaiRefKey+"vnfc-name:" + ctx.getAttribute(aaiRefKey + "vnfc-name")); - - String numVnfcsStr = ctx.getAttribute(aaiRefKey + "vnfc-count"); - String vnfcNameAai = ctx.getAttribute(aaiRefKey + "vnfc-name"); - - if (StringUtils.isNotBlank(vnfcNameAai)) { - // Get Vnfc_reference data - for(int vnfcRefIndx=0;vnfcRefIndx < vnfcRefLen;vnfcRefIndx++ ) { - - String vnfcRefKey = "vnfcReference[" + vnfcRefIndx + "]."; - - log.info("VNFCREFKEY " + vnfcRefKey); - log.info("AAIREFKEY " + aaiRefKey); - - String vnfcFuncCode = ctx.getAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE"); - String vserverName = ctx.getAttribute(aaiRefKey + "vserver-name"); - String vnfcNameReference = vserverName + vnfcFuncCode + "001"; - - if(vnfcNameAai.equals(vnfcNameReference)) { - - updateVnfcStatus( vnfcNameAai, params, prefix); - } - - - } - } - - - - - - - } - - - } - - public void updateVnfcStatus(String vnfcName, Map params, String prefix) throws Exception { - - log.info("Received updateVnfcStatus call with vnfcName : " +vnfcName); - log.info("Received updateVnfcStatus call with params : " + params); - - String resourceKey = "vnfc.vnfc-name = '" + vnfcName + "'"; - log.info("Received updateVnfcStatus call with resourceKey : " + resourceKey); - - - Map vnfcParams = new HashMap(); - vnfcParams.put("prov-status", "NVTPROV"); - vnfcParams.put("orchestration-status", "CONFIGURED"); - - log.info("In updateVnfcStatus call with vnfcParams : " + vnfcParams); - - updateResource( "vnfc" , resourceKey, vnfcParams); - - log.info("End of updateVnfcStatus"); - - - } - - - - //Added for 1710 - - -} diff --git a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/node/AAIResourceNode.java b/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/node/AAIResourceNode.java deleted file mode 100644 index 250508358..000000000 --- a/appc-outbound/appc-aai-client/provider/src/main/java/org/openecomp/appc/aai/client/node/AAIResourceNode.java +++ /dev/null @@ -1,514 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client.node; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import org.onap.appc.aai.client.AppcAaiClientConstant; -import org.onap.appc.aai.client.aai.AaiService; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -//import com.fasterxml.jackson.databind.ObjectMapper; - - -public class AAIResourceNode implements SvcLogicJavaPlugin { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(AAIResourceNode.class); - - - public AaiService getAaiService() { - return new AaiService(); - } - /* Gets VNF Info and All VServers associated with Vnf */ - public void getVnfInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getVnfInfo call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - AaiService aai = getAaiService(); - - - - aai.getGenericVnfInfo(inParams,ctx); - - - - - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); - log.info("getVnfInfo Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getVnfInfo " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - - public void getAllVServersVnfcsInfo(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getAllVServersVnfcsInfo call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - AaiService aai = getAaiService(); - - - - ArrayList> vservers = new ArrayList>(); - - int vmWithNoVnfcsCount = 0; - String vmCountStr = ctx.getAttribute(responsePrefix + "vm-count"); - - if ( vmCountStr == null ) - throw new Exception("Unable to get VServers for the VNF"); - - int vmCount = Integer.parseInt(vmCountStr); - for ( int i = 0; i < vmCount; i++ ) { - - SvcLogicContext vmServerCtx = new SvcLogicContext(); - - Map paramsVm = new HashMap(); - paramsVm.put("vserverId", ctx.getAttribute(responsePrefix + "vm[" + i + "].vserver-id")); - paramsVm.put("tenantId", ctx.getAttribute(responsePrefix +"vm[" + i + "].tenant-id")); - paramsVm.put("cloudOwner", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-owner")); - paramsVm.put("cloudRegionId", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-region-id")); - paramsVm.put(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX, inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX)); - - - - aai.getVMInfo(paramsVm, vmServerCtx); - - HashMap vserverMap = new HashMap(); - vserverMap.put("vserver-id", ctx.getAttribute(responsePrefix + "vm[" + i + "].vserver-id")); - vserverMap.put("tenant-id", ctx.getAttribute(responsePrefix +"vm[" + i + "].tenant-id")); - vserverMap.put("cloud-owner", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-owner")); - vserverMap.put("cloud-region-id", ctx.getAttribute(responsePrefix +"vm[" + i + "].cloud-region-id")); - - // Parameters returned by getVMInfo - vserverMap.put("vserver-name", vmServerCtx.getAttribute(responsePrefix + "vm.vserver-name")); - vserverMap.put("vf-module-id", vmServerCtx.getAttribute(responsePrefix + "vm.vf-module-id")); - - - // as Per 17.07 requirements we are supporting only one VNFC per VM. - - String vnfcName = vmServerCtx.getAttribute(responsePrefix + "vm.vnfc[0].vnfc-name"); - vserverMap.put("vnfc-name", vnfcName); - - - String vnfcCount = vmServerCtx.getAttribute(responsePrefix + "vm.vnfc-count"); - if ( vnfcCount == null ) - vnfcCount = "0"; - - vserverMap.put("vnfc-count", vnfcCount); - - if ( vnfcName != null ) { - Map paramsVnfc = new HashMap(); - paramsVnfc.put("vnfcName", vnfcName); - - paramsVnfc.put(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX, inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX)); - - SvcLogicContext vnfcCtx = new SvcLogicContext(); - - aai.getVnfcInfo(paramsVnfc, vnfcCtx); - - vserverMap.put("vnfc-type", vnfcCtx.getAttribute(responsePrefix + "vnfc.vnfc-type")); - vserverMap.put("vnfc-function-code", vnfcCtx.getAttribute(responsePrefix + "vnfc.vnfc-function-code")); - vserverMap.put("group-notation", vnfcCtx.getAttribute(responsePrefix + "vnfc.group-notation")); - - - } - else - vmWithNoVnfcsCount++; - - - - vservers.add(vserverMap); - - } // vmCount - - - - - Collections.sort(vservers, new Comparator>() { - @Override - public int compare(Map o1, Map o2) { - return o1.get("vserver-name").compareTo(o2.get("vserver-name")); - } - }); - - log.info("SORTED VSERVERS " + vservers.toString()); - - populateContext(vservers, ctx, responsePrefix); - - log.info("VMCOUNT IN GETALLVSERVERS " + vmCount); - log.info("VMSWITHNOVNFCSCOUNT IN GETALLVSERVERS " + vmWithNoVnfcsCount); - ctx.setAttribute(responsePrefix+"vnf.vm-count", String.valueOf(vmCount)); - ctx.setAttribute(responsePrefix+"vnf.vm-with-no-vnfcs-count", String.valueOf(vmWithNoVnfcsCount)); - - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getAllVServersVnfcsInfo " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - - - public void populateContext(ArrayList> vservers, SvcLogicContext ctx, String prefix) { - - - log.info("Populating Final Context"); - int ctr = 0; - - for (Map entry : vservers) { - for (String key : entry.keySet()) { - String value = entry.get(key); - - ctx.setAttribute(prefix+ "vm[" + ctr + "]."+ key, value); - log.info("Populating Context Key = " + prefix+ "vm[" + ctr + "]."+ key + " Value = " + value); - - } - - - ctr++; - } - - String firstVServerName = null; - for ( int i =0; i < ctr; i++ ) { - String vnfcName = ctx.getAttribute(prefix + "vm[" + i + "].vnfc-name"); - log.info("VNFCNAME " + i + vnfcName); - if ( vnfcName == null && firstVServerName == null ) { - firstVServerName = ctx.getAttribute(prefix + "vm[" + i + "].vserver-name"); - ctx.setAttribute("vm-name" , firstVServerName); - log.info("Populating Context Key = " + "vm-name" + " Value = " + firstVServerName); - } - } - } - - - - public void addVnfcs(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received addVnfcs call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - int vnfcRefLen =0 ; - int vmCount = 0; - int vmWithNoVnfcCount = 0; - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - AaiService aai = getAaiService(); - - - - String vnfcRefLenStr = ctx.getAttribute("vnfcReference_length"); - - if ( vnfcRefLenStr == null) { - log.info("Vnfc Reference data is missing"); - throw new Exception("Vnfc Reference data is missing"); - - } - else - vnfcRefLen = Integer.parseInt(vnfcRefLenStr); - - String vmWithNoVnfcCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-with-no-vnfcs-count"); - - //Commented for backward compatibility - - /*if ( vmWithNoVnfcCountStr == null) { - throw new Exception("VNFCs to be added data from A&AI is missing"); - //log.info("VNFCs to be added data from A&AI is missing"); - } - else - vmWithNoVnfcCount = Integer.parseInt(vmWithNoVnfcCountStr); - - if ( vmWithNoVnfcCount!= vnfcRefLen ) - throw new Exception("Unable to Add Vnfcs to A&AI. Reference data mismatch."); - - String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); - - if ( vmCountStr == null) - throw new Exception("VM data from A&AI is missing"); - else - vmCount = Integer.parseInt(vmCountStr); - - - log.info("VMCOUNT " + vmCount); - log.info("VNFCREFLEN " + vnfcRefLen); - aai.insertVnfcs(inParams,ctx, vnfcRefLen, vmCount); - - */ - - - // Modified for 1710 - - if ( vmWithNoVnfcCountStr == null) { - log.info("Parameter VM without VNFCs(vmWithNoVnfcCountStr) from A&AI is Null"); - } - else - vmWithNoVnfcCount = Integer.parseInt(vmWithNoVnfcCountStr); - - log.info("No of VM without VNFCs(vmWithNoVnfcCount) from A&AI is " +vmWithNoVnfcCount); - - String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); - - if ( vmCountStr == null) - throw new Exception("VM data from A&AI is missing"); - else - vmCount = Integer.parseInt(vmCountStr); - - log.info("VMCOUNT " + vmCount); - log.info("VNFCREFLEN " + vnfcRefLen); - - if ( vmWithNoVnfcCount!= vnfcRefLen ) { - //throw new Exception("Unable to Add Vnfcs to A&AI. Reference data mismatch."); - log.info("vmWithNoVnfcCount and vnfcRefLen data from table are not same "); - aai.checkAndUpdateVnfc(inParams,ctx, vnfcRefLen, vmCount); - } - - else { - - aai.insertVnfcs(inParams,ctx, vnfcRefLen, vmCount); - } - - //// Modified 1710 - - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); - - log.info("addVnfcs Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in addVnfcs " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - - public void updateVnfAndVServerStatus(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received updateVnfAndVServerStatus call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - - int vmCount = 0; - - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - AaiService aai = getAaiService(); - - - - String vmCountStr = ctx.getAttribute(responsePrefix+"vnf.vm-count"); - - if ( vmCountStr == null) - throw new Exception("VM data from A&AI is missing"); - else - vmCount = Integer.parseInt(vmCountStr); - - - log.info("VMCOUNT " + vmCount); - - - aai.updateVnfStatus(inParams, ctx); - aai.updateVServerStatus(inParams,ctx, vmCount); - - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_SUCCESS); - - log.info("updateVnfAndVServerStatus Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in updateVnfAndVServerStatus " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - } - - /*public void getDummyValues(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getDummyValues call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String instarKeys = inParams.get("instarKeys"); - ObjectMapper mapper = new ObjectMapper(); - if ( instarKeys != null ) { - - List keyList = mapper.readValue(instarKeys, ArrayList.class); - - Map instarParams =new HashMap(); - if(keyList != null){ - //System.out.println(keyList.toString()); - - - for(int i=0;i"+keyList.get(i)); - - //ctx.setAttribute(keyList.get(i), "test" + i); - - instarParams.put( keyList.get(i), "test" + i); - } - - } - log.info("INSTARPARAMMAP " + instarParams); - String jsonString = mapper.writeValueAsString(instarParams); - log.info(jsonString); - ctx.setAttribute(responsePrefix + "configuration-parameters", jsonString); - - } - - log.info("getDummyValues Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getDummyValues " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - - } - - */ - /*public void getRequestKeys(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - log.info("Received getRequestKeys call with params : " + inParams); - - String responsePrefix = inParams.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - try { - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""; - String instarKeys = inParams.get("instarKeys"); - - ObjectMapper mapper = new ObjectMapper(); - if ( instarKeys != null ) { - - List keyList = mapper.readValue(instarKeys, ArrayList.class); - - //Map instarParams =new HashMap(); - if(keyList != null){ - - - for(int i=0;i"+keyList.get(i)); - - - String instarParameter = ctx.getAttribute("INSTAR." + keyList.get(i)); - log.info("INSTARPARAMETER " + instarParameter); - Parameter param = parseParameterContent(instarParameter); - - log.info("PARAMETER KEY SIZE " + param.getRequestKeys().size()); - log.info("RULE TYPE " + param.getClassType()); - - for ( int j =0 ; j < param.getRequestKeys().size() ; j++ ) { - - log.info(" PARAM KEY NAME " + param.getRequestKeys().get(j).getKeyName()); - log.info(" PARAM KEY VALUE " + param.getRequestKeys().get(j).getKeyValue()); - } - - // instarParams.put( keyList.get(i), "test" + i); - } - - } - //log.info("INSTARPARAMMAP " + instarParams); - //String jsonString = mapper.writeValueAsString(instarParams); - //log.info(jsonString); - //ctx.setAttribute(responsePrefix + "configuration-parameters", jsonString); - - } - - log.info("getRequestKeys Successful "); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_STATUS, - AppcAaiClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + AppcAaiClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed in getRequestKeys " + e.getMessage()); - - throw new SvcLogicException(e.getMessage()); - } - - } - - - public Parameter parseParameterContent(String parameter) throws JsonParseException, JsonMappingException, IOException{ - Parameter parameterDefinition = null; - if(StringUtils.isNotBlank(parameter)){ - ObjectMapper mapper = new ObjectMapper(); - parameterDefinition = mapper.readValue(parameter, Parameter.class); - } - return parameterDefinition; - }*/ -} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/MockAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/MockAaiService.java new file mode 100644 index 000000000..724c8bf3b --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/MockAaiService.java @@ -0,0 +1,541 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client.aai; +import static org.junit.Assert.assertEquals; + +import static org.junit.Assert.fail; + + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; + +public class MockAaiService extends AaiService { + + //ONAP migration + + private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAaiService.class); + private AAIClient aaiClient; + + public MockAaiService(AAIClient aaic) { + super(aaic); + } + + + /*public MockAaiService() { + super(new AAIClientMock()); + }*/ + + public SvcLogicContext readResource(String query, String prefix, String resourceType) throws Exception { + log.info("In MockRead Resource"); + SvcLogicContext resourceContext = new SvcLogicContext(); + + //prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; + if ( "generic-vnf".equals(resourceType) ) { + populateGenericVnfContext(resourceContext, prefix); + } + else if("vserver".equals(resourceType) ) { + populateVmContext(resourceContext, prefix); + } + else if("vnfc".equals(resourceType) ) { + populateVnfcContext(resourceContext, prefix); + } + + + return resourceContext; + + + + } + + public void addVnfc(String vnfcName, Map params, String prefix) throws Exception { + + + if ( vnfcName.startsWith("ibcx")) { + assertEquals("ibcxvm0002func0001", vnfcName); + + + log.info("In AddVnfc " + vnfcName); + Map expectedParams = getExpectedParams(); + + + /* for (Map.Entry entry : params.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + + log.info("key= " + key + "value = " + value ); + + }*/ + assertEquals(params, expectedParams); + } + } + + + public void updateResource( String resource, String resourceKey, Map params) throws Exception { + + Map expectedParams = new HashMap(); + + + expectedParams.put("prov-status", "NVTPROV"); + assertEquals(params, expectedParams); + + if ( "vserver".equals(resource)) { + + String key = "vserver.vserver-id = 'ibcx00000'" + + " AND tenant.tenant-id = 'tenantId'" + + " AND cloud-region.cloud-owner = 'cloudOwner'" + + " AND cloud-region.cloud-region-id = 'cloudRegionId'"; + + assertEquals(key, resourceKey); + } + else if ( "generic-vnf".equals(resource)) { + assertEquals(resourceKey, "generic-vnf.vnf-id = 'ibcx000000'"); + } + else + fail("Invalid resource " + resource); + + + + + } + + public Map getExpectedParams() throws Exception { + Map vnfcParams = new HashMap(); + + vnfcParams.put("vnfc-function-code", "func0"); + + + + vnfcParams.put("vnfc-type", "ssc0"); + + vnfcParams.put("ipaddress-v4-oam-vip", "000.00.00.00"); + + vnfcParams.put("prov-status", "NVTPROV"); + vnfcParams.put("orchestration-status", "CONFIGURED"); + vnfcParams.put("in-maint", "false"); + vnfcParams.put("is-closed-loop", "false"); + vnfcParams.put("group-notation","2"); + + + vnfcParams.put("relationship-list.relationship[0].related-to","vserver"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-key","vserver.vserver-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-value","ibcx00000"); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-key","tenant.tenant-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-value","tenantId"); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-key","cloud-region.cloud-owner"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-value","cloudOwner"); + + + vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-key","cloud-region.cloud-region-id"); + vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-value","cloudRegionId"); + + + vnfcParams.put("relationship-list.relationship[1].related-to","generic-vnf"); + vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-key","generic-vnf.vnf-id"); + vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-value","ibcx000000"); + + + vnfcParams.put("relationship-list.relationship[2].related-to","vf-module"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-key","generic-vnf.vnf-id"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-value","ibcx000000"); + + + vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-key","vf-module.vf-module-id"); + vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-value","vfModuleId"); + + return vnfcParams; + } + public void populateVnfcContext(SvcLogicContext ctx, String prefix) { + log.info("In populateVnfcContext " + prefix); + + ctx.setAttribute(prefix + ".vnfc-type", "vnfctype1"); + ctx.setAttribute(prefix + ".vnfc-function-code", "funccode1"); + ctx.setAttribute(prefix + ".group-notation", "grpnot1"); + } + + public void populateVmContext(SvcLogicContext ctx, String prefix) { + log.info("In populateVmContext " + prefix); + + ctx.setAttribute(prefix + ".vserver-name", "ibcx0000000"); + + + ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); + + // Junk + ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "test"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "1"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vnfc.vnfc-name"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "test"); + + + + // VNFC + ctx.setAttribute(prefix + ".relationship-list.relationship[1].related-to", "vnfc"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data_length", "1"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-key", "vnfc.vnfc-name"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-value", "ibcx0001vm001vnfc1"); + + + // VFModule + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].related-to", "vf-module"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data_length", "1"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-key", "vf-module.vf-module-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-value", "vfModule1"); + + + } + + public void populateGenericVnfContext(SvcLogicContext ctx, String prefix) throws Exception { + + log.info("In populateGenericVnf " + prefix); + ctx.setAttribute(prefix + ".vnf-name", "ibvcx0001"); + ctx.setAttribute(prefix + ".vnf-type", "vUSP-Metaswitch"); + + ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); + + /* // VM1 + ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "vserver"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "4"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vserver.vserver-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "ibcx001vm001-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-key", "tenant.tenant-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-value", "sometenant"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-value", "testcloudregionid"); + + + //ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); +*/ + // VM1 + ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "vserver"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "4"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vserver.vserver-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "ibcx001vm001-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-key", "tenant.tenant-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-value", "sometenant"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-value", "testcloudregionid"); + + + // VM2 + ctx.setAttribute(prefix + ".relationship-list.relationship[1].related-to", "vserver"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data_length", "4"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-key", "vserver.vserver-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-value", "ibcx000000"); + + + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[1].relationship-key", "tenant.tenant-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[1].relationship-value", "sometenant"); + + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); + ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); + + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); + ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[3].relationship-value", "testcloudregionid"); + + + // Unrelated + ctx.setAttribute(prefix + ".relationship-list.relationship[2].related-to", "junk"); + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data_length", "4"); + + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-key", "test"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-value", "ibcx000000"); + + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[1].relationship-key", "test1"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[1].relationship-value", "sometenant"); + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[2].relationship-key", "test2"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[2].relationship-value", "ATTAIC"); + + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[3].relationship-key", "test3"); + ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[3].relationship-value", "testcloudregionid"); + } + + + + public void populateFirstVnfcData(SvcLogicContext ctx, String prefix) throws Exception { + + + + ctx.setAttribute(prefix + "vnf.vm-count", "4"); + + ctx.setAttribute(prefix+ "vm[0].vnfc-type", "mmc"); + ctx.setAttribute(prefix+ "vm[0].vnfc-name", "vnfcname1"); + + ctx.setAttribute(prefix+ "vm[1].vnfc-type", "mmc"); + ctx.setAttribute(prefix+ "vm[1].vnfc-name", "vnfcname2"); + + ctx.setAttribute(prefix+ "vm[2].vnfc-type", "ssc"); + ctx.setAttribute(prefix+ "vm[2].vnfc-name", "vnfcname3"); + + ctx.setAttribute(prefix+ "vm[3].vnfc-type", "ssc"); + ctx.setAttribute(prefix+ "vm[3].vnfc-name", "vnfcname4"); + } + + + + public void populateGroupNotation(SvcLogicContext ctx, String prefix) throws Exception { + + + + ctx.setAttribute(prefix + "vnf.vm-count", "5"); + + ctx.setAttribute(prefix+ "vm[0].vserver-name", "ibcxvm0001"); + ctx.setAttribute(prefix+ "vm[0].group-notation", "grpNot1"); + + ctx.setAttribute(prefix+ "vm[1].vserver-name", "ibcxvm0002"); + ctx.setAttribute(prefix+ "vm[1].group-notation", "grpNot2"); + + + ctx.setAttribute(prefix+ "vm[2].vserver-name", "ibcxvm0003"); + ctx.setAttribute(prefix+ "vm[2].group-notation", "grpNot3"); + + ctx.setAttribute(prefix+ "vm[3].vserver-name", "ibcxvm0004"); + ctx.setAttribute(prefix+ "vm[3].group-notation", "4"); + + ctx.setAttribute(prefix+ "vm[4].vserver-name", "ibcxvm0005"); + ctx.setAttribute(prefix+ "vm[4].group-notation", "4"); + } + + + public void populateVnfcRef(SvcLogicContext ctx) throws Exception { + + for (int i = 0; i < 2; i++ ) { + + String vnfcRefKey = "vnfcReference[" + i+ "]."; + + + + ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); + ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); + + + //if ( i == 0 || i == 1 ) { + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "2"); + //} + + ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "ssc"+i ); + + ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "func" +i); + + ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); + } + + } + + public void populateAllVnfInfo(SvcLogicContext ctx, String prefix) throws Exception { + + ctx.setAttribute("vnf-id", "ibcx000000"); + + ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); + ctx.setAttribute(prefix + ".vnf.vm-count", "2"); + + + + + ctx.setAttribute(prefix+ ".vm[0].vserver-name", "ibcxvm0000"); + ctx.setAttribute(prefix+ ".vm[0].vnfc-name", "VNFCNAME"); + + ctx.setAttribute(prefix+ ".vm[0].vserver-id", "ibcxvm0001id"); + ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid"); + ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner"); + ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId"); + + ctx.setAttribute(prefix+ ".vm[0].vf-module-id", "vfModuleId"); + + + + ctx.setAttribute(prefix+ ".vm[1].vserver-name", "ibcxvm0002"); + + ctx.setAttribute(prefix+ ".vm[1].vserver-id", "ibcx00000"); + ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantId"); + ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner"); + ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId"); + + ctx.setAttribute(prefix+ ".vm[1].vf-module-id", "vfModuleId"); + + + //ctx.setAttribute(prefix+ ".vm[1].vserver-name", "ibcxvm0002"); + + + + + } + + + + public void populateAllVnfInfo1(SvcLogicContext ctx, String prefix) throws Exception { + + ctx.setAttribute("vnf-id", "dbjx0001v"); + + ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); + ctx.setAttribute(prefix + ".vnf.vm-count", "2"); + + + + + ctx.setAttribute(prefix+ ".vm[0].vserver-name", "dbjx0001vm001"); + + + ctx.setAttribute(prefix+ ".vm[0].vserver-id", "dbjx0001vm0001id"); + ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid1"); + ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner1"); + ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId1"); + + ctx.setAttribute(prefix+ ".vm[0].vf-module-id", "vfModuleId1"); + + + + ctx.setAttribute(prefix+ ".vm[1].vserver-name", "dbjx0001vm002"); + + ctx.setAttribute(prefix+ ".vm[1].vserver-id", "dbjx0001vm0002id"); + ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantId2"); + ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner2"); + ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId2"); + + ctx.setAttribute(prefix+ ".vm[1].vf-module-id", "vfModuleId2"); + + + + } + + public void populateVnfcRefFirstVnfcName(SvcLogicContext ctx) throws Exception { + + + for (int i = 0; i < 2; i++ ) { + + String vnfcRefKey = "vnfcReference[" + i+ "]."; + + + + ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); + ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); + + + + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "first-vnfc-name"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "pair"); + + + ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "vDBE-I? - DBJX" ); + + ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); + + ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); + } + + } + + public void populateVnfcRefRelValueSame(SvcLogicContext ctx) throws Exception { + + + for (int i = 0; i < 2; i++ ) { + + String vnfcRefKey = "vnfcReference[" + i+ "]."; + + + + ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); + ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); + + + + if ( i == 0 ) { + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "1"); + } + else { + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "relative-value"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "same"); + } + + + + ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "v-I? - DBJX" ); + + ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); + + ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); + } + + } + + + public void populateVnfcRefRelValueNext(SvcLogicContext ctx) throws Exception { + + + for (int i = 0; i < 2; i++ ) { + + String vnfcRefKey = "vnfcReference[" + i+ "]."; + + + + ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); + ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); + + + + if ( i == 0 ) { + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "1"); + } + else { + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "relative-value"); + ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "next"); + } + + + + ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "v-I? - DBJX" ); + + ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); + + ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); + } + + } + +} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/TestAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/TestAaiService.java new file mode 100644 index 000000000..aa807087f --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/aai/TestAaiService.java @@ -0,0 +1,351 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client.aai; + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestAaiService { + // ONAP merging + + private static final EELFLogger log = EELFManager.getInstance().getLogger(TestAaiService.class); + private AAIClient aaiClient; + + @Test + public void testGetGenericVnfInfo() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + inParams.put("vnfId", "ibcxvm0000"); + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.getGenericVnfInfo(inParams, ctx); + + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-type"), "vUSP-Metaswitch"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm-count"), "2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "ibcx001vm001-id"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-id"), "ibcx000000"); + } + + @Test + public void testGetVmInfo() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + inParams.put("vserverId", "vserverId1"); + inParams.put("tenantId", "tenantId1"); + inParams.put("cloudOwner", "cloudOwner1"); + inParams.put("cloudRegionId", "cloudRegionId1"); + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.getVMInfo(inParams, ctx); + + printContext(ctx); + + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vserver-name"), "ibcx0000000"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vnfc-count"), "1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vf-module-id"), "vfModule1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vnfc[0].vnfc-name"), "ibcx0001vm001vnfc1"); + + } + + @Test + public void testGetVnfcInfo() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + inParams.put("vnfcName", "vnfcName1"); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.getVnfcInfo(inParams, ctx); + + printContext(ctx); + + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.vnfc-type"), null); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.vnfc-function-code"), null); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.group-notation"), "grpnot1"); + + } + + @Test + public void testGetFirstVnfcNameForVnfcType() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + String prefix = "tmp.vnfInfo."; + + SvcLogicContext ctx = new SvcLogicContext(); // VNFC with specified vnfc + // type found + mockAai.populateFirstVnfcData(ctx, prefix); + String firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "ssc"); + assertEquals(firstVnfcName, "vnfcname3"); + + ctx = new SvcLogicContext(); // no VMS found + firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "ssc"); + assertEquals(firstVnfcName, null); + + ctx = new SvcLogicContext(); // no VMS found with specified type + mockAai.populateFirstVnfcData(ctx, prefix); + firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "test"); + assertEquals(firstVnfcName, null); + + } + + @Test + public void testGroupNotation() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + String prefix = "tmp.vnfInfo."; + + SvcLogicContext ctx = new SvcLogicContext(); + mockAai.populateGroupNotation(ctx, prefix); + + // printContext(ctx); + String grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "ibcxvm0002"); + assertEquals(grpNotation, "grpNot2"); + + ctx = new SvcLogicContext(); // no VMS found + grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "ibcxvm0002"); + assertEquals(grpNotation, null); + + ctx = new SvcLogicContext(); // no VMS found with specified name + mockAai.populateGroupNotation(ctx, prefix); + grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "test"); + assertEquals(grpNotation, null); + + } + + @Test + public void testGetGroupNotation() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + String prefix = "tmp.vnfInfo."; + + SvcLogicContext ctx = new SvcLogicContext(); + + String grpNotation = mockAai.getGroupNotation("fixed-value", "2", null, null, null, null, null); + assertEquals(grpNotation, "2"); + + mockAai.populateFirstVnfcData(ctx, prefix); // Existing VNFC Found + grpNotation = mockAai.getGroupNotation("first-vnfc-name", "2", "currentVnfcName", "currentVServerName", prefix, + ctx, "ssc"); + assertEquals(grpNotation, "vnfcname32"); + + ctx = new SvcLogicContext(); // no vnfcs exist in A&AI- Use current + // vnfcName + grpNotation = mockAai.getGroupNotation("first-vnfc-name", "2", "currentVnfcName", "currentVServerName", prefix, + ctx, "ssc"); + assertEquals(grpNotation, "currentVnfcName2"); + + ctx = new SvcLogicContext(); + mockAai.populateGroupNotation(ctx, prefix); + grpNotation = mockAai.getGroupNotation("relative-value", "same", "currentVnfcName", "ibcxvm0003", prefix, ctx, + "ssc"); + assertEquals(grpNotation, "grpNot2"); + + ctx = new SvcLogicContext(); + mockAai.populateGroupNotation(ctx, prefix); + grpNotation = mockAai.getGroupNotation("relative-value", "next", "currentVnfcName", "ibcxvm0006", prefix, ctx, + "ssc"); + assertEquals(grpNotation, "5"); + + ctx = new SvcLogicContext(); + mockAai.populateGroupNotation(ctx, prefix); + grpNotation = mockAai.getGroupNotation("relative-value", "next", "currentVnfcName", "ibcxvm0003", prefix, ctx, + "ssc"); + assertEquals(grpNotation, null); // Null if grpNotation is not numeric + + } + + @Test + public void testInsertVnfcs() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateVnfcRef(ctx); + + mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); + + // mockAai.insertVnfcs(inParams,ctx,2, 2) ; + } + + @Test + public void testUpdateVServerStatus() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); + + mockAai.updateVServerStatus(inParams, ctx, 2); + } + + @Test + public void testInsertVnfcsForFirstVnfc() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateVnfcRefFirstVnfcName(ctx); + + mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); + + mockAai.insertVnfcs(inParams, ctx, 2, 2); + + + } + @Test + public void testInsertVnfcsForRelativeValueSame() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateVnfcRefRelValueSame(ctx); + + mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); + + mockAai.insertVnfcs(inParams, ctx, 2, 2); + + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name"), "dbjx0001vm001dbj001"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-function-code"), "dbj"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-type"), "v-I? - DBJX"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].group-notation"), "1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "dbjx0001vm002dbj001"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "dbj"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "v-I? - DBJX"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "1"); + } + + @Test + public void testInsertVnfcsForRelativeValueNext() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateVnfcRefRelValueNext(ctx); + + mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); + + mockAai.insertVnfcs(inParams, ctx, 2, 2); + + + + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name"), "dbjx0001vm001dbj001"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-function-code"), "dbj"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-type"), "v-I? - DBJX"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].group-notation"), "1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "dbjx0001vm002dbj001"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "dbj"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "v-I? - DBJX"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "2"); + } + + @Test + public void testUpdateVnfStatus() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + + Map inParams = new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + + SvcLogicContext ctx = new SvcLogicContext(); + + mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); + + mockAai.updateVnfStatus(inParams, ctx); + } + + @Test + public void testReadResource() throws Exception { + + MockAaiService mockAai = new MockAaiService(aaiClient); + // AaiService mockAai = new AaiService(new AAIClientMock()); + + String vnfId = "ibcx0001v"; + String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "'"; + String resourceType = "generic-vnf"; + String queryPrefix = "vnfInfo"; + SvcLogicContext ctx = mockAai.readResource(resourceKey, queryPrefix, resourceType); + + // System.out.println("VNF TYPE " + queryPrefix + ".vnf.vnf-type"); + + assertEquals(ctx.getAttribute("vnfInfo.vnf-type"), "vUSP-Metaswitch"); + + } + private void printContext(SvcLogicContext ctx) throws Exception { + for (String key : ctx.getAttributeKeySet()) { + log.info(" KEY " + key); + log.info(" VALUE " + ctx.getAttribute(key)); + } + } +} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/MockAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/MockAaiService.java new file mode 100644 index 000000000..2e03e6b5a --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/MockAaiService.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.aai.client.node; +import static junit.framework.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.aai.client.AppcAaiClientConstant; +//import org.onap.appc.aai.client.aai.AAIClientMock; +import org.onap.appc.aai.client.aai.AaiService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; + +public class MockAaiService extends AaiService { + + // ONAP merging + private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAaiService.class); + private AAIClient aaiClient; + + /*public MockAaiService() { + super(new AAIClientMock()); + }*/ + + + public MockAaiService(AAIClient aaic) { + super(aaic); + } + + public void getVMInfo(Map params,SvcLogicContext ctx ) throws Exception { + log.info("Received Mock getVmInfo call with params : " + params); + String vserverId = params.get("vserverId"); + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + if ( vserverId.equals("ibcm0001id")) { + ctx.setAttribute(prefix + ".vm.vserver-name", "vserverName1"); + ctx.setAttribute(prefix + ".vm.vf-module-id", "vfModule1"); + } + else { + ctx.setAttribute(prefix + ".vm.vserver-name", "vserverName2"); + ctx.setAttribute(prefix + ".vm.vf-module-id", "vfModule2"); + ctx.setAttribute(prefix + ".vm.vnfc[0].vnfc-name", "vnfcName2"); + } + + } + + + public void getVnfcInfo(Map params,SvcLogicContext ctx ) throws Exception { + log.info("Received Mock getVmInfo call with params : " + params); + String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); + + String vnfcName = params.get("vnfcName"); + + if ( vnfcName.equals("vnfcName2") ) { + ctx.setAttribute(prefix + ".vnfc.vnfc-type", "vnfcType2"); + ctx.setAttribute(prefix + ".vnfc.vnfc-function-code", "vnfcFuncCode2"); + ctx.setAttribute(prefix + ".vnfc.group-notation", "vnfcGrpNot2"); + } + + + } +} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/TestAAIResourceNode.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/TestAAIResourceNode.java new file mode 100644 index 000000000..6b05c08bb --- /dev/null +++ b/appc-outbound/appc-aai-client/provider/src/test/java/org/onap/appc/aai/client/node/TestAAIResourceNode.java @@ -0,0 +1,238 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.aai.client.node; + +import static org.junit.Assert.*; + +import java.io.File; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.aai.client.AppcAaiClientConstant; +import org.onap.appc.aai.client.aai.AaiService; +import org.onap.appc.aai.client.aai.TestAaiService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; + +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class TestAAIResourceNode { + + //Removed for ONAP integration + + private static final EELFLogger log = EELFManager.getInstance().getLogger(TestAAIResourceNode.class); + + @Test + public void sortVServer() throws Exception{ + + //log.info("Test"); + + ArrayList> vservers = new ArrayList>(); + HashMap vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId9"); + vserverMap.put("tenant-id", "tenantId9"); + vserverMap.put("cloud-owner", "cloudOwner9"); + vserverMap.put("cloud-region-id", "cloudRegionId9"); + vserverMap.put("vserver-name", "vServerName9"); + vservers.add(vserverMap); + vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId1"); + vserverMap.put("tenant-id", "tenantId1"); + vserverMap.put("cloud-owner", "cloudOwner1"); + vserverMap.put("cloud-region-id", "cloudRegionId1"); + vserverMap.put("vserver-name", "vServerName1"); + vservers.add(vserverMap); + vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId3"); + vserverMap.put("tenant-id", "tenantId3"); + vserverMap.put("cloud-owner", "cloudOwner3"); + vserverMap.put("cloud-region-id", "cloudRegionId3"); + vserverMap.put("vserver-name", "vServerName3"); + vservers.add(vserverMap); + Collections.sort(vservers, new Comparator>() { + @Override + public int compare(Map o1, Map o2) { + return o1.get("vserver-name").compareTo(o2.get("vserver-name")); + } + }); + + SvcLogicContext ctx = new SvcLogicContext(); + AAIResourceNode aai = new AAIResourceNode(); + aai.populateContext(vservers, ctx, "vserver."); + log.info(ctx.getAttribute("vserver.vm[0].vserver-name")); + } + + @Test + public void testAllVServer() throws Exception{ + + MockAAIResourceNode mrn = new MockAAIResourceNode(); + SvcLogicContext ctx = new SvcLogicContext(); + populateAllVServerInfo(ctx, "tmp.vnfInfo"); + Map inParams =new HashMap(); + inParams.put("responsePrefix", "tmp.vnfInfo"); + mrn.getAllVServersVnfcsInfo(inParams, ctx); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm-count"), "2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vm-count"), "2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vm-with-no-vnfcs-count"), "0"); + // VM1 + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "ibcsm0002id"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].tenant-id"), "tenantid2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-owner"), "cloudOwner2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-region-id"), "cloudRegionId2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-name"), "vserverName2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vf-module-id"), "vfModule2"); + //assertNull(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name")); + + // VM2 + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-id"), "ibcxvm0001id"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].tenant-id"), "tenantid1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].cloud-owner"), "cloudOwner1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].cloud-region-id"), "cloudRegionId1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-name"), "vserverName2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vf-module-id"), "vfModule2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "vnfcName2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "vnfcType2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "vnfcFuncCode2"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "vnfcGrpNot2"); + } + public void populateAllVServerInfo(SvcLogicContext ctx, String prefix) throws Exception { + ctx.setAttribute("vnf-id", "ibcx0001v"); + ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); + ctx.setAttribute(prefix + ".vm-count", "2"); + ctx.setAttribute(prefix+ ".vm[0].vserver-id", "ibcsm0002id"); + ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid2"); + ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner2"); + ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId2"); + ctx.setAttribute(prefix+ ".vm[1].vserver-id", "ibcxvm0001id"); + ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantid1"); + ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner1"); + ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId1"); + + } + + public static class MockAAIResourceNode extends AAIResourceNode { + private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAAIResourceNode.class); + private AAIClient aaiClient; + + public AaiService getAaiService() { + log.info("In MockAAI"); + return new MockAaiService(aaiClient); + } + } + + @Test + public void testPopulateContext() throws Exception{ + + ArrayList> vservers = new ArrayList>(); + HashMap vserverMap = new HashMap(); + vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId1"); + vserverMap.put("tenant-id", "tenantId1"); + vserverMap.put("cloud-owner", "cloudOwner1"); + vserverMap.put("cloud-region-id", "cloudRegionId1"); + vserverMap.put("vserver-name", "vServerName1"); + vserverMap.put("vnfc-name", "vnfcName1"); + vservers.add(vserverMap); + vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId3"); + vserverMap.put("tenant-id", "tenantId3"); + vserverMap.put("cloud-owner", "cloudOwner3"); + vserverMap.put("cloud-region-id", "cloudRegionId3"); + vserverMap.put("vserver-name", "vServerName3"); + vservers.add(vserverMap); + vserverMap = new HashMap(); + vserverMap.put("vserver-id", "vserverId9"); + vserverMap.put("tenant-id", "tenantId9"); + vserverMap.put("cloud-owner", "cloudOwner9"); + vserverMap.put("cloud-region-id", "cloudRegionId9"); + vserverMap.put("vserver-name", "vServerName9"); + vservers.add(vserverMap); + SvcLogicContext ctx = new SvcLogicContext(); + AAIResourceNode aai = new AAIResourceNode(); + aai.populateContext(vservers, ctx, "tmp.vnfInfo."); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-name"), "vServerName1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].tenant-id"), "tenantId1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-owner"), "cloudOwner1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-region-id"), "cloudRegionId1"); + assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "vserverId1"); + assertEquals(ctx.getAttribute("vm-name"), "vServerName3"); + } + + @Test + public final void testGetVnfInfo() { + SvcLogicContext ctx = new SvcLogicContext(); + AAIResourceNode aai = new AAIResourceNode(); +Map inParams =new HashMap(); + inParams.put("responsePrefix", "tmp.vnfInfo"); + try { + aai.getVnfInfo(inParams, ctx); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + + } + @Test + public final void testaddVnfcs() + { + SvcLogicContext ctx = new SvcLogicContext(); + AAIResourceNode aai = new AAIResourceNode(); +Map inParams =new HashMap(); + inParams.put("responsePrefix", "tmp.vnfInfo"); + try { + aai.addVnfcs(inParams, ctx); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + + } + @Test + public final void testupdateVnfAndVServerStatus(){ + SvcLogicContext ctx = new SvcLogicContext(); + AAIResourceNode aai = new AAIResourceNode(); +Map inParams =new HashMap(); + + inParams.put("responsePrefix", "tmp.vnfInfo"); + try { + aai.updateVnfAndVServerStatus(inParams, ctx); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + } +} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/MockAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/MockAaiService.java deleted file mode 100644 index 724c8bf3b..000000000 --- a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/MockAaiService.java +++ /dev/null @@ -1,541 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client.aai; -import static org.junit.Assert.assertEquals; - -import static org.junit.Assert.fail; - - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; - -public class MockAaiService extends AaiService { - - //ONAP migration - - private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAaiService.class); - private AAIClient aaiClient; - - public MockAaiService(AAIClient aaic) { - super(aaic); - } - - - /*public MockAaiService() { - super(new AAIClientMock()); - }*/ - - public SvcLogicContext readResource(String query, String prefix, String resourceType) throws Exception { - log.info("In MockRead Resource"); - SvcLogicContext resourceContext = new SvcLogicContext(); - - //prefix = StringUtils.isNotBlank(prefix) ? (prefix+".") : ""; - if ( "generic-vnf".equals(resourceType) ) { - populateGenericVnfContext(resourceContext, prefix); - } - else if("vserver".equals(resourceType) ) { - populateVmContext(resourceContext, prefix); - } - else if("vnfc".equals(resourceType) ) { - populateVnfcContext(resourceContext, prefix); - } - - - return resourceContext; - - - - } - - public void addVnfc(String vnfcName, Map params, String prefix) throws Exception { - - - if ( vnfcName.startsWith("ibcx")) { - assertEquals("ibcxvm0002func0001", vnfcName); - - - log.info("In AddVnfc " + vnfcName); - Map expectedParams = getExpectedParams(); - - - /* for (Map.Entry entry : params.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - - - log.info("key= " + key + "value = " + value ); - - }*/ - assertEquals(params, expectedParams); - } - } - - - public void updateResource( String resource, String resourceKey, Map params) throws Exception { - - Map expectedParams = new HashMap(); - - - expectedParams.put("prov-status", "NVTPROV"); - assertEquals(params, expectedParams); - - if ( "vserver".equals(resource)) { - - String key = "vserver.vserver-id = 'ibcx00000'" + - " AND tenant.tenant-id = 'tenantId'" + - " AND cloud-region.cloud-owner = 'cloudOwner'" + - " AND cloud-region.cloud-region-id = 'cloudRegionId'"; - - assertEquals(key, resourceKey); - } - else if ( "generic-vnf".equals(resource)) { - assertEquals(resourceKey, "generic-vnf.vnf-id = 'ibcx000000'"); - } - else - fail("Invalid resource " + resource); - - - - - } - - public Map getExpectedParams() throws Exception { - Map vnfcParams = new HashMap(); - - vnfcParams.put("vnfc-function-code", "func0"); - - - - vnfcParams.put("vnfc-type", "ssc0"); - - vnfcParams.put("ipaddress-v4-oam-vip", "000.00.00.00"); - - vnfcParams.put("prov-status", "NVTPROV"); - vnfcParams.put("orchestration-status", "CONFIGURED"); - vnfcParams.put("in-maint", "false"); - vnfcParams.put("is-closed-loop", "false"); - vnfcParams.put("group-notation","2"); - - - vnfcParams.put("relationship-list.relationship[0].related-to","vserver"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-key","vserver.vserver-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[0].relationship-value","ibcx00000"); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-key","tenant.tenant-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[1].relationship-value","tenantId"); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-key","cloud-region.cloud-owner"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[2].relationship-value","cloudOwner"); - - - vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-key","cloud-region.cloud-region-id"); - vnfcParams.put("relationship-list.relationship[0].relationship-data[3].relationship-value","cloudRegionId"); - - - vnfcParams.put("relationship-list.relationship[1].related-to","generic-vnf"); - vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-key","generic-vnf.vnf-id"); - vnfcParams.put("relationship-list.relationship[1].relationship-data[0].relationship-value","ibcx000000"); - - - vnfcParams.put("relationship-list.relationship[2].related-to","vf-module"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-key","generic-vnf.vnf-id"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[0].relationship-value","ibcx000000"); - - - vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-key","vf-module.vf-module-id"); - vnfcParams.put("relationship-list.relationship[2].relationship-data[1].relationship-value","vfModuleId"); - - return vnfcParams; - } - public void populateVnfcContext(SvcLogicContext ctx, String prefix) { - log.info("In populateVnfcContext " + prefix); - - ctx.setAttribute(prefix + ".vnfc-type", "vnfctype1"); - ctx.setAttribute(prefix + ".vnfc-function-code", "funccode1"); - ctx.setAttribute(prefix + ".group-notation", "grpnot1"); - } - - public void populateVmContext(SvcLogicContext ctx, String prefix) { - log.info("In populateVmContext " + prefix); - - ctx.setAttribute(prefix + ".vserver-name", "ibcx0000000"); - - - ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); - - // Junk - ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "test"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "1"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vnfc.vnfc-name"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "test"); - - - - // VNFC - ctx.setAttribute(prefix + ".relationship-list.relationship[1].related-to", "vnfc"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data_length", "1"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-key", "vnfc.vnfc-name"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-value", "ibcx0001vm001vnfc1"); - - - // VFModule - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].related-to", "vf-module"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data_length", "1"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-key", "vf-module.vf-module-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-value", "vfModule1"); - - - } - - public void populateGenericVnfContext(SvcLogicContext ctx, String prefix) throws Exception { - - log.info("In populateGenericVnf " + prefix); - ctx.setAttribute(prefix + ".vnf-name", "ibvcx0001"); - ctx.setAttribute(prefix + ".vnf-type", "vUSP-Metaswitch"); - - ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); - - /* // VM1 - ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "vserver"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "4"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vserver.vserver-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "ibcx001vm001-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-key", "tenant.tenant-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-value", "sometenant"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-value", "testcloudregionid"); - - - //ctx.setAttribute(prefix + ".relationship-list.relationship_length", "3"); -*/ - // VM1 - ctx.setAttribute(prefix + ".relationship-list.relationship[0].related-to", "vserver"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data_length", "4"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-key", "vserver.vserver-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[0].relationship-value", "ibcx001vm001-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-key", "tenant.tenant-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[1].relationship-value", "sometenant"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[3].relationship-value", "testcloudregionid"); - - - // VM2 - ctx.setAttribute(prefix + ".relationship-list.relationship[1].related-to", "vserver"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data_length", "4"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-key", "vserver.vserver-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[0].relationship-value", "ibcx000000"); - - - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[1].relationship-key", "tenant.tenant-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[1].relationship-value", "sometenant"); - - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[2].relationship-key", "cloud-region.cloud-owner"); - ctx.setAttribute(prefix + ".relationship-list.relationship[0].relationship-data[2].relationship-value", "ATTAIC"); - - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[3].relationship-key", "cloud-region.cloud-region-id"); - ctx.setAttribute(prefix + ".relationship-list.relationship[1].relationship-data[3].relationship-value", "testcloudregionid"); - - - // Unrelated - ctx.setAttribute(prefix + ".relationship-list.relationship[2].related-to", "junk"); - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data_length", "4"); - - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-key", "test"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[0].relationship-value", "ibcx000000"); - - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[1].relationship-key", "test1"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[1].relationship-value", "sometenant"); - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[2].relationship-key", "test2"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[2].relationship-value", "ATTAIC"); - - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[3].relationship-key", "test3"); - ctx.setAttribute(prefix + ".relationship-list.relationship[2].relationship-data[3].relationship-value", "testcloudregionid"); - } - - - - public void populateFirstVnfcData(SvcLogicContext ctx, String prefix) throws Exception { - - - - ctx.setAttribute(prefix + "vnf.vm-count", "4"); - - ctx.setAttribute(prefix+ "vm[0].vnfc-type", "mmc"); - ctx.setAttribute(prefix+ "vm[0].vnfc-name", "vnfcname1"); - - ctx.setAttribute(prefix+ "vm[1].vnfc-type", "mmc"); - ctx.setAttribute(prefix+ "vm[1].vnfc-name", "vnfcname2"); - - ctx.setAttribute(prefix+ "vm[2].vnfc-type", "ssc"); - ctx.setAttribute(prefix+ "vm[2].vnfc-name", "vnfcname3"); - - ctx.setAttribute(prefix+ "vm[3].vnfc-type", "ssc"); - ctx.setAttribute(prefix+ "vm[3].vnfc-name", "vnfcname4"); - } - - - - public void populateGroupNotation(SvcLogicContext ctx, String prefix) throws Exception { - - - - ctx.setAttribute(prefix + "vnf.vm-count", "5"); - - ctx.setAttribute(prefix+ "vm[0].vserver-name", "ibcxvm0001"); - ctx.setAttribute(prefix+ "vm[0].group-notation", "grpNot1"); - - ctx.setAttribute(prefix+ "vm[1].vserver-name", "ibcxvm0002"); - ctx.setAttribute(prefix+ "vm[1].group-notation", "grpNot2"); - - - ctx.setAttribute(prefix+ "vm[2].vserver-name", "ibcxvm0003"); - ctx.setAttribute(prefix+ "vm[2].group-notation", "grpNot3"); - - ctx.setAttribute(prefix+ "vm[3].vserver-name", "ibcxvm0004"); - ctx.setAttribute(prefix+ "vm[3].group-notation", "4"); - - ctx.setAttribute(prefix+ "vm[4].vserver-name", "ibcxvm0005"); - ctx.setAttribute(prefix+ "vm[4].group-notation", "4"); - } - - - public void populateVnfcRef(SvcLogicContext ctx) throws Exception { - - for (int i = 0; i < 2; i++ ) { - - String vnfcRefKey = "vnfcReference[" + i+ "]."; - - - - ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); - ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); - - - //if ( i == 0 || i == 1 ) { - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "2"); - //} - - ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "ssc"+i ); - - ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "func" +i); - - ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); - } - - } - - public void populateAllVnfInfo(SvcLogicContext ctx, String prefix) throws Exception { - - ctx.setAttribute("vnf-id", "ibcx000000"); - - ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); - ctx.setAttribute(prefix + ".vnf.vm-count", "2"); - - - - - ctx.setAttribute(prefix+ ".vm[0].vserver-name", "ibcxvm0000"); - ctx.setAttribute(prefix+ ".vm[0].vnfc-name", "VNFCNAME"); - - ctx.setAttribute(prefix+ ".vm[0].vserver-id", "ibcxvm0001id"); - ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid"); - ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner"); - ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId"); - - ctx.setAttribute(prefix+ ".vm[0].vf-module-id", "vfModuleId"); - - - - ctx.setAttribute(prefix+ ".vm[1].vserver-name", "ibcxvm0002"); - - ctx.setAttribute(prefix+ ".vm[1].vserver-id", "ibcx00000"); - ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantId"); - ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner"); - ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId"); - - ctx.setAttribute(prefix+ ".vm[1].vf-module-id", "vfModuleId"); - - - //ctx.setAttribute(prefix+ ".vm[1].vserver-name", "ibcxvm0002"); - - - - - } - - - - public void populateAllVnfInfo1(SvcLogicContext ctx, String prefix) throws Exception { - - ctx.setAttribute("vnf-id", "dbjx0001v"); - - ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); - ctx.setAttribute(prefix + ".vnf.vm-count", "2"); - - - - - ctx.setAttribute(prefix+ ".vm[0].vserver-name", "dbjx0001vm001"); - - - ctx.setAttribute(prefix+ ".vm[0].vserver-id", "dbjx0001vm0001id"); - ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid1"); - ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner1"); - ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId1"); - - ctx.setAttribute(prefix+ ".vm[0].vf-module-id", "vfModuleId1"); - - - - ctx.setAttribute(prefix+ ".vm[1].vserver-name", "dbjx0001vm002"); - - ctx.setAttribute(prefix+ ".vm[1].vserver-id", "dbjx0001vm0002id"); - ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantId2"); - ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner2"); - ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId2"); - - ctx.setAttribute(prefix+ ".vm[1].vf-module-id", "vfModuleId2"); - - - - } - - public void populateVnfcRefFirstVnfcName(SvcLogicContext ctx) throws Exception { - - - for (int i = 0; i < 2; i++ ) { - - String vnfcRefKey = "vnfcReference[" + i+ "]."; - - - - ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); - ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); - - - - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "first-vnfc-name"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "pair"); - - - ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "vDBE-I? - DBJX" ); - - ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); - - ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); - } - - } - - public void populateVnfcRefRelValueSame(SvcLogicContext ctx) throws Exception { - - - for (int i = 0; i < 2; i++ ) { - - String vnfcRefKey = "vnfcReference[" + i+ "]."; - - - - ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); - ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); - - - - if ( i == 0 ) { - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "1"); - } - else { - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "relative-value"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "same"); - } - - - - ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "v-I? - DBJX" ); - - ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); - - ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); - } - - } - - - public void populateVnfcRefRelValueNext(SvcLogicContext ctx) throws Exception { - - - for (int i = 0; i < 2; i++ ) { - - String vnfcRefKey = "vnfcReference[" + i+ "]."; - - - - ctx.setAttribute(vnfcRefKey+ "VM-INSTANCE", String.valueOf(i)); - ctx.setAttribute(vnfcRefKey+ "VNFC-INSTANCE", "1"); - - - - if ( i == 0 ) { - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "fixed-value"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "1"); - } - else { - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-TYPE", "relative-value"); - ctx.setAttribute(vnfcRefKey+ "GROUP-NOTATION-VALUE", "next"); - } - - - - ctx.setAttribute(vnfcRefKey+ "VNFC-TYPE", "v-I? - DBJX" ); - - ctx.setAttribute(vnfcRefKey+ "VNFC-FUNCTION-CODE", "dbj"); - - ctx.setAttribute(vnfcRefKey+ "IPADDRESS-V4-OAM-VIP", "Y"); - } - - } - -} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/TestAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/TestAaiService.java deleted file mode 100644 index aa807087f..000000000 --- a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/aai/TestAaiService.java +++ /dev/null @@ -1,351 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client.aai; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TestAaiService { - // ONAP merging - - private static final EELFLogger log = EELFManager.getInstance().getLogger(TestAaiService.class); - private AAIClient aaiClient; - - @Test - public void testGetGenericVnfInfo() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - inParams.put("vnfId", "ibcxvm0000"); - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.getGenericVnfInfo(inParams, ctx); - - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vnf-type"), "vUSP-Metaswitch"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm-count"), "2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "ibcx001vm001-id"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-id"), "ibcx000000"); - } - - @Test - public void testGetVmInfo() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - inParams.put("vserverId", "vserverId1"); - inParams.put("tenantId", "tenantId1"); - inParams.put("cloudOwner", "cloudOwner1"); - inParams.put("cloudRegionId", "cloudRegionId1"); - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.getVMInfo(inParams, ctx); - - printContext(ctx); - - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vserver-name"), "ibcx0000000"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vnfc-count"), "1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vf-module-id"), "vfModule1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm.vnfc[0].vnfc-name"), "ibcx0001vm001vnfc1"); - - } - - @Test - public void testGetVnfcInfo() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - inParams.put("vnfcName", "vnfcName1"); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.getVnfcInfo(inParams, ctx); - - printContext(ctx); - - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.vnfc-type"), null); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.vnfc-function-code"), null); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnfc.group-notation"), "grpnot1"); - - } - - @Test - public void testGetFirstVnfcNameForVnfcType() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - String prefix = "tmp.vnfInfo."; - - SvcLogicContext ctx = new SvcLogicContext(); // VNFC with specified vnfc - // type found - mockAai.populateFirstVnfcData(ctx, prefix); - String firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "ssc"); - assertEquals(firstVnfcName, "vnfcname3"); - - ctx = new SvcLogicContext(); // no VMS found - firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "ssc"); - assertEquals(firstVnfcName, null); - - ctx = new SvcLogicContext(); // no VMS found with specified type - mockAai.populateFirstVnfcData(ctx, prefix); - firstVnfcName = mockAai.getFirstVnfcNameForVnfcType(ctx, prefix, "test"); - assertEquals(firstVnfcName, null); - - } - - @Test - public void testGroupNotation() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - String prefix = "tmp.vnfInfo."; - - SvcLogicContext ctx = new SvcLogicContext(); - mockAai.populateGroupNotation(ctx, prefix); - - // printContext(ctx); - String grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "ibcxvm0002"); - assertEquals(grpNotation, "grpNot2"); - - ctx = new SvcLogicContext(); // no VMS found - grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "ibcxvm0002"); - assertEquals(grpNotation, null); - - ctx = new SvcLogicContext(); // no VMS found with specified name - mockAai.populateGroupNotation(ctx, prefix); - grpNotation = mockAai.getGroupNotationForVServer(ctx, prefix, "test"); - assertEquals(grpNotation, null); - - } - - @Test - public void testGetGroupNotation() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - String prefix = "tmp.vnfInfo."; - - SvcLogicContext ctx = new SvcLogicContext(); - - String grpNotation = mockAai.getGroupNotation("fixed-value", "2", null, null, null, null, null); - assertEquals(grpNotation, "2"); - - mockAai.populateFirstVnfcData(ctx, prefix); // Existing VNFC Found - grpNotation = mockAai.getGroupNotation("first-vnfc-name", "2", "currentVnfcName", "currentVServerName", prefix, - ctx, "ssc"); - assertEquals(grpNotation, "vnfcname32"); - - ctx = new SvcLogicContext(); // no vnfcs exist in A&AI- Use current - // vnfcName - grpNotation = mockAai.getGroupNotation("first-vnfc-name", "2", "currentVnfcName", "currentVServerName", prefix, - ctx, "ssc"); - assertEquals(grpNotation, "currentVnfcName2"); - - ctx = new SvcLogicContext(); - mockAai.populateGroupNotation(ctx, prefix); - grpNotation = mockAai.getGroupNotation("relative-value", "same", "currentVnfcName", "ibcxvm0003", prefix, ctx, - "ssc"); - assertEquals(grpNotation, "grpNot2"); - - ctx = new SvcLogicContext(); - mockAai.populateGroupNotation(ctx, prefix); - grpNotation = mockAai.getGroupNotation("relative-value", "next", "currentVnfcName", "ibcxvm0006", prefix, ctx, - "ssc"); - assertEquals(grpNotation, "5"); - - ctx = new SvcLogicContext(); - mockAai.populateGroupNotation(ctx, prefix); - grpNotation = mockAai.getGroupNotation("relative-value", "next", "currentVnfcName", "ibcxvm0003", prefix, ctx, - "ssc"); - assertEquals(grpNotation, null); // Null if grpNotation is not numeric - - } - - @Test - public void testInsertVnfcs() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateVnfcRef(ctx); - - mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); - - // mockAai.insertVnfcs(inParams,ctx,2, 2) ; - } - - @Test - public void testUpdateVServerStatus() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); - - mockAai.updateVServerStatus(inParams, ctx, 2); - } - - @Test - public void testInsertVnfcsForFirstVnfc() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateVnfcRefFirstVnfcName(ctx); - - mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); - - mockAai.insertVnfcs(inParams, ctx, 2, 2); - - - } - @Test - public void testInsertVnfcsForRelativeValueSame() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateVnfcRefRelValueSame(ctx); - - mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); - - mockAai.insertVnfcs(inParams, ctx, 2, 2); - - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name"), "dbjx0001vm001dbj001"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-function-code"), "dbj"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-type"), "v-I? - DBJX"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].group-notation"), "1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "dbjx0001vm002dbj001"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "dbj"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "v-I? - DBJX"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "1"); - } - - @Test - public void testInsertVnfcsForRelativeValueNext() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateVnfcRefRelValueNext(ctx); - - mockAai.populateAllVnfInfo1(ctx, "tmp.vnfInfo"); - - mockAai.insertVnfcs(inParams, ctx, 2, 2); - - - - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name"), "dbjx0001vm001dbj001"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-function-code"), "dbj"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-type"), "v-I? - DBJX"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].group-notation"), "1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "dbjx0001vm002dbj001"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "dbj"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "v-I? - DBJX"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "2"); - } - - @Test - public void testUpdateVnfStatus() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - - Map inParams = new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - - SvcLogicContext ctx = new SvcLogicContext(); - - mockAai.populateAllVnfInfo(ctx, "tmp.vnfInfo"); - - mockAai.updateVnfStatus(inParams, ctx); - } - - @Test - public void testReadResource() throws Exception { - - MockAaiService mockAai = new MockAaiService(aaiClient); - // AaiService mockAai = new AaiService(new AAIClientMock()); - - String vnfId = "ibcx0001v"; - String resourceKey = "generic-vnf.vnf-id = '" + vnfId + "'"; - String resourceType = "generic-vnf"; - String queryPrefix = "vnfInfo"; - SvcLogicContext ctx = mockAai.readResource(resourceKey, queryPrefix, resourceType); - - // System.out.println("VNF TYPE " + queryPrefix + ".vnf.vnf-type"); - - assertEquals(ctx.getAttribute("vnfInfo.vnf-type"), "vUSP-Metaswitch"); - - } - private void printContext(SvcLogicContext ctx) throws Exception { - for (String key : ctx.getAttributeKeySet()) { - log.info(" KEY " + key); - log.info(" VALUE " + ctx.getAttribute(key)); - } - } -} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/MockAaiService.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/MockAaiService.java deleted file mode 100644 index 2e03e6b5a..000000000 --- a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/MockAaiService.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.aai.client.node; -import static junit.framework.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.aai.client.AppcAaiClientConstant; -//import org.onap.appc.aai.client.aai.AAIClientMock; -import org.onap.appc.aai.client.aai.AaiService; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; - -public class MockAaiService extends AaiService { - - // ONAP merging - private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAaiService.class); - private AAIClient aaiClient; - - /*public MockAaiService() { - super(new AAIClientMock()); - }*/ - - - public MockAaiService(AAIClient aaic) { - super(aaic); - } - - public void getVMInfo(Map params,SvcLogicContext ctx ) throws Exception { - log.info("Received Mock getVmInfo call with params : " + params); - String vserverId = params.get("vserverId"); - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - if ( vserverId.equals("ibcm0001id")) { - ctx.setAttribute(prefix + ".vm.vserver-name", "vserverName1"); - ctx.setAttribute(prefix + ".vm.vf-module-id", "vfModule1"); - } - else { - ctx.setAttribute(prefix + ".vm.vserver-name", "vserverName2"); - ctx.setAttribute(prefix + ".vm.vf-module-id", "vfModule2"); - ctx.setAttribute(prefix + ".vm.vnfc[0].vnfc-name", "vnfcName2"); - } - - } - - - public void getVnfcInfo(Map params,SvcLogicContext ctx ) throws Exception { - log.info("Received Mock getVmInfo call with params : " + params); - String prefix = params.get(AppcAaiClientConstant.INPUT_PARAM_RESPONSE_PREFIX); - - String vnfcName = params.get("vnfcName"); - - if ( vnfcName.equals("vnfcName2") ) { - ctx.setAttribute(prefix + ".vnfc.vnfc-type", "vnfcType2"); - ctx.setAttribute(prefix + ".vnfc.vnfc-function-code", "vnfcFuncCode2"); - ctx.setAttribute(prefix + ".vnfc.group-notation", "vnfcGrpNot2"); - } - - - } -} diff --git a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/TestAAIResourceNode.java b/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/TestAAIResourceNode.java deleted file mode 100644 index 6b05c08bb..000000000 --- a/appc-outbound/appc-aai-client/provider/src/test/java/org/openecomp/appc/aai/client/node/TestAAIResourceNode.java +++ /dev/null @@ -1,238 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.aai.client.node; - -import static org.junit.Assert.*; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.aai.client.AppcAaiClientConstant; -import org.onap.appc.aai.client.aai.AaiService; -import org.onap.appc.aai.client.aai.TestAaiService; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; - -import com.fasterxml.jackson.databind.ObjectMapper; - - -public class TestAAIResourceNode { - - //Removed for ONAP integration - - private static final EELFLogger log = EELFManager.getInstance().getLogger(TestAAIResourceNode.class); - - @Test - public void sortVServer() throws Exception{ - - //log.info("Test"); - - ArrayList> vservers = new ArrayList>(); - HashMap vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId9"); - vserverMap.put("tenant-id", "tenantId9"); - vserverMap.put("cloud-owner", "cloudOwner9"); - vserverMap.put("cloud-region-id", "cloudRegionId9"); - vserverMap.put("vserver-name", "vServerName9"); - vservers.add(vserverMap); - vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId1"); - vserverMap.put("tenant-id", "tenantId1"); - vserverMap.put("cloud-owner", "cloudOwner1"); - vserverMap.put("cloud-region-id", "cloudRegionId1"); - vserverMap.put("vserver-name", "vServerName1"); - vservers.add(vserverMap); - vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId3"); - vserverMap.put("tenant-id", "tenantId3"); - vserverMap.put("cloud-owner", "cloudOwner3"); - vserverMap.put("cloud-region-id", "cloudRegionId3"); - vserverMap.put("vserver-name", "vServerName3"); - vservers.add(vserverMap); - Collections.sort(vservers, new Comparator>() { - @Override - public int compare(Map o1, Map o2) { - return o1.get("vserver-name").compareTo(o2.get("vserver-name")); - } - }); - - SvcLogicContext ctx = new SvcLogicContext(); - AAIResourceNode aai = new AAIResourceNode(); - aai.populateContext(vservers, ctx, "vserver."); - log.info(ctx.getAttribute("vserver.vm[0].vserver-name")); - } - - @Test - public void testAllVServer() throws Exception{ - - MockAAIResourceNode mrn = new MockAAIResourceNode(); - SvcLogicContext ctx = new SvcLogicContext(); - populateAllVServerInfo(ctx, "tmp.vnfInfo"); - Map inParams =new HashMap(); - inParams.put("responsePrefix", "tmp.vnfInfo"); - mrn.getAllVServersVnfcsInfo(inParams, ctx); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm-count"), "2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vm-count"), "2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vnf.vm-with-no-vnfcs-count"), "0"); - // VM1 - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "ibcsm0002id"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].tenant-id"), "tenantid2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-owner"), "cloudOwner2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-region-id"), "cloudRegionId2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-name"), "vserverName2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vf-module-id"), "vfModule2"); - //assertNull(ctx.getAttribute("tmp.vnfInfo.vm[0].vnfc-name")); - - // VM2 - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-id"), "ibcxvm0001id"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].tenant-id"), "tenantid1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].cloud-owner"), "cloudOwner1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].cloud-region-id"), "cloudRegionId1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vserver-name"), "vserverName2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vf-module-id"), "vfModule2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-name"), "vnfcName2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-type"), "vnfcType2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].vnfc-function-code"), "vnfcFuncCode2"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[1].group-notation"), "vnfcGrpNot2"); - } - public void populateAllVServerInfo(SvcLogicContext ctx, String prefix) throws Exception { - ctx.setAttribute("vnf-id", "ibcx0001v"); - ctx.setAttribute("vnf-host-ip-address", "000.00.00.00"); - ctx.setAttribute(prefix + ".vm-count", "2"); - ctx.setAttribute(prefix+ ".vm[0].vserver-id", "ibcsm0002id"); - ctx.setAttribute(prefix+ ".vm[0].tenant-id", "tenantid2"); - ctx.setAttribute(prefix+ ".vm[0].cloud-owner", "cloudOwner2"); - ctx.setAttribute(prefix+ ".vm[0].cloud-region-id", "cloudRegionId2"); - ctx.setAttribute(prefix+ ".vm[1].vserver-id", "ibcxvm0001id"); - ctx.setAttribute(prefix+ ".vm[1].tenant-id", "tenantid1"); - ctx.setAttribute(prefix+ ".vm[1].cloud-owner", "cloudOwner1"); - ctx.setAttribute(prefix+ ".vm[1].cloud-region-id", "cloudRegionId1"); - - } - - public static class MockAAIResourceNode extends AAIResourceNode { - private static final EELFLogger log = EELFManager.getInstance().getLogger(MockAAIResourceNode.class); - private AAIClient aaiClient; - - public AaiService getAaiService() { - log.info("In MockAAI"); - return new MockAaiService(aaiClient); - } - } - - @Test - public void testPopulateContext() throws Exception{ - - ArrayList> vservers = new ArrayList>(); - HashMap vserverMap = new HashMap(); - vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId1"); - vserverMap.put("tenant-id", "tenantId1"); - vserverMap.put("cloud-owner", "cloudOwner1"); - vserverMap.put("cloud-region-id", "cloudRegionId1"); - vserverMap.put("vserver-name", "vServerName1"); - vserverMap.put("vnfc-name", "vnfcName1"); - vservers.add(vserverMap); - vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId3"); - vserverMap.put("tenant-id", "tenantId3"); - vserverMap.put("cloud-owner", "cloudOwner3"); - vserverMap.put("cloud-region-id", "cloudRegionId3"); - vserverMap.put("vserver-name", "vServerName3"); - vservers.add(vserverMap); - vserverMap = new HashMap(); - vserverMap.put("vserver-id", "vserverId9"); - vserverMap.put("tenant-id", "tenantId9"); - vserverMap.put("cloud-owner", "cloudOwner9"); - vserverMap.put("cloud-region-id", "cloudRegionId9"); - vserverMap.put("vserver-name", "vServerName9"); - vservers.add(vserverMap); - SvcLogicContext ctx = new SvcLogicContext(); - AAIResourceNode aai = new AAIResourceNode(); - aai.populateContext(vservers, ctx, "tmp.vnfInfo."); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-name"), "vServerName1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].tenant-id"), "tenantId1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-owner"), "cloudOwner1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].cloud-region-id"), "cloudRegionId1"); - assertEquals(ctx.getAttribute("tmp.vnfInfo.vm[0].vserver-id"), "vserverId1"); - assertEquals(ctx.getAttribute("vm-name"), "vServerName3"); - } - - @Test - public final void testGetVnfInfo() { - SvcLogicContext ctx = new SvcLogicContext(); - AAIResourceNode aai = new AAIResourceNode(); -Map inParams =new HashMap(); - inParams.put("responsePrefix", "tmp.vnfInfo"); - try { - aai.getVnfInfo(inParams, ctx); - } catch (SvcLogicException e) { - e.printStackTrace(); - } - - } - @Test - public final void testaddVnfcs() - { - SvcLogicContext ctx = new SvcLogicContext(); - AAIResourceNode aai = new AAIResourceNode(); -Map inParams =new HashMap(); - inParams.put("responsePrefix", "tmp.vnfInfo"); - try { - aai.addVnfcs(inParams, ctx); - } catch (SvcLogicException e) { - e.printStackTrace(); - } - - } - @Test - public final void testupdateVnfAndVServerStatus(){ - SvcLogicContext ctx = new SvcLogicContext(); - AAIResourceNode aai = new AAIResourceNode(); -Map inParams =new HashMap(); - - inParams.put("responsePrefix", "tmp.vnfInfo"); - try { - aai.updateVnfAndVServerStatus(inParams, ctx); - } catch (SvcLogicException e) { - e.printStackTrace(); - } - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/InstarClientActivator.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/InstarClientActivator.java new file mode 100644 index 000000000..09021daa4 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/InstarClientActivator.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.appc.instar.node.InstarClientNode; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class InstarClientActivator implements BundleActivator{ + + private List registrations = new LinkedList(); + private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarClientActivator.class); + + @Override + public void start(BundleContext ctx) throws Exception + { + + InstarClientNode instarClientNode = new InstarClientNode(); + log.info("Registering service "+ instarClientNode.getClass().getName()); + registrations.add(ctx.registerService(instarClientNode.getClass().getName(), instarClientNode, null)); + log.info("Registering service sccessful for "+ instarClientNode.getClass().getName()); + + } + @Override + public void stop(BundleContext arg0) throws Exception + { + for (ServiceRegistration registration: registrations) + { + registration.unregister(); + registration = null; + } + + } + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/Dme2Client.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/Dme2Client.java new file mode 100644 index 000000000..fa22a751f --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/Dme2Client.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.dme2client; +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Properties; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.io.IOUtils; +import org.onap.appc.instar.utils.InstarClientConstant; + + +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 com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; + + +public class Dme2Client { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(Dme2Client.class); + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + //DME2Client client = null; + Properties props = new Properties(); + String operationName ; + String appendContext; + + public Dme2Client(String optName, String subCtxt, HashMap data) throws Exception{ + log.info("Setting Properties for DME2 Client for INSTAR connection"); + this.operationName=optName; + this.appendContext = data.get(subCtxt); + String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); + if (propDir == null) + throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); + String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES; + InputStream propStream = new FileInputStream(propFile); + try + { + props.load(propStream); + } + catch (Exception e) + { + throw new Exception("Could not load properties file " + propFile, e); + } + finally + { + try + { + propStream.close(); + } + catch (Exception e) + { + log.warn("Could not close FileInputStream", e); + } + } + } + + public ClientResponse sendtoInstar() throws Exception { + + log.info("Called Send with operation Name=" + this.operationName + "and = " + props.getProperty(operationName+InstarClientConstant.BASE_URL)); + String resourceUri = props.getProperty(operationName+InstarClientConstant.BASE_URL)+ + props.getProperty(operationName + InstarClientConstant.URL_SUFFIX) + + props.getProperty(operationName + InstarClientConstant.SUB_CONTEXT)+ appendContext ; + + log.info("DME Endpoint URI:" + resourceUri); + Client client = null; + WebResource webResource = null; + ClientResponse clientResponse = null; + String authorization = props.getProperty("authorization"); + String requestDataType = "application/json"; + String responseDataType= MediaType.APPLICATION_JSON; + String methodType = props.getProperty("getIpAddressByVnf_method"); + String request = ""; + String userId=props.getProperty("MechID"); + String password=props.getProperty("MechPass"); + + log.info("authorization = " + authorization + "methodType= " + methodType); + try{ + DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); + System.setProperty("jsse.enableSNIExtension", "false"); + SSLContext sslContext = null; + SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); + sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); + defaultClientConfig.getProperties().put( + com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, + new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); + client = Client.create(defaultClientConfig); + client.addFilter(new HTTPBasicAuthFilter(userId, password)); + + webResource = client.resource(new URI(resourceUri)); + webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); + + if(HttpMethod.GET.equalsIgnoreCase(methodType)){ + clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); + }else if(HttpMethod.POST.equalsIgnoreCase(methodType)){ + clientResponse = webResource.type(requestDataType).post(ClientResponse.class, request); + }else if(HttpMethod.PUT.equalsIgnoreCase(methodType)){ + clientResponse = webResource.type(requestDataType).put(ClientResponse.class,request); + }else if(HttpMethod.DELETE.equalsIgnoreCase(methodType)){ + clientResponse = webResource.delete(ClientResponse.class); + } + + return clientResponse; + + }catch (Exception e) { + log.info("failed in RESTCONT Action ("+methodType+") for the resource " + resourceUri + ", falut message :"+e.getMessage()); + throw new Exception("Error While gettting Data from INSTAR" + e.getMessage()); + } + finally { + // clean up. + webResource = null; + if(client != null){ + client.destroy(); + client = null; + } + } + + + } + + public String send() { + String response = null; + try{ + + if(props !=null && + props.getProperty(InstarClientConstant.MOCK_INSTAR) != null && + props.getProperty(InstarClientConstant.MOCK_INSTAR).equalsIgnoreCase("true")) + return IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"), Charset.defaultCharset()); + + ClientResponse clientResponse = sendtoInstar(); + if(clientResponse != null){ + response = clientResponse.getEntity(String.class); + log.info(clientResponse.getStatus() + " Status, Response :" + response); + + } + } catch (Exception t) { + log.error("Error in Dme2Client for send() method while sending response:" ,t); + } + return response; + } + + private HostnameVerifier getHostnameVerifier() { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { + return true; + } + }; + } + + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/SecureRestClientTrustManager.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/SecureRestClientTrustManager.java new file mode 100644 index 000000000..86c2d99b3 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/dme2client/SecureRestClientTrustManager.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.dme2client; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.X509TrustManager; + + +public class SecureRestClientTrustManager implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public boolean isClientTrusted(X509Certificate[] arg0) { + return true; + } + + public boolean isServerTrusted(X509Certificate[] arg0) { + return true; + } + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java new file mode 100644 index 000000000..08df6f02e --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.appc.instar.interfaces.ResponseHandlerInterface; +import org.onap.appc.instar.utils.InstarClientConstant; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class InstarResponseHandlerImpl implements ResponseHandlerInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarResponseHandlerImpl.class); + + ResponseKey resKey = null; + SvcLogicContext ctxt = null; + + public InstarResponseHandlerImpl(ResponseKey filterKeys, SvcLogicContext context) { + this.resKey = filterKeys; + this.ctxt = context; + + } + + @Override + public Object processResponse(String instarResponse, String instarKey) { + String fn = " InstarResponseHandlerImpl.processResponse "; + log.info(fn + " Instar Response :" + instarResponse); + + JSONObject instarKeyValues; + + log.info("Instar Data in Context : "+ ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); + if(ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES) != null){ + instarKeyValues = new JSONObject(ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); + log.info("Instar data already exsits : " + instarKeyValues.toString()); + } + else + instarKeyValues = new JSONObject(); + JSONArray instarResponses = new JSONObject(instarResponse).getJSONArray(InstarClientConstant.INSTAR_RESPONSE_BLOCK_NAME); + for (int i = 0; i < instarResponses.length(); i++){ + JSONObject res = instarResponses.getJSONObject(i); + log.info(fn + "Instar Block :" + i + " Values :" + res.toString()); + log.info(fn + "Appc Filter Key :" + ctxt.getAttribute(InstarClientConstant.VNF_NAME) + resKey.getUniqueKeyValue()); + + if(res.getString(InstarClientConstant.FDQN) != null && + res.getString(InstarClientConstant.FDQN).equalsIgnoreCase(ctxt.getAttribute(InstarClientConstant.VNF_NAME) + resKey.getUniqueKeyValue())){ + if(resKey.getFieldKeyName().equals(InstarClientConstant.V4_ADDRESS)) + instarKeyValues.put(instarKey, res.getString(InstarClientConstant.INSTAR_V4_ADDRESS)); + else if(resKey.getFieldKeyName().equals(InstarClientConstant.V6_ADDRESS)) + instarKeyValues.put(instarKey, res.getString(InstarClientConstant.INSTAR_V6_ADDRESS)); + break; + } + } + log.info(fn + "Instar KeyValues :" + instarKeyValues); + ctxt.setAttribute(InstarClientConstant.INSTAR_KEY_VALUES, instarKeyValues.toString()); + + + return instarKeyValues; + } + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarRestClientImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarRestClientImpl.java new file mode 100644 index 000000000..db43d9c41 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InstarRestClientImpl.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.HashMap; + +import org.apache.commons.io.IOUtils; +import org.onap.appc.instar.dme2client.Dme2Client; +import org.onap.appc.instar.interfaces.RestClientInterface; +import org.onap.appc.instar.utils.InstarClientConstant; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class InstarRestClientImpl implements RestClientInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarRestClientImpl.class); + HashMap requestData = null; + Dme2Client dme2Client; + + public InstarRestClientImpl(HashMap instarRequestData) { + + this.requestData = instarRequestData; + } + + @Override + public String sendRequest(String operation) throws Exception { + + String instarResponse = null; + try { + if(operation !=null && operation.equalsIgnoreCase(InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME)){ + dme2Client = new Dme2Client(operation, InstarClientConstant.VNF_NAME, requestData); + } + instarResponse = dme2Client.send(); + log.info("Resposne in InstarRestClientImpl = " + instarResponse); + if(instarResponse == null || instarResponse.length() < 0) + throw new Exception ("No Data received from Instar for this call " + operation); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + return instarResponse; + } + + + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java new file mode 100644 index 000000000..cc2eeaa07 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import java.util.HashMap; +import java.util.List; + +import org.onap.appc.instar.interfaces.ResponseHandlerInterface; +import org.onap.appc.instar.interfaces.RestClientInterface; +import org.onap.appc.instar.interfaces.RuleHandlerInterface; +import org.onap.appc.instar.node.InstarClientNode; +import org.onap.appc.instar.utils.InstarClientConstant; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class InterfaceIpAddressImpl implements RuleHandlerInterface { + + private static final EELFLogger log = EELFManager.getInstance().getLogger(InterfaceIpAddressImpl.class); + private Parameter parameters; + private SvcLogicContext context; + + public InterfaceIpAddressImpl(Parameter params, SvcLogicContext ctx) { + this.parameters = params; + this.context = ctx; + } + + @Override + public void processRule() throws Exception { + + String fn = "InterfaceIpAddressHandler.processRule"; + log.info(fn + "Processing rule :" + parameters.getRuleType()); + String operationName ; + + RestClientInterface restClient = null; + ResponseHandlerInterface responseHandler = null; + + List responseKeyList = parameters.getResponseKeys(); + if(responseKeyList != null && responseKeyList.size() > 0){ + for(ResponseKey filterKeys : responseKeyList){ + //response.setUniqueKeyValue(response.getUniqueKeyValue()+ context.getAttribute(InstarClientConstant.VNF_NAME)); + switch(parameters.getSource()){ + case InstarClientConstant.SOURCE_SYSTEM_INSTAR: + restClient = new InstarRestClientImpl(createInstarRequestData(context)); + responseHandler = new InstarResponseHandlerImpl(filterKeys, context ); + operationName = "getIpAddressByVnf"; + break; + default: + throw new Exception("No Client registered for : " + parameters.getSource()); + + } + responseHandler.processResponse(restClient.sendRequest(operationName),parameters.getName() ); + } + } + else + { + throw new Exception("NO response Keys set for : " + parameters.getRuleType()); + } + } + + private HashMap createInstarRequestData(SvcLogicContext ctxt) { + HashMap requestParams = new HashMap(); + requestParams.put(InstarClientConstant.VNF_NAME, ctxt.getAttribute(InstarClientConstant.VNF_NAME)); + return requestParams; + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/ResponseHandlerInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/ResponseHandlerInterface.java new file mode 100644 index 000000000..8211967b0 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/ResponseHandlerInterface.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaces; + +public interface ResponseHandlerInterface { + + public Object processResponse(String response, String instarKey); + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RestClientInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RestClientInterface.java new file mode 100644 index 000000000..bf6c5b34d --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RestClientInterface.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaces; + +public interface RestClientInterface { + + + public String sendRequest(String operation) throws Exception; + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RuleHandlerInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RuleHandlerInterface.java new file mode 100644 index 000000000..86f31d2fa --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/interfaces/RuleHandlerInterface.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaces; + + +public interface RuleHandlerInterface { + + public void processRule() throws Exception; + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/node/InstarClientNode.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/node/InstarClientNode.java new file mode 100644 index 000000000..1d343c668 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/node/InstarClientNode.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.node; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.instar.interfaceImpl.InstarRestClientImpl; +import org.onap.appc.instar.interfaceImpl.InterfaceIpAddressImpl; +import org.onap.appc.instar.interfaces.RestClientInterface; +import org.onap.appc.instar.interfaces.RuleHandlerInterface; +import org.onap.appc.instar.utils.InstarClientConstant; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public class InstarClientNode implements SvcLogicJavaPlugin +{ + private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarClientNode.class); + + public void getInstarInfo(Map inParams, SvcLogicContext ctx) + throws SvcLogicException{ + log.info("Received getInstarInfo call with params : " + inParams); + String responsePrefix = (String)inParams.get(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try + { + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? responsePrefix + "." : ""; + String [] instarKeys = getInstarKeys(inParams.get(InstarClientConstant.INSTAR_KEYS)); + for (String instarKey : instarKeys){ + log.info("Processing Key : " + instarKey); + log.info("Searching key for : " + "INSTAR." + instarKey); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + RuleHandlerInterface handler = null; + log.info("Received Context : " + ctx.getAttribute("INSTAR." + instarKey)); + Parameter params = mapper.readValue(ctx.getAttribute(InstarClientConstant.SOURCE_SYSTEM_INSTAR + "." + instarKey), Parameter.class); + + log.info("Processing rule Type : " + params.getRuleType()); + switch(params.getRuleType()){ + case InstarClientConstant.INTERFACE_IP_ADDRESS: + handler = new InterfaceIpAddressImpl(params, ctx); + break; + default: + throw new Exception("No Rule Defined to process :" + params.getRuleType()); + } + handler.processRule(); + + } + log.info("responsePrefix =" + responsePrefix); + ctx.setAttribute(responsePrefix + InstarClientConstant.INSTAR_KEY_VALUES, ctx.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_SUCCESS); + ctx.setAttribute(InstarClientConstant.INSTAR_KEY_VALUES, null); + } + catch (Exception e) + { + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed processing Instar request" + e.getMessage()); + e.printStackTrace(); + throw new SvcLogicException(e.getMessage()); + } + } + private static String[] getInstarKeys(String keyString) { + String fn = "InstarClientNode.getInstarKeys"; + System.out.println("Received instar Key String as :" + keyString); + + keyString = keyString.replace("[",""); + keyString = keyString.replace("]", ""); + keyString = keyString.replace("\"", ""); + if(keyString.contains(",")) + { + String[] keys = keyString.split(","); + return keys; + } + else{ + String[] keys = {keyString}; + return keys; + } + } + public void getInstarData(Map inParams, SvcLogicContext ctx) + throws SvcLogicException{ + log.info("Received getInstarData call with params : " + inParams); + String responsePrefix = (String)inParams.get(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX); + try + { + HashMap input = new HashMap(); + input.putAll(inParams); + RestClientInterface rcINterface = new InstarRestClientImpl(input); + String response = rcINterface.sendRequest(inParams.get("operationName")); + + responsePrefix = StringUtils.isNotBlank(responsePrefix) ? responsePrefix + "." : ""; + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_SUCCESS); + ctx.setAttribute(responsePrefix + InstarClientConstant.INSTAR_KEY_VALUES, response); + + } + catch (Exception e) + { + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + log.error("Failed processing Instar request" + e.getMessage()); + e.printStackTrace(); + throw new SvcLogicException(e.getMessage()); + } + } + +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/utils/InstarClientConstant.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/utils/InstarClientConstant.java new file mode 100644 index 000000000..30e59db22 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/onap/appc/instar/utils/InstarClientConstant.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.utils; + +public class InstarClientConstant +{ + public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; + public static String OUTPUT_PARAM_STATUS = "status"; + public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static String OUTPUT_STATUS_SUCCESS = "success"; + public static String OUTPUT_STATUS_FAILURE = "failure"; + + + + public static final String INSTAR_KEYS = "instarKeys"; + + public static final String INTERFACE_IP_ADDRESS = "interface-ip-address"; + public static final String SOURCE_SYSTEM_INSTAR = "INSTAR"; + public static final String VNF_TYPE = "vnf-type"; + public static final String ADDRESSFDQN = "addressfqdn"; + public static final String VNF_NAME = "vnf-name"; + public static final String INSTAR_KEY_VALUES = "INSTAR-KEY-VALUES"; + public static final String INSTAR_RESPONSE_BLOCK_NAME = "vnfConfigurationParameterDetails"; + public static final String FDQN = "fqdn"; + + + public static final String MOCK_INSTAR="mock_instar"; + public static final String AFT_LATITUDE="aft_latitude"; + public static final String AFT_LONGITUDE="aft_latitude"; + public static final String AFT_ENVIRONMENT="aft_environment"; + public static final String SCLD_PLATFORM="scld_platform"; + public static final String AUTHORIZATION="authorization"; + public static final String DME2_CLIENT_TIMEOUTMS="dme2_client_timeoutms"; + public static final String DME2_CLIENT_SENDANDWAIT="dme2_client_sendandwait"; + public static final String BASE_URL="_base_url"; + public static final String HTTP_HEADERS="_http_headers"; + + public static final String V6_ADDRESS="ipaddress-v6"; + public static final String INSTAR_V6_ADDRESS="v6IPAddress"; + + + public static final String V4_ADDRESS="ipaddress-v4"; + public static final String INSTAR_V4_ADDRESS="v4IPAddress"; + + public static final String SUB_CONTEXT="_sub_context"; + public static final String URL_SUFFIX="_suffix"; + public static final String VERSION="_version"; + public static final String ENV_CONTEXT="_env_context"; + public static final String ROUTEOFFER="_routeoffer"; + public static final String APPC_PROPERTIES = "appc.properties"; + public static final String METHOD="_method"; + public static final String OPERATION_GET_IPADDRESS_BY_VNF_NAME = "getIpAddressByVnf"; + + public static final String OUTBOUND_PROPERTIES= "/outbound.properties"; + + public static String CONTENT_TYPE = "application/json"; + public static String RETURNED_RESPONSE_TYPE = "application/json"; + +} + diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/InstarClientActivator.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/InstarClientActivator.java deleted file mode 100644 index 09021daa4..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/InstarClientActivator.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar; - -import java.util.LinkedList; -import java.util.List; - -import org.onap.appc.instar.node.InstarClientNode; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class InstarClientActivator implements BundleActivator{ - - private List registrations = new LinkedList(); - private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarClientActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception - { - - InstarClientNode instarClientNode = new InstarClientNode(); - log.info("Registering service "+ instarClientNode.getClass().getName()); - registrations.add(ctx.registerService(instarClientNode.getClass().getName(), instarClientNode, null)); - log.info("Registering service sccessful for "+ instarClientNode.getClass().getName()); - - } - @Override - public void stop(BundleContext arg0) throws Exception - { - for (ServiceRegistration registration: registrations) - { - registration.unregister(); - registration = null; - } - - } - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/Dme2Client.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/Dme2Client.java deleted file mode 100644 index fa22a751f..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/Dme2Client.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.dme2client; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Properties; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.io.IOUtils; -import org.onap.appc.instar.utils.InstarClientConstant; - - -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 com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; - - -public class Dme2Client { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(Dme2Client.class); - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - //DME2Client client = null; - Properties props = new Properties(); - String operationName ; - String appendContext; - - public Dme2Client(String optName, String subCtxt, HashMap data) throws Exception{ - log.info("Setting Properties for DME2 Client for INSTAR connection"); - this.operationName=optName; - this.appendContext = data.get(subCtxt); - String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) - throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR); - String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES; - InputStream propStream = new FileInputStream(propFile); - try - { - props.load(propStream); - } - catch (Exception e) - { - throw new Exception("Could not load properties file " + propFile, e); - } - finally - { - try - { - propStream.close(); - } - catch (Exception e) - { - log.warn("Could not close FileInputStream", e); - } - } - } - - public ClientResponse sendtoInstar() throws Exception { - - log.info("Called Send with operation Name=" + this.operationName + "and = " + props.getProperty(operationName+InstarClientConstant.BASE_URL)); - String resourceUri = props.getProperty(operationName+InstarClientConstant.BASE_URL)+ - props.getProperty(operationName + InstarClientConstant.URL_SUFFIX) + - props.getProperty(operationName + InstarClientConstant.SUB_CONTEXT)+ appendContext ; - - log.info("DME Endpoint URI:" + resourceUri); - Client client = null; - WebResource webResource = null; - ClientResponse clientResponse = null; - String authorization = props.getProperty("authorization"); - String requestDataType = "application/json"; - String responseDataType= MediaType.APPLICATION_JSON; - String methodType = props.getProperty("getIpAddressByVnf_method"); - String request = ""; - String userId=props.getProperty("MechID"); - String password=props.getProperty("MechPass"); - - log.info("authorization = " + authorization + "methodType= " + methodType); - try{ - DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); - System.setProperty("jsse.enableSNIExtension", "false"); - SSLContext sslContext = null; - SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); - sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); - defaultClientConfig.getProperties().put( - com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext)); - client = Client.create(defaultClientConfig); - client.addFilter(new HTTPBasicAuthFilter(userId, password)); - - webResource = client.resource(new URI(resourceUri)); - webResource.setProperty("Content-Type", "application/json;charset=UTF-8"); - - if(HttpMethod.GET.equalsIgnoreCase(methodType)){ - clientResponse = webResource.accept(responseDataType).get(ClientResponse.class); - }else if(HttpMethod.POST.equalsIgnoreCase(methodType)){ - clientResponse = webResource.type(requestDataType).post(ClientResponse.class, request); - }else if(HttpMethod.PUT.equalsIgnoreCase(methodType)){ - clientResponse = webResource.type(requestDataType).put(ClientResponse.class,request); - }else if(HttpMethod.DELETE.equalsIgnoreCase(methodType)){ - clientResponse = webResource.delete(ClientResponse.class); - } - - return clientResponse; - - }catch (Exception e) { - log.info("failed in RESTCONT Action ("+methodType+") for the resource " + resourceUri + ", falut message :"+e.getMessage()); - throw new Exception("Error While gettting Data from INSTAR" + e.getMessage()); - } - finally { - // clean up. - webResource = null; - if(client != null){ - client.destroy(); - client = null; - } - } - - - } - - public String send() { - String response = null; - try{ - - if(props !=null && - props.getProperty(InstarClientConstant.MOCK_INSTAR) != null && - props.getProperty(InstarClientConstant.MOCK_INSTAR).equalsIgnoreCase("true")) - return IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"), Charset.defaultCharset()); - - ClientResponse clientResponse = sendtoInstar(); - if(clientResponse != null){ - response = clientResponse.getEntity(String.class); - log.info(clientResponse.getStatus() + " Status, Response :" + response); - - } - } catch (Exception t) { - log.error("Error in Dme2Client for send() method while sending response:" ,t); - } - return response; - } - - private HostnameVerifier getHostnameVerifier() { - return new HostnameVerifier() { - @Override - public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { - return true; - } - }; - } - - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/SecureRestClientTrustManager.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/SecureRestClientTrustManager.java deleted file mode 100644 index 86c2d99b3..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/dme2client/SecureRestClientTrustManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.dme2client; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.X509TrustManager; - - -public class SecureRestClientTrustManager implements X509TrustManager { - - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) - throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public boolean isClientTrusted(X509Certificate[] arg0) { - return true; - } - - public boolean isServerTrusted(X509Certificate[] arg0) { - return true; - } - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java deleted file mode 100644 index 08df6f02e..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarResponseHandlerImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.appc.instar.interfaces.ResponseHandlerInterface; -import org.onap.appc.instar.utils.InstarClientConstant; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class InstarResponseHandlerImpl implements ResponseHandlerInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarResponseHandlerImpl.class); - - ResponseKey resKey = null; - SvcLogicContext ctxt = null; - - public InstarResponseHandlerImpl(ResponseKey filterKeys, SvcLogicContext context) { - this.resKey = filterKeys; - this.ctxt = context; - - } - - @Override - public Object processResponse(String instarResponse, String instarKey) { - String fn = " InstarResponseHandlerImpl.processResponse "; - log.info(fn + " Instar Response :" + instarResponse); - - JSONObject instarKeyValues; - - log.info("Instar Data in Context : "+ ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); - if(ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES) != null){ - instarKeyValues = new JSONObject(ctxt.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); - log.info("Instar data already exsits : " + instarKeyValues.toString()); - } - else - instarKeyValues = new JSONObject(); - JSONArray instarResponses = new JSONObject(instarResponse).getJSONArray(InstarClientConstant.INSTAR_RESPONSE_BLOCK_NAME); - for (int i = 0; i < instarResponses.length(); i++){ - JSONObject res = instarResponses.getJSONObject(i); - log.info(fn + "Instar Block :" + i + " Values :" + res.toString()); - log.info(fn + "Appc Filter Key :" + ctxt.getAttribute(InstarClientConstant.VNF_NAME) + resKey.getUniqueKeyValue()); - - if(res.getString(InstarClientConstant.FDQN) != null && - res.getString(InstarClientConstant.FDQN).equalsIgnoreCase(ctxt.getAttribute(InstarClientConstant.VNF_NAME) + resKey.getUniqueKeyValue())){ - if(resKey.getFieldKeyName().equals(InstarClientConstant.V4_ADDRESS)) - instarKeyValues.put(instarKey, res.getString(InstarClientConstant.INSTAR_V4_ADDRESS)); - else if(resKey.getFieldKeyName().equals(InstarClientConstant.V6_ADDRESS)) - instarKeyValues.put(instarKey, res.getString(InstarClientConstant.INSTAR_V6_ADDRESS)); - break; - } - } - log.info(fn + "Instar KeyValues :" + instarKeyValues); - ctxt.setAttribute(InstarClientConstant.INSTAR_KEY_VALUES, instarKeyValues.toString()); - - - return instarKeyValues; - } - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarRestClientImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarRestClientImpl.java deleted file mode 100644 index db43d9c41..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InstarRestClientImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.HashMap; - -import org.apache.commons.io.IOUtils; -import org.onap.appc.instar.dme2client.Dme2Client; -import org.onap.appc.instar.interfaces.RestClientInterface; -import org.onap.appc.instar.utils.InstarClientConstant; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class InstarRestClientImpl implements RestClientInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarRestClientImpl.class); - HashMap requestData = null; - Dme2Client dme2Client; - - public InstarRestClientImpl(HashMap instarRequestData) { - - this.requestData = instarRequestData; - } - - @Override - public String sendRequest(String operation) throws Exception { - - String instarResponse = null; - try { - if(operation !=null && operation.equalsIgnoreCase(InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME)){ - dme2Client = new Dme2Client(operation, InstarClientConstant.VNF_NAME, requestData); - } - instarResponse = dme2Client.send(); - log.info("Resposne in InstarRestClientImpl = " + instarResponse); - if(instarResponse == null || instarResponse.length() < 0) - throw new Exception ("No Data received from Instar for this call " + operation); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - return instarResponse; - } - - - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java deleted file mode 100644 index cc2eeaa07..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaceImpl/InterfaceIpAddressImpl.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import java.util.HashMap; -import java.util.List; - -import org.onap.appc.instar.interfaces.ResponseHandlerInterface; -import org.onap.appc.instar.interfaces.RestClientInterface; -import org.onap.appc.instar.interfaces.RuleHandlerInterface; -import org.onap.appc.instar.node.InstarClientNode; -import org.onap.appc.instar.utils.InstarClientConstant; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class InterfaceIpAddressImpl implements RuleHandlerInterface { - - private static final EELFLogger log = EELFManager.getInstance().getLogger(InterfaceIpAddressImpl.class); - private Parameter parameters; - private SvcLogicContext context; - - public InterfaceIpAddressImpl(Parameter params, SvcLogicContext ctx) { - this.parameters = params; - this.context = ctx; - } - - @Override - public void processRule() throws Exception { - - String fn = "InterfaceIpAddressHandler.processRule"; - log.info(fn + "Processing rule :" + parameters.getRuleType()); - String operationName ; - - RestClientInterface restClient = null; - ResponseHandlerInterface responseHandler = null; - - List responseKeyList = parameters.getResponseKeys(); - if(responseKeyList != null && responseKeyList.size() > 0){ - for(ResponseKey filterKeys : responseKeyList){ - //response.setUniqueKeyValue(response.getUniqueKeyValue()+ context.getAttribute(InstarClientConstant.VNF_NAME)); - switch(parameters.getSource()){ - case InstarClientConstant.SOURCE_SYSTEM_INSTAR: - restClient = new InstarRestClientImpl(createInstarRequestData(context)); - responseHandler = new InstarResponseHandlerImpl(filterKeys, context ); - operationName = "getIpAddressByVnf"; - break; - default: - throw new Exception("No Client registered for : " + parameters.getSource()); - - } - responseHandler.processResponse(restClient.sendRequest(operationName),parameters.getName() ); - } - } - else - { - throw new Exception("NO response Keys set for : " + parameters.getRuleType()); - } - } - - private HashMap createInstarRequestData(SvcLogicContext ctxt) { - HashMap requestParams = new HashMap(); - requestParams.put(InstarClientConstant.VNF_NAME, ctxt.getAttribute(InstarClientConstant.VNF_NAME)); - return requestParams; - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/ResponseHandlerInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/ResponseHandlerInterface.java deleted file mode 100644 index 8211967b0..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/ResponseHandlerInterface.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaces; - -public interface ResponseHandlerInterface { - - public Object processResponse(String response, String instarKey); - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RestClientInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RestClientInterface.java deleted file mode 100644 index bf6c5b34d..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RestClientInterface.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaces; - -public interface RestClientInterface { - - - public String sendRequest(String operation) throws Exception; - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RuleHandlerInterface.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RuleHandlerInterface.java deleted file mode 100644 index 86f31d2fa..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/interfaces/RuleHandlerInterface.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaces; - - -public interface RuleHandlerInterface { - - public void processRule() throws Exception; - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/node/InstarClientNode.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/node/InstarClientNode.java deleted file mode 100644 index 1d343c668..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/node/InstarClientNode.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.node; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.instar.interfaceImpl.InstarRestClientImpl; -import org.onap.appc.instar.interfaceImpl.InterfaceIpAddressImpl; -import org.onap.appc.instar.interfaces.RestClientInterface; -import org.onap.appc.instar.interfaces.RuleHandlerInterface; -import org.onap.appc.instar.utils.InstarClientConstant; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public class InstarClientNode implements SvcLogicJavaPlugin -{ - private static final EELFLogger log = EELFManager.getInstance().getLogger(InstarClientNode.class); - - public void getInstarInfo(Map inParams, SvcLogicContext ctx) - throws SvcLogicException{ - log.info("Received getInstarInfo call with params : " + inParams); - String responsePrefix = (String)inParams.get(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try - { - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? responsePrefix + "." : ""; - String [] instarKeys = getInstarKeys(inParams.get(InstarClientConstant.INSTAR_KEYS)); - for (String instarKey : instarKeys){ - log.info("Processing Key : " + instarKey); - log.info("Searching key for : " + "INSTAR." + instarKey); - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - RuleHandlerInterface handler = null; - log.info("Received Context : " + ctx.getAttribute("INSTAR." + instarKey)); - Parameter params = mapper.readValue(ctx.getAttribute(InstarClientConstant.SOURCE_SYSTEM_INSTAR + "." + instarKey), Parameter.class); - - log.info("Processing rule Type : " + params.getRuleType()); - switch(params.getRuleType()){ - case InstarClientConstant.INTERFACE_IP_ADDRESS: - handler = new InterfaceIpAddressImpl(params, ctx); - break; - default: - throw new Exception("No Rule Defined to process :" + params.getRuleType()); - } - handler.processRule(); - - } - log.info("responsePrefix =" + responsePrefix); - ctx.setAttribute(responsePrefix + InstarClientConstant.INSTAR_KEY_VALUES, ctx.getAttribute(InstarClientConstant.INSTAR_KEY_VALUES)); - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_SUCCESS); - ctx.setAttribute(InstarClientConstant.INSTAR_KEY_VALUES, null); - } - catch (Exception e) - { - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed processing Instar request" + e.getMessage()); - e.printStackTrace(); - throw new SvcLogicException(e.getMessage()); - } - } - private static String[] getInstarKeys(String keyString) { - String fn = "InstarClientNode.getInstarKeys"; - System.out.println("Received instar Key String as :" + keyString); - - keyString = keyString.replace("[",""); - keyString = keyString.replace("]", ""); - keyString = keyString.replace("\"", ""); - if(keyString.contains(",")) - { - String[] keys = keyString.split(","); - return keys; - } - else{ - String[] keys = {keyString}; - return keys; - } - } - public void getInstarData(Map inParams, SvcLogicContext ctx) - throws SvcLogicException{ - log.info("Received getInstarData call with params : " + inParams); - String responsePrefix = (String)inParams.get(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX); - try - { - HashMap input = new HashMap(); - input.putAll(inParams); - RestClientInterface rcINterface = new InstarRestClientImpl(input); - String response = rcINterface.sendRequest(inParams.get("operationName")); - - responsePrefix = StringUtils.isNotBlank(responsePrefix) ? responsePrefix + "." : ""; - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_SUCCESS); - ctx.setAttribute(responsePrefix + InstarClientConstant.INSTAR_KEY_VALUES, response); - - } - catch (Exception e) - { - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_STATUS, InstarClientConstant.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + InstarClientConstant.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - log.error("Failed processing Instar request" + e.getMessage()); - e.printStackTrace(); - throw new SvcLogicException(e.getMessage()); - } - } - -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/utils/InstarClientConstant.java b/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/utils/InstarClientConstant.java deleted file mode 100644 index 30e59db22..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/main/java/org/openecomp/appc/instar/utils/InstarClientConstant.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.utils; - -public class InstarClientConstant -{ - public static String INPUT_PARAM_RESPONSE_PRIFIX = "responsePrefix"; - public static String OUTPUT_PARAM_STATUS = "status"; - public static String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static String OUTPUT_STATUS_SUCCESS = "success"; - public static String OUTPUT_STATUS_FAILURE = "failure"; - - - - public static final String INSTAR_KEYS = "instarKeys"; - - public static final String INTERFACE_IP_ADDRESS = "interface-ip-address"; - public static final String SOURCE_SYSTEM_INSTAR = "INSTAR"; - public static final String VNF_TYPE = "vnf-type"; - public static final String ADDRESSFDQN = "addressfqdn"; - public static final String VNF_NAME = "vnf-name"; - public static final String INSTAR_KEY_VALUES = "INSTAR-KEY-VALUES"; - public static final String INSTAR_RESPONSE_BLOCK_NAME = "vnfConfigurationParameterDetails"; - public static final String FDQN = "fqdn"; - - - public static final String MOCK_INSTAR="mock_instar"; - public static final String AFT_LATITUDE="aft_latitude"; - public static final String AFT_LONGITUDE="aft_latitude"; - public static final String AFT_ENVIRONMENT="aft_environment"; - public static final String SCLD_PLATFORM="scld_platform"; - public static final String AUTHORIZATION="authorization"; - public static final String DME2_CLIENT_TIMEOUTMS="dme2_client_timeoutms"; - public static final String DME2_CLIENT_SENDANDWAIT="dme2_client_sendandwait"; - public static final String BASE_URL="_base_url"; - public static final String HTTP_HEADERS="_http_headers"; - - public static final String V6_ADDRESS="ipaddress-v6"; - public static final String INSTAR_V6_ADDRESS="v6IPAddress"; - - - public static final String V4_ADDRESS="ipaddress-v4"; - public static final String INSTAR_V4_ADDRESS="v4IPAddress"; - - public static final String SUB_CONTEXT="_sub_context"; - public static final String URL_SUFFIX="_suffix"; - public static final String VERSION="_version"; - public static final String ENV_CONTEXT="_env_context"; - public static final String ROUTEOFFER="_routeoffer"; - public static final String APPC_PROPERTIES = "appc.properties"; - public static final String METHOD="_method"; - public static final String OPERATION_GET_IPADDRESS_BY_VNF_NAME = "getIpAddressByVnf"; - - public static final String OUTBOUND_PROPERTIES= "/outbound.properties"; - - public static String CONTENT_TYPE = "application/json"; - public static String RETURNED_RESPONSE_TYPE = "application/json"; - -} - diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java new file mode 100644 index 000000000..1d0db357a --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import org.junit.Test; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestInstarResponseHandlerImpl { + + @Test + public void testProcessResponseForIpv4(){ + ResponseKey resKey = new ResponseKey(); + resKey.setUniqueKeyValue("x"); + SvcLogicContext svc = new SvcLogicContext(); + svc.setAttribute("vnf-name", "fqdn"); + resKey.setFieldKeyName("ipaddress-v4"); + String instarKey = "key"; + String instarRes ="{\"vnfConfigurationParameterDetails\":" + + "[{\"fqdn\":\"fqdnx\",\"v4IPAddress\":\"value2\"}]}"; + InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); + impl.processResponse(instarRes, instarKey); + } + + @Test + public void testProcessResponseForIpv6(){ + ResponseKey resKey = new ResponseKey(); + resKey.setUniqueKeyValue("x"); + SvcLogicContext svc = new SvcLogicContext(); + svc.setAttribute("vnf-name", "fqdn"); + resKey.setFieldKeyName("ipaddress-v6"); + String instarKey = "key"; + String instarRes ="{\"vnfConfigurationParameterDetails\":" + + "[{\"fqdn\":\"fqdnx\",\"v6IPAddress\":\"value2\"}]}"; + InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); + impl.processResponse(instarRes, instarKey); + } + + @Test + public void testProcessResponseInstarKeyValues(){ + + ResponseKey resKey = new ResponseKey(); + resKey.setUniqueKeyValue("x"); + String json ="{\"vnfConfigurationParameterDetails\":" + + "[{\"fqdn\":\"fqdnx\",\"v4IPAddress\":\"value2\"}]}"; + SvcLogicContext svc = new SvcLogicContext(); + svc.setAttribute("vnf-name", "fqdn"); + svc.setAttribute("INSTAR-KEY-VALUES", json); + resKey.setFieldKeyName("ipaddress-v6"); + String instarKey = "key"; + String instarRes ="{\"vnfConfigurationParameterDetails\":" + + "[{\"fqdn\":\"fqdnx\",\"v6IPAddress\":\"value2\"}]}"; + InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); + impl.processResponse(instarRes, instarKey); + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarRestClientImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarRestClientImpl.java new file mode 100644 index 000000000..cf2427dc1 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInstarRestClientImpl.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import java.util.HashMap; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.instar.dme2client.Dme2Client; + +public class TestInstarRestClientImpl { + + @Test(expected=Exception.class) + public void testSendRequest() throws Exception{ + HashMap map = new HashMap<>(); + map.put("key", "value"); + Dme2Client client = Mockito.mock(Dme2Client.class); + Mockito.when(client.send()).thenReturn("test"); + InstarRestClientImpl imp = new InstarRestClientImpl(map); + imp.sendRequest("getIpAddressByVnf"); + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java new file mode 100644 index 000000000..f29bebd7e --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.interfaceImpl; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import org.openecomp.sdnc.config.params.data.Parameter; +import org.openecomp.sdnc.config.params.data.ResponseKey; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestInterfaceIpAddressImpl { + + @Test(expected=Exception.class) + public void testProcessRuleException1() throws Exception{ + Parameter param = new Parameter(); + param.setRuleType("test"); + param.setName("test"); + param.setSource("INSTAR"); + SvcLogicContext svc = new SvcLogicContext(); + svc.setAttribute("vnf-name", "test"); + InterfaceIpAddressImpl impl = new InterfaceIpAddressImpl(param,svc); + impl.processRule(); + } + + @Test(expected=Exception.class) + public void testProcessRuleException2() throws Exception{ + List list = new ArrayList<>(); + list.add(new ResponseKey()); + list.add(new ResponseKey()); + Parameter param = new Parameter(); + param.setResponseKeys(list); + param.setRuleType("test"); + param.setName("test"); + param.setSource("INSTAR"); + SvcLogicContext svc = new SvcLogicContext(); + svc.setAttribute("vnf-name", "test"); + InterfaceIpAddressImpl impl = new InterfaceIpAddressImpl(param,svc); + impl.processRule(); + param.setSource("INSTAR1"); + impl.processRule(); + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestDme2Client.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestDme2Client.java new file mode 100644 index 000000000..8e87ffe35 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestDme2Client.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.node; + +import java.util.HashMap; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.appc.instar.dme2client.Dme2Client; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class TestDme2Client { + + @Test(expected=Exception.class) + public void testSendtoInstar() throws Exception{ + + HashMap data = new HashMap(); + data.put("subtext","value"); + PowerMockito.mockStatic(System.class); + PowerMockito.when((System.getenv("test"))).thenReturn("test"); + Dme2Client dme2 = new Dme2Client("opt","subtext",data); + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestInstarClientNode.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestInstarClientNode.java new file mode 100644 index 000000000..285662f75 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestInstarClientNode.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.node; + +import java.net.URI; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.ws.rs.HttpMethod; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.instar.dme2client.SecureRestClientTrustManager; +import org.onap.appc.instar.utils.InstarClientConstant; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; + + +public class TestInstarClientNode { + + //ONAP Migration + + @Test(expected=Exception.class) + public void testInstarClientNode() throws Exception { + + SvcLogicContext ctx = new SvcLogicContext(); + String key_conetent = IOUtils.toString(TestInstarClientNode.class.getClassLoader().getResourceAsStream("templates/sampleKeyContents"), Charset.defaultCharset()); + Map inParams = new HashMap(); + inParams.put(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX, "TEST"); + inParams.put(InstarClientConstant.INSTAR_KEYS, "LOCAL_ACCESS_IP_ADDR"); + inParams.put("operationName", InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME); + ctx.setAttribute("INSTAR.LOCAL_ACCESS_IP_ADDR", key_conetent); + ctx.setAttribute(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX, "TEST"); + ctx.setAttribute(InstarClientConstant.VNF_NAME, "basx0003v"); + InstarClientNode icn = new InstarClientNode(); + icn.getInstarInfo(inParams, ctx); + String address = (new JSONObject(ctx.getAttribute("TEST." + InstarClientConstant.INSTAR_KEY_VALUES))).getString("LOCAL_ACCESS_IP_ADDR"); + } + @Test(expected=Exception.class) + public void testInstarData() throws Exception { + + InstarClientNode inNode = new InstarClientNode(); + SvcLogicContext ctx = new SvcLogicContext (); + Map inParams = new HashMap(); + + inParams.put(InstarClientConstant.VNF_NAME, "basx0003v"); + inParams.put("operationName", InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME); + inNode.getInstarData(inParams, ctx); + + + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestSecureRestClientTrustManager.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestSecureRestClientTrustManager.java new file mode 100644 index 000000000..b18673a40 --- /dev/null +++ b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/onap/appc/instar/node/TestSecureRestClientTrustManager.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.instar.node; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.instar.dme2client.SecureRestClientTrustManager; + +public class TestSecureRestClientTrustManager { + + @Test + public void testSecureRestClient() throws CertificateException{ + X509Certificate[] arg0 = new X509Certificate[1]; + SecureRestClientTrustManager sm = Mockito.mock(SecureRestClientTrustManager.class); + Mockito.when(sm.getAcceptedIssuers()).thenReturn(Mockito.any()); + Mockito.when(sm.isClientTrusted(arg0)).thenReturn(true); + Mockito.when(sm.isServerTrusted(arg0)).thenReturn(true); + } +} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java deleted file mode 100644 index 1d0db357a..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarResponseHandlerImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import org.junit.Test; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestInstarResponseHandlerImpl { - - @Test - public void testProcessResponseForIpv4(){ - ResponseKey resKey = new ResponseKey(); - resKey.setUniqueKeyValue("x"); - SvcLogicContext svc = new SvcLogicContext(); - svc.setAttribute("vnf-name", "fqdn"); - resKey.setFieldKeyName("ipaddress-v4"); - String instarKey = "key"; - String instarRes ="{\"vnfConfigurationParameterDetails\":" - + "[{\"fqdn\":\"fqdnx\",\"v4IPAddress\":\"value2\"}]}"; - InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); - impl.processResponse(instarRes, instarKey); - } - - @Test - public void testProcessResponseForIpv6(){ - ResponseKey resKey = new ResponseKey(); - resKey.setUniqueKeyValue("x"); - SvcLogicContext svc = new SvcLogicContext(); - svc.setAttribute("vnf-name", "fqdn"); - resKey.setFieldKeyName("ipaddress-v6"); - String instarKey = "key"; - String instarRes ="{\"vnfConfigurationParameterDetails\":" - + "[{\"fqdn\":\"fqdnx\",\"v6IPAddress\":\"value2\"}]}"; - InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); - impl.processResponse(instarRes, instarKey); - } - - @Test - public void testProcessResponseInstarKeyValues(){ - - ResponseKey resKey = new ResponseKey(); - resKey.setUniqueKeyValue("x"); - String json ="{\"vnfConfigurationParameterDetails\":" - + "[{\"fqdn\":\"fqdnx\",\"v4IPAddress\":\"value2\"}]}"; - SvcLogicContext svc = new SvcLogicContext(); - svc.setAttribute("vnf-name", "fqdn"); - svc.setAttribute("INSTAR-KEY-VALUES", json); - resKey.setFieldKeyName("ipaddress-v6"); - String instarKey = "key"; - String instarRes ="{\"vnfConfigurationParameterDetails\":" - + "[{\"fqdn\":\"fqdnx\",\"v6IPAddress\":\"value2\"}]}"; - InstarResponseHandlerImpl impl = new InstarResponseHandlerImpl(resKey,svc); - impl.processResponse(instarRes, instarKey); - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarRestClientImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarRestClientImpl.java deleted file mode 100644 index cf2427dc1..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInstarRestClientImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import java.util.HashMap; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.instar.dme2client.Dme2Client; - -public class TestInstarRestClientImpl { - - @Test(expected=Exception.class) - public void testSendRequest() throws Exception{ - HashMap map = new HashMap<>(); - map.put("key", "value"); - Dme2Client client = Mockito.mock(Dme2Client.class); - Mockito.when(client.send()).thenReturn("test"); - InstarRestClientImpl imp = new InstarRestClientImpl(map); - imp.sendRequest("getIpAddressByVnf"); - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java deleted file mode 100644 index f29bebd7e..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/interfaceImpl/TestInterfaceIpAddressImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.interfaceImpl; - -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.openecomp.sdnc.config.params.data.Parameter; -import org.openecomp.sdnc.config.params.data.ResponseKey; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestInterfaceIpAddressImpl { - - @Test(expected=Exception.class) - public void testProcessRuleException1() throws Exception{ - Parameter param = new Parameter(); - param.setRuleType("test"); - param.setName("test"); - param.setSource("INSTAR"); - SvcLogicContext svc = new SvcLogicContext(); - svc.setAttribute("vnf-name", "test"); - InterfaceIpAddressImpl impl = new InterfaceIpAddressImpl(param,svc); - impl.processRule(); - } - - @Test(expected=Exception.class) - public void testProcessRuleException2() throws Exception{ - List list = new ArrayList<>(); - list.add(new ResponseKey()); - list.add(new ResponseKey()); - Parameter param = new Parameter(); - param.setResponseKeys(list); - param.setRuleType("test"); - param.setName("test"); - param.setSource("INSTAR"); - SvcLogicContext svc = new SvcLogicContext(); - svc.setAttribute("vnf-name", "test"); - InterfaceIpAddressImpl impl = new InterfaceIpAddressImpl(param,svc); - impl.processRule(); - param.setSource("INSTAR1"); - impl.processRule(); - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestDme2Client.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestDme2Client.java deleted file mode 100644 index 8e87ffe35..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestDme2Client.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.node; - -import java.util.HashMap; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.appc.instar.dme2client.Dme2Client; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -public class TestDme2Client { - - @Test(expected=Exception.class) - public void testSendtoInstar() throws Exception{ - - HashMap data = new HashMap(); - data.put("subtext","value"); - PowerMockito.mockStatic(System.class); - PowerMockito.when((System.getenv("test"))).thenReturn("test"); - Dme2Client dme2 = new Dme2Client("opt","subtext",data); - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestInstarClientNode.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestInstarClientNode.java deleted file mode 100644 index 285662f75..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestInstarClientNode.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.node; - -import java.net.URI; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.ws.rs.HttpMethod; - -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.instar.dme2client.SecureRestClientTrustManager; -import org.onap.appc.instar.utils.InstarClientConstant; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; - - -public class TestInstarClientNode { - - //ONAP Migration - - @Test(expected=Exception.class) - public void testInstarClientNode() throws Exception { - - SvcLogicContext ctx = new SvcLogicContext(); - String key_conetent = IOUtils.toString(TestInstarClientNode.class.getClassLoader().getResourceAsStream("templates/sampleKeyContents"), Charset.defaultCharset()); - Map inParams = new HashMap(); - inParams.put(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX, "TEST"); - inParams.put(InstarClientConstant.INSTAR_KEYS, "LOCAL_ACCESS_IP_ADDR"); - inParams.put("operationName", InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME); - ctx.setAttribute("INSTAR.LOCAL_ACCESS_IP_ADDR", key_conetent); - ctx.setAttribute(InstarClientConstant.INPUT_PARAM_RESPONSE_PRIFIX, "TEST"); - ctx.setAttribute(InstarClientConstant.VNF_NAME, "basx0003v"); - InstarClientNode icn = new InstarClientNode(); - icn.getInstarInfo(inParams, ctx); - String address = (new JSONObject(ctx.getAttribute("TEST." + InstarClientConstant.INSTAR_KEY_VALUES))).getString("LOCAL_ACCESS_IP_ADDR"); - } - @Test(expected=Exception.class) - public void testInstarData() throws Exception { - - InstarClientNode inNode = new InstarClientNode(); - SvcLogicContext ctx = new SvcLogicContext (); - Map inParams = new HashMap(); - - inParams.put(InstarClientConstant.VNF_NAME, "basx0003v"); - inParams.put("operationName", InstarClientConstant.OPERATION_GET_IPADDRESS_BY_VNF_NAME); - inNode.getInstarData(inParams, ctx); - - - } -} diff --git a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestSecureRestClientTrustManager.java b/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestSecureRestClientTrustManager.java deleted file mode 100644 index b18673a40..000000000 --- a/appc-outbound/appc-network-inventory-client/provider/src/test/java/org/openecomp/appc/instar/node/TestSecureRestClientTrustManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.instar.node; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.instar.dme2client.SecureRestClientTrustManager; - -public class TestSecureRestClientTrustManager { - - @Test - public void testSecureRestClient() throws CertificateException{ - X509Certificate[] arg0 = new X509Certificate[1]; - SecureRestClientTrustManager sm = Mockito.mock(SecureRestClientTrustManager.class); - Mockito.when(sm.getAcceptedIssuers()).thenReturn(Mockito.any()); - Mockito.when(sm.isClientTrusted(arg0)).thenReturn(true); - Mockito.when(sm.isServerTrusted(arg0)).thenReturn(true); - } -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProvider.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProvider.java new file mode 100644 index 000000000..990576422 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProvider.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.util.concurrent.Futures; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.onap.appc.provider.topology.TopologyService; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/* ADDED FOR FUSION SERVICE CODE */ + +@SuppressWarnings("JavaDoc") +/** + * Defines the APPC service provider. + *

+ * The rpc definition in the YANG model is shown below. This model is used to generate code to manage the inputs and + * outputs of the RPC service. For example, the input is defined by a class named {@link ConfigurationOperationInput}, + * which is generated from the name of the RPC and the "input" definition of the RPC. This class encapsulates the + * various objects that are passed to the RPC and is used to obtain values from the input parameters. + *

+ *

+ * Likewise, the outputs are defined by a class named {@link ConfigurationOperationOutput}. This class encapsulates the + * defined outputs. To make construction of the outputs easier, there are also generated builder classes that are named + * for the various elements of the output they "build", such as {@link ConfigurationResponseBuilder}. + *

+ * + *
+ *   rpc configuration-operation {
+ *      description "An operation to view, change, or audit the configuration of a VM";
+ *      input {
+ *          uses configuration-request-header;
+ *          uses configuration-request;
+ *      }
+ *      output {
+ *          uses common-response-header;
+ *          uses configuration-response;
+ *      }
+ *  }
+ * 
+ * + */ +public class AppcProvider implements AutoCloseable, AppcProviderService { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderClient.class); + + private final ExecutorService executor; + + /** + * The ODL data store broker. Provides access to a conceptual data tree store and also provides the ability to + * subscribe for changes to data under a given branch of the tree. + */ + protected DataBroker dataBroker; + + /** + * ODL Notification Service that provides publish/subscribe capabilities for YANG modeled notifications. + */ + protected NotificationProviderService notificationService; + + /** + * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are defined in YANG models. + */ + protected RpcProviderRegistry rpcRegistry; + + /** + * Represents our RPC implementation registration + */ + protected BindingAwareBroker.RpcRegistration rpcRegistration; + + /** + * The configuration + */ + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * @param dataBroker2 + * @param notificationProviderService + * @param rpcProviderRegistry + */ + @SuppressWarnings({ + "javadoc", "nls" + }) + public AppcProvider(DataBroker dataBroker2, NotificationProviderService notificationProviderService, + RpcProviderRegistry rpcProviderRegistry) { + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_INITIALIZING, appName, "provider"); + + executor = Executors.newFixedThreadPool(1); + dataBroker = dataBroker2; + notificationService = notificationProviderService; + rpcRegistry = rpcProviderRegistry; + + if (rpcRegistry != null) { + rpcRegistration = rpcRegistry.addRpcImplementation(AppcProviderService.class, this); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "provider"); + } + + /** + * Implements the close of the service + * + * @see java.lang.AutoCloseable#close() + */ + @SuppressWarnings("nls") + @Override + public void close() throws Exception { + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_TERMINATING, appName, "provider"); + executor.shutdown(); + if (rpcRegistration != null) { + rpcRegistration.close(); + } + logger.info(Msg.COMPONENT_TERMINATED, appName, "provider"); + } + + public Future> modifyConfig(ModifyConfigInput input) { + CommonRequestHeader hdr = input.getCommonRequestHeader(); + ConfigPayload data = input.getConfigPayload(); + RpcResult result = getTopologyService().modifyConfig(hdr, data); + return Futures.immediateFuture(result); + } + + /** + * Rebuilds a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#rebuild(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput) + */ + @Override + public Future> rebuild(RebuildInput input) { + + CommonRequestHeader hdr = input.getCommonRequestHeader(); + VnfResource vnf = input.getVnfResource(); + + RpcResult result = getTopologyService().rebuild(hdr, vnf); + return Futures.immediateFuture(result); + } + + /** + * Restarts a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#restart(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput) + */ + @Override + public Future> restart(RestartInput input) { + CommonRequestHeader hdr = input.getCommonRequestHeader(); + VnfResource vnf = input.getVnfResource(); + + RpcResult result = getTopologyService().restart(hdr, vnf); + return Futures.immediateFuture(result); + } + + /** + * Migrates a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#migrate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput) + */ + @Override + public Future> migrate(MigrateInput input) { + CommonRequestHeader hdr = input.getCommonRequestHeader(); + VnfResource vnf = input.getVnfResource(); + + RpcResult result = getTopologyService().migrate(hdr, vnf); + return Futures.immediateFuture(result); + } + + /** + * Evacuates a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#evacuate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput) + */ + @Override + public Future> evacuate(EvacuateInput input) { + + return null; + } + + /** + * Evacuates a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#evacuate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput) + */ + @Override + public Future> snapshot(SnapshotInput input) { + CommonRequestHeader hdr = input.getCommonRequestHeader(); + VnfResource vnf = input.getVnfResource(); + + RpcResult result = getTopologyService().snapshot(hdr, vnf); + return Futures.immediateFuture(result); + } + + /** + * Checks status of a VM + */ + @Override + public Future> vmstatuscheck(VmstatuscheckInput input) { + CommonRequestHeader hdr = input.getCommonRequestHeader(); + VnfResource vnf = input.getVnfResource(); + + TopologyService topology = getTopologyService(); + RpcResult result = getTopologyService().vmstatuscheck(hdr, vnf); + return Futures.immediateFuture(result); + } + + TopologyService getTopologyService() { + return new TopologyService(this); + } +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderClient.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderClient.java new file mode 100644 index 000000000..6195521be --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderClient.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.onap.appc.util.StringHelper; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.MDC; + +import static com.att.eelf.configuration.Configuration.*; + +import java.util.Properties; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class AppcProviderClient { + + private static EELFLogger LOG = EELFManager.getInstance().getApplicationLogger(); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + private SvcLogicService svcLogic = null; + + public AppcProviderClient() { + BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext(); + //Handle BundleContext returning null + if (bctx == null){ + LOG.warn("Cannot find bundle context for " + SvcLogicService.NAME); + } + else{ + // Get SvcLogicService reference + ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); + if (sref != null) { + svcLogic = (SvcLogicService) bctx.getService(sref); + + } else { + LOG.warn("Cannot find service reference for " + SvcLogicService.NAME); + + } + } + } + + public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { + LOG.debug(String.format("Checking for graph. %s %s %s %s", module, rpc, version, mode)); + return (svcLogic.hasGraph(module, rpc, version, mode)); + } + + public Properties execute(String module, String rpc, String version, String mode, Properties parms) + throws SvcLogicException { + + /* + * Set End time for Metrics Logger + */ + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + String startTimeStr = df.format(new Date()); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "sli"); + MDC.put("TargetServiceName", "execute"); + MDC.put("ClassName", "org.onap.appc.provider.AppcProviderClient"); + + LOG.debug("Parameters passed to SLI: " + StringHelper.propertiesToString(parms)); + metricsLogger.info("Parameters passed to SLI: " + StringHelper.propertiesToString(parms)); + + Properties respProps = svcLogic.execute(module, rpc, version, mode, parms); + + /* + * Set End time for Metrics Logger + */ + endTime = System.currentTimeMillis(); + duration = endTime - startTime; + endTimeStr = String.valueOf(endTime); + durationStr = String.valueOf(duration); + endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + + LOG.debug("Parameters returned by SLI: " + StringHelper.propertiesToString(respProps)); + metricsLogger.info("Parameters returned by SLI: " + StringHelper.propertiesToString(respProps)); + + return respProps; + } +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderLcm.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderLcm.java new file mode 100644 index 000000000..66e8909bd --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/AppcProviderLcm.java @@ -0,0 +1,1208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.google.common.util.concurrent.Futures; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AppcProviderLcmService; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.ActionLevel; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.i18n.Msg; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.provider.lcm.util.RequestInputBuilder; +import org.onap.appc.provider.lcm.util.ValidationService; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; + +import java.text.ParseException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.Collection; + +public class AppcProviderLcm implements AutoCloseable, AppcProviderLcmService { + + private Configuration configuration = ConfigurationFactory.getConfiguration(); + private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderLcm.class); + + private final ExecutorService executor; + + private final String COMMON_ERROR_MESSAGE_TEMPLATE = "Error processing %s input : %s"; + + /** + * The ODL data store broker. Provides access to a conceptual data tree store and also provides the ability to + * subscribe for changes to data under a given branch of the tree. + */ + protected DataBroker dataBroker; + + /** + * ODL Notification Service that provides publish/subscribe capabilities for YANG modeled notifications. + */ + protected NotificationProviderService notificationService; + + /** + * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are defined in YANG models. + */ + protected RpcProviderRegistry rpcRegistry; + + /** + * Represents our RPC implementation registration + */ + protected BindingAwareBroker.RpcRegistration rpcRegistration; + + + /** + * @param dataBroker + * @param notificationProviderService + * @param rpcProviderRegistry + */ + @SuppressWarnings({ + "javadoc", "nls" + }) + public AppcProviderLcm(DataBroker dataBroker, NotificationProviderService notificationProviderService, + RpcProviderRegistry rpcProviderRegistry) { + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_INITIALIZING, appName, "provider-lcm"); + + executor = Executors.newFixedThreadPool(1); + this.dataBroker = dataBroker; + this.notificationService = notificationProviderService; + this.rpcRegistry = rpcProviderRegistry; + + if (this.rpcRegistry != null) { + rpcRegistration = rpcRegistry.addRpcImplementation(AppcProviderLcmService.class, this); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "provider"); + } + + /** + * Implements the close of the service + * + * @see java.lang.AutoCloseable#close() + */ + @SuppressWarnings("nls") + @Override + public void close() throws Exception { + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_TERMINATING, appName, "provider"); + executor.shutdown(); + if (rpcRegistration != null) { + rpcRegistration.close(); + } + logger.info(Msg.COMPONENT_TERMINATED, appName, "provider"); + } + + + /** + * Rebuilds a specific VNF + * + * @see AppcProviderLcmService#rebuild(RebuildInput) + */ + @Override + public Future> rebuild(RebuildInput input) { + logger.debug("Input received : " + input.toString()); + + RebuildOutputBuilder outputBuilder = new RebuildOutputBuilder(); + String action = Action.Rebuild.toString() ; + String rpcName = Action.Rebuild.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + /** + * Restarts a specific VNF + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AppcProviderLcmService#restart(RestartInput) + */ + @Override + public Future> restart(RestartInput input) { + logger.debug("Input received : " + input.toString()); + + RestartOutputBuilder outputBuilder = new RestartOutputBuilder(); + String action = Action.Restart.toString() ; + String rpcName = Action.Restart.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()) + .action(action) + .rpcName(rpcName) + .build(); + + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + /** + * Migrates a specific VNF + * + * @see AppcProviderLcmService#migrate(MigrateInput) + */ + @Override + public Future> migrate(MigrateInput input) { + logger.debug("Input received : " + input.toString()); + + MigrateOutputBuilder outputBuilder = new MigrateOutputBuilder(); + String action = Action.Migrate.toString() ; + String rpcName = Action.Migrate.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + /** + * Evacuates a specific VNF + * + * @see AppcProviderLcmService#evacuate(EvacuateInput) + */ + @Override + public Future> evacuate(EvacuateInput input) { + logger.debug("Input received : " + input.toString()); + + EvacuateOutputBuilder outputBuilder = new EvacuateOutputBuilder(); + String action = Action.Evacuate.toString() ; + String rpcName = Action.Evacuate.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + /** + * Evacuates a specific VNF + * + * @see AppcProviderLcmService#snapshot(SnapshotInput) + */ + @Override + public Future> snapshot(SnapshotInput input) { + logger.debug("Input received : " + input.toString()); + + SnapshotOutputBuilder outputBuilder = new SnapshotOutputBuilder(); + String action = Action.Snapshot.toString() ; + String rpcName = Action.Snapshot.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + String identityUrl = input.getIdentityUrl(); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName) + .additionalContext("identity-url", identityUrl).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> rollback(RollbackInput input) { + logger.debug("Input received : " + input.toString()); + + RollbackOutputBuilder outputBuilder = new RollbackOutputBuilder(); + String rpcName = Action.Rollback.toString() ; + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), rpcName); + String identityUrl = input.getIdentityUrl(); + String snapshotId = input.getSnapshotId(); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).additionalContext("identity-url", identityUrl) + .additionalContext("snapshot-id", snapshotId).action(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, rpcName, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> sync(SyncInput input) { + logger.debug("Input received : " + input.toString()); + SyncOutputBuilder outputBuilder = new SyncOutputBuilder(); + String action = Action.Sync.toString() ; + String rpcName = Action.Sync.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + private Status buildParsingErrorStatus(ParseException e){ + LCMCommandStatus requestParsingFailure = LCMCommandStatus.REQUEST_PARSING_FAILED; + String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + Params params = new Params().addParam("errorMsg", errorMessage); + return buildStatus(requestParsingFailure.getResponseCode(), requestParsingFailure.getFormattedMessage(params)); + } + + private Status buildStatus(Integer code,String message){ + StatusBuilder status = new StatusBuilder(); + status.setCode(code); + status.setMessage(message); + return status.build(); + } + + private Status buildStatusWithDispatcherOutput(RequestHandlerOutput requestHandlerOutput){ + Integer statusCode = requestHandlerOutput.getResponseContext().getStatus().getCode(); + String statusMessage = requestHandlerOutput.getResponseContext().getStatus().getMessage(); + return buildStatus(statusCode, statusMessage); + } + + private RequestHandlerOutput createErrorRequestHandlerObj(RequestHandlerInput request, + LCMCommandStatus cmdStatus, + Msg msg, + Exception e) { + final String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + final String reason = EELFResourceManager.format(msg, e, + appName, e.getClass().getSimpleName(), "", e.getMessage()); + + RequestHandlerOutput requestHandlerOutput = new RequestHandlerOutput(); + final ResponseContext responseContext = new ResponseContext(); + requestHandlerOutput.setResponseContext(responseContext); + responseContext.setCommonHeader(request.getRequestContext().getCommonHeader()); + + String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + Params params = new Params().addParam("errorMsg", errorMessage); + responseContext.setStatus(cmdStatus.toStatus(params)); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + reason, + this.getClass().getName()); + + return requestHandlerOutput; + } + + private RequestHandler getRequestHandler(ActionLevel actionLevel){ + final BundleContext context = FrameworkUtil.getBundle(RequestHandler.class).getBundleContext(); + if (context != null) { + String filter = null; + try { + filter = "(level=" + actionLevel.name() + ")"; + Collection> serviceReferences = context.getServiceReferences(RequestHandler.class, filter); + if (serviceReferences.size() != 1) { + logger.error("Cannot find service reference for " + RequestHandler.class.getName()); + throw new RuntimeException(); + } + ServiceReference serviceReference = serviceReferences.iterator().next(); + return context.getService(serviceReference); + } catch (InvalidSyntaxException e) { + logger.error("Cannot find service reference for " + RequestHandler.class.getName() + ": Invalid Syntax " + filter, e); + throw new RuntimeException(e); + } + } + return null; + } + + @Override + public Future> terminate(TerminateInput input) { + logger.debug("Input received : " + input.toString()); + TerminateOutputBuilder outputBuilder = new TerminateOutputBuilder(); + String action = Action.Terminate.toString() ; + String rpcName = Action.Terminate.name().toLowerCase(); + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = + RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> configure(ConfigureInput input) { + logger.debug("Input received : " + input.toString()); + ConfigureOutputBuilder outputBuilder = new ConfigureOutputBuilder(); + String action = Action.Configure.toString() ; + String rpcName = "configure"; + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = + RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> configModify(ConfigModifyInput input) { + logger.debug("Input received : " + input.toString()); + ConfigModifyOutputBuilder outputBuilder = new ConfigModifyOutputBuilder(); + String action = Action.ConfigModify.toString() ; + String rpcName = "config-modify"; + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = + RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> configScaleout(ConfigScaleoutInput input) { + logger.debug("Input received : " + input.toString()); + ConfigScaleoutOutputBuilder outputBuilder = new ConfigScaleoutOutputBuilder(); + String action = Action.ConfigScaleOut.toString() ; + String rpcName = "config-scaleout"; + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = + RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> configRestore(ConfigRestoreInput input) { + logger.debug("Input received : " + input.toString()); + ConfigRestoreOutputBuilder outputBuilder = new ConfigRestoreOutputBuilder(); + String action = Action.ConfigRestore.toString() ; + String rpcName = "config-restore"; + Status status = + ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = + RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> test(TestInput input) { + logger.debug("Input received : " + input.toString()); + TestOutputBuilder outputBuilder = new TestOutputBuilder(); + String action = Action.Test.toString() ; + String rpcName = Action.Test.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> stop(StopInput input) { + logger.debug("Input received : " + input.toString()); + StopOutputBuilder outputBuilder = new StopOutputBuilder(); + String action = Action.Stop.toString() ; + String rpcName = Action.Stop.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + /** + * Starts a specific VNF + * + * @see AppcProviderLcmService#start(StartInput) + */ + @Override + public Future> start(StartInput input) { + logger.debug("Input received : " + input.toString()); + + StartOutputBuilder outputBuilder = new StartOutputBuilder(); + String action = Action.Start.toString() ; + String rpcName = Action.Start.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()) + .action(action) + .rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> audit(AuditInput input) { + logger.debug("Input received : " + input.toString()); + AuditOutputBuilder outputBuilder = new AuditOutputBuilder(); + String action = Action.Audit.toString(); + String rpcName = Action.Audit.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> softwareUpload(SoftwareUploadInput input) { + logger.debug("Input received : " + input.toString()); + SoftwareUploadOutputBuilder outputBuilder = new SoftwareUploadOutputBuilder(); + String action = Action.SoftwareUpload.toString() ; + String rpcName = convertActionNameToUrl(action); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder(). + requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> healthCheck(HealthCheckInput input) { + logger.debug("Input received : " + input.toString()); + HealthCheckOutputBuilder outputBuilder = new HealthCheckOutputBuilder(); + String action = Action.HealthCheck.toString() ; + String rpcName = convertActionNameToUrl(action); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> liveUpgrade(LiveUpgradeInput input) { + logger.debug("Input received : " + input.toString()); + LiveUpgradeOutputBuilder outputBuilder = new LiveUpgradeOutputBuilder(); + String action = Action.LiveUpgrade.toString() ; + String rpcName = convertActionNameToUrl(action); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> lock(LockInput input) { + logger.debug("Input received : " + input.toString()); + LockOutputBuilder outputBuilder = new LockOutputBuilder(); + String action = Action.Lock.toString() ; + String rpcName = Action.Lock.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> unlock(UnlockInput input) { + logger.debug("Input received : " + input.toString()); + UnlockOutputBuilder outputBuilder = new UnlockOutputBuilder(); + String action = Action.Unlock.toString() ; + String rpcName = Action.Unlock.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> checkLock(CheckLockInput input) { + logger.debug("Input received : " + input.toString()); + CheckLockOutputBuilder outputBuilder = new CheckLockOutputBuilder(); + String action = Action.CheckLock.toString(); + String rpcName = Action.CheckLock.name().toLowerCase(); + RequestHandlerOutput requestHandlerOutput = null; + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), + input.getAction(), action); + if (null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input + .getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action) + .rpcName(rpcName).build(); + requestHandlerOutput = executeRequest(request); + + status = buildStatusWithDispatcherOutput(requestHandlerOutput); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", + input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + if (requestHandlerOutput != null && requestHandlerOutput.getResponseContext().getStatus().getCode() == 400) { + outputBuilder.setLocked(CheckLockOutput.Locked.valueOf(requestHandlerOutput.getResponseContext() + .getAdditionalContext().get("locked").toUpperCase())); + } + RpcResult result = RpcResultBuilder.status(true) + .withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + @Override + public Future> configBackup(ConfigBackupInput input) { + logger.debug("Input received : " + input.toString()); + ConfigBackupOutputBuilder outputBuilder = new ConfigBackupOutputBuilder(); + String action = Action.ConfigBackup.toString() ; + String rpcName = Action.ConfigBackup.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> configBackupDelete(ConfigBackupDeleteInput input) { + logger.debug("Input received : " + input.toString()); + ConfigBackupDeleteOutputBuilder outputBuilder = new ConfigBackupDeleteOutputBuilder(); + String action = Action.ConfigBackupDelete.toString() ; + String rpcName = Action.ConfigBackupDelete.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + + @Override + public Future> configExport(ConfigExportInput input) { + logger.debug("Input received : " + input.toString()); + ConfigExportOutputBuilder outputBuilder = new ConfigExportOutputBuilder(); + String action = Action.ConfigExport.toString() ; + String rpcName = Action.ConfigExport.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + @Override + public Future> startApplication(StartApplicationInput input) { + logger.debug("Input received : " + input.toString()); + + StartApplicationOutputBuilder outputBuilder = new StartApplicationOutputBuilder(); + String action = Action.StartApplication.toString() ; + String rpcName = Action.StartApplication.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext() + .commonHeader(input.getCommonHeader()) + .actionIdentifiers(input.getActionIdentifiers()) + .payload(input.getPayload()) + .action(action) + .rpcName(rpcName) + .build(); + + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + @Override + public Future> stopApplication(StopApplicationInput input){ + logger.debug("Input received : " + input.toString()); + StopApplicationOutputBuilder outputBuilder = new StopApplicationOutputBuilder(); + String action = Action.StopApplication.toString() ; + String rpcName = Action.StopApplication.name().toLowerCase(); + Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); + if(null == status) { + try { + RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); + status = buildStatusWithDispatcherOutput(executeRequest(request)); + logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); + } catch (ParseException e) { + status = buildParsingErrorStatus(e); + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.APPC_PROVIDER, + String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), + this.getClass().getName()); + + } + } + outputBuilder.setCommonHeader(input.getCommonHeader()); + outputBuilder.setStatus(status); + RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); + return Futures.immediateFuture(result); + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } + + RequestHandlerOutput executeRequest(RequestHandlerInput request){ + RequestHandler handler = getRequestHandler(request.getRequestContext().getActionLevel()); + RequestHandlerOutput requestHandlerOutput; + if (handler != null) { + try { + requestHandlerOutput = handler.handleRequest(request); + } catch (Exception e) { + logger.info("UNEXPECTED FAILURE while executing " + request.getRequestContext().getAction().name()); + requestHandlerOutput = createErrorRequestHandlerObj(request, + LCMCommandStatus.UNEXPECTED_ERROR, Msg.EXCEPTION_CALLING_DG, e); + } + } else { + String errorMsg = "LCM request cannot be processed at the moment because APPC isn't running"; + requestHandlerOutput = createErrorRequestHandlerObj(request, + LCMCommandStatus.REJECTED, Msg.REQUEST_HANDLER_UNAVAILABLE, new APPCException(errorMsg)); + } + return requestHandlerOutput; + } +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/ResponseHeaderBuilder.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/ResponseHeaderBuilder.java new file mode 100644 index 000000000..7c479ddc0 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/ResponseHeaderBuilder.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.TIMESTAMP; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeaderBuilder; +import org.onap.appc.util.Time; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + + +/** + * Builds the responses from the APP-C services according to the YANG domainmodel + * + * @since Nov 16, 2015 + * @version $Id$ + */ +public class ResponseHeaderBuilder { + + /** + * The date/time formatter to format timestamps. + */ + @SuppressWarnings("nls") + public static final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); + public static final DateFormat ZULU_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); + + /** + * Private default constructor prevents instantiation + */ + private ResponseHeaderBuilder() { + } + + /** + * This method builds the common response header and returns it to the caller for integration into the response + * + * @param success + * True or false indicating the outcome of the operation. True indicates that the operation was + * successful, false indicates it failed. + * @param requestId + * The original request id for the service + * @param reason + * The reason for the failure if the success flag is false. If success is true, the reason is not used. + * @param duration + * The duration of the request processing + * @return The common response header to be returned to the caller. + */ + @SuppressWarnings("nls") + public static CommonResponseHeader buildHeader(Boolean success, String requestId, String reason, long duration) { + CommonResponseHeaderBuilder builder = new CommonResponseHeaderBuilder(); + + TIMESTAMP timestamp = new TIMESTAMP(FORMATTER.format(Time.utcDate())); + builder.setServiceRequestId(requestId); + builder.setCompleted(timestamp); + builder.setDuration(duration); + builder.setSuccess(success); + + if (success.equals(Boolean.TRUE)) { + builder.setReason("Success"); + } else { + builder.setReason(reason); + } + + return builder.build(); + } + + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/LCMConstants.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/LCMConstants.java new file mode 100644 index 000000000..40e632e7f --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/LCMConstants.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider.lcm.util; + +public final class LCMConstants { + private LCMConstants() { + } + + public static final String CODE = "Status"; + public static final String VALUE = "Value"; + //flags + public static final String FORCE = "FORCE"; + public static final String MODE = "MODE"; + public static final String TTL = "TTL"; + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/RequestInputBuilder.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/RequestInputBuilder.java new file mode 100644 index 000000000..979c834de --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/RequestInputBuilder.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider.lcm.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.TimeZone; + +import org.apache.commons.lang.StringUtils; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Payload; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiers; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; +import org.onap.appc.domainmodel.lcm.Flags.Mode; +import org.onap.appc.domainmodel.lcm.ActionLevel; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + + +public class RequestInputBuilder { + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + private static final String FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + + private RequestContext requestContext; + private String rpcName; + + public RequestInputBuilder() { + } + + + public RequestInputBuilder requestContext() { + this.requestContext = new RequestContext(); + return this; + } + + public RequestInputBuilder action(String action) { + this.requestContext.setAction(VNFOperation.findByString(action)); + return this; + } + + + public RequestInputBuilder additionalContext(String key, String value) { + this.requestContext.addKeyValueToAdditionalContext(key, value); + return this; + } + + public RequestInputBuilder payload(Payload payload) { + if (payload != null) { + this.requestContext.setPayload(payload.getValue()); + } + return this; + } + + public RequestHandlerInput build (){ + RequestHandlerInput request = new RequestHandlerInput(); + request.setRequestContext(this.requestContext); + request.setRpcName(rpcName); + return request; + } + + public RequestInputBuilder rpcName(String rpcName) { + this.rpcName = rpcName; + return this; + } + + public RequestInputBuilder commonHeader(CommonHeader commonHeader) throws ParseException { + org.onap.appc.domainmodel.lcm.CommonHeader header = new org.onap.appc.domainmodel.lcm.CommonHeader(); + this.requestContext.setCommonHeader(header); + + try { + if(null != commonHeader.getTimestamp()) { + SimpleDateFormat format = new SimpleDateFormat(FORMAT); + format.setLenient(false); + format.setTimeZone(TimeZone.getTimeZone("UTC")); + header.setTimestamp(format.parse(commonHeader.getTimestamp().getValue()).toInstant()); + }else{ + throw new ParseException("Missing mandatory parameter : timestamp " , 0); + } + } catch (ParseException e) { + logger.error(String.format("DATE format is incorrect: %s", e.getMessage())); + throw e; + } + header.setApiVer(commonHeader.getApiVer()); + header.setRequestId(commonHeader.getRequestId()); + header.setOriginatorId(commonHeader.getOriginatorId()); + header.setSubRequestId(commonHeader.getSubRequestId()); + + Flags inFlags = commonHeader.getFlags(); + boolean force = false; + Mode mode = null; + int ttl = 0; + if (inFlags != null) { + + if (null != inFlags.getForce()) { + force = Boolean.parseBoolean(inFlags.getForce().toString().toLowerCase()); + } + if (null != inFlags.getMode()) { + mode = Mode.valueOf(inFlags.getMode().name()); + } + if (null != inFlags.getTtl()) { + ttl = inFlags.getTtl(); + } + + } + this.requestContext.getCommonHeader().setFlags(new org.onap.appc.domainmodel.lcm.Flags(mode, force, ttl)); + return this; + } + + public RequestInputBuilder actionIdentifiers(ActionIdentifiers actionIdentifiers) throws ParseException { + if(null!= actionIdentifiers) { + org.onap.appc.domainmodel.lcm.ActionIdentifiers actionIds = new org.onap.appc.domainmodel.lcm.ActionIdentifiers(); + actionIds.setServiceInstanceId(actionIdentifiers.getServiceInstanceId()); + actionIds.setVnfcName(actionIdentifiers.getVnfcName()); + actionIds.setvServerId(actionIdentifiers.getVserverId()); + actionIds.setVnfId(actionIdentifiers.getVnfId()); + actionIds.setVfModuleId(actionIdentifiers.getVfModuleId()); + this.requestContext.setActionIdentifiers(actionIds); + + ActionLevel actionLevel = readActionLevel(actionIds); + this.requestContext.setActionLevel(actionLevel); + return this; + }else{ + throw new ParseException("Missing action identifier" , 0); + } + } + + private ActionLevel readActionLevel(org.onap.appc.domainmodel.lcm.ActionIdentifiers actionIds) { + if(!StringUtils.isEmpty(actionIds.getVserverId())){ + return ActionLevel.VM; + } + return ActionLevel.VNF; + } + + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/ValidationService.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/ValidationService.java new file mode 100644 index 000000000..69e100b57 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/lcm/util/ValidationService.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider.lcm.util; + +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; + +import javax.swing.*; + + + +public class ValidationService { + + private static class ValidationServiceHolder { + private static final ValidationService INSTANCE = new ValidationService(); + } + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ValidationService.class); + + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + public static ValidationService getInstance(){ + return ValidationServiceHolder.INSTANCE; + } + + public Status validateInput (CommonHeader commonHeader, Action action , String rpcName) { + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String reason ; + StringBuilder paramName = new StringBuilder(""); + if (!isEmpty(commonHeader) && !isEmpty(commonHeader.getApiVer())&& !isEmpty(commonHeader.getTimestamp()) && !isEmpty(commonHeader.getRequestId()) && !isEmpty(action) && !isEmpty(commonHeader.getOriginatorId())){ + if(!action.toString().equalsIgnoreCase(rpcName)) logger.warn("action in input request '" + action.toString() + "' is different from endpoint '" + rpcName + "'"); + return null; + } else{ + if(isEmpty(commonHeader)){ + paramName.append("common-header"); + }else{ + if (isEmpty(commonHeader.getApiVer())) paramName.append("api-ver"); + if (isEmpty(commonHeader.getTimestamp())) paramName.append(isEmpty(paramName) ? "timestamp" : " , timestamp" ); + if (isEmpty(commonHeader.getRequestId())) paramName.append(isEmpty(paramName) ? "request-id" : " , request-id" ); + if (isEmpty(commonHeader.getOriginatorId())) paramName.append(isEmpty(paramName) ? "originator-id" : " , originator-id" ); + } + if (isEmpty(action)) paramName.append(isEmpty(paramName) ? "action" : " , action" ); + } + + + + reason = EELFResourceManager.format(Msg.NULL_OR_INVALID_ARGUMENT, appName, rpcName, paramName.toString() , ""); + logger.info("Mandatory parameter/s" + paramName.toString() + " is/are missing"); + logger.error(reason); + LCMCommandStatus lcmCommandStatus = LCMCommandStatus.MISSING_MANDATORY_PARAMETER; + Params params = new Params().addParam("paramName", paramName.toString()); + StatusBuilder status = new StatusBuilder(); + status.setCode(lcmCommandStatus.getResponseCode()); + status.setMessage(lcmCommandStatus.getFormattedMessage(params)); + return status.build(); + } + + private boolean isEmpty (Object object){ + return (null == object || "".equalsIgnoreCase(object.toString())); + } +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/topology/TopologyService.java b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/topology/TopologyService.java new file mode 100644 index 000000000..ea1d3f1ee --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/onap/appc/provider/topology/TopologyService.java @@ -0,0 +1,800 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider.topology; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +import java.net.InetAddress; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; +import java.util.TimeZone; + +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.UUID; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutputBuilder; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.onap.appc.provider.AppcProvider; +import org.onap.appc.provider.AppcProviderClient; +import org.onap.appc.provider.ResponseHeaderBuilder; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.slf4j.MDC; + +/** + * This class is used to implement the topology services API and invoke the appropriate directed graphs based on the + * service being requested. + * + */ +public class TopologyService { + + /** + * The loggers we are using + */ + // private static EELFLogger logger = LoggerFactory.getLogger(TopologyService.class); + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static EELFLogger performanceLogger = EELFManager.getInstance().getPerformanceLogger(); + + /** + * The provider we are servicing + */ + private AppcProvider provider; + + /** + * The reason associated with the last DG call + */ + private String reason; + + /** + * The APPC configuration properties + */ + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * Create the topology services implementation for the specific appc provider (api) implementation + * + * @param provider + * The provider we are servicing + */ + public TopologyService(AppcProvider provider) { + this.provider = provider; + } + + // /** + // * Processes the topology request + // * + // * @param input + // * The request to be processed + // * @return The result of processing + // */ + // public RpcResult process(TopologyOperationInput input) { + // RpcResult response; + // + // String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + // logger.info(String.format("%s:topology operations called...", appName)); + // + // /* + // * Properties used to pass information to the DG + // */ + // Properties properties = new Properties(); + // + // if (input == null || input.getTopologyRequest().getVmId() == null) { + // String msg = + // String.format("%s: topology operation failed, invalid input. Null or empty argument '%s'", appName, + // "vm_id"); + // logger.debug(msg); + // response = generateTopologyOperationResponse(Boolean.FALSE, "UNKNOWN", msg, "UNDEFINED"); + // } else { + // // CommonRequestHeader crh = input.getCommonRequestHeader(); + // TopologyHeader hdr = input.getTopologyHeader(); + // TopologyRequest req = input.getTopologyRequest(); + // + // // String requestId = crh.getServiceRequestId(); + // String requestId = hdr.getSvcRequestId(); + // properties.put(Constants.CONTEXT_REQID, requestId); + // + // String infomsg = String.format("Topology request '%s' (%s) received.", requestId, hdr.getSvcAction()); + // + // // switch (req.getSvcAction()) { + // switch (hdr.getSvcAction()) { + // case Restart: + // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_RESTART); + // response = restart(input, properties); + // logger.info(infomsg); + // break; + // + // case Rebuild: + // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_REBUILD); + // response = rebuild(input, properties); + // logger.info(infomsg); + // break; + // + // default: + // String msg = String.format("Invalid request type [%s] for request id [%s]", req, requestId); + // response = generateTopologyOperationResponse(Boolean.FALSE, requestId, msg, "N/A"); + // } + // } + // + // return response; + // } + + /** + * Restart a VM + * + * @param hdr + * The common request header + * @param vnf + * The identification of the VNF resource to be operated upon + * @return The rpc result of the restart operation + */ + public RpcResult modifyConfig(CommonRequestHeader hdr, ConfigPayload data) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + df.setTimeZone(tz); + // String startTimeStr = String.valueOf(startTime); + String startTimeStr = df.format(new Date()); + String requestId = hdr.getServiceRequestId(); + + //MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + MDC.put("startTime", Long.toString(startTime)); + MDC.put("target", "appc"); + logger.info(String.format("Starting RESTART for request with id [%s]", requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", + startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + //UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "modifyConfig"); + properties.put(Constants.CONTEXT_REQID, requestId); + //properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + String url = configuration.getProperty("appc.provider.vfodl.url"); + try{ + if(url.contains("NODE_NAME")){ + url = url.replace("NODE_NAME", data.getConfigUrl()); + } + }catch(Exception e){ + url = configuration.getProperty("appc.provider.vfodl.url"); + } + logger.trace("Final URL to VF ODL: "+url); + properties.put("org.onap.appc.configURL", url); + properties.put("org.onap.appc.configJson", data.getConfigJson()); + + //UUID identityUrl = vnf.getIdentityUrl(); + //if (identityUrl != null) { + // properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + //} + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + + MDC.put("target", "appc"); + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("APPC0119I ModifyConfig '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + + ModifyConfigOutputBuilder rob = new ModifyConfigOutputBuilder(); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + MDC.put("endTime", endTimeStr); + MDC.put("duration", durationStr); + rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + //rob.setVmId(new UUID(vmId)); + + auditLogger.info(String.format( + "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + metricsLogger.info(String.format( + "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(rob.build()).build(); + return rpcResult; + + } + + + + + /** + * Restart a VM + * + * @param hdr + * The common request header + * @param vnf + * The identification of the VNF resource to be operated upon + * @return The rpc result of the restart operation + */ + public RpcResult migrate(CommonRequestHeader hdr, VnfResource vnf) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + df.setTimeZone(tz); + // String startTimeStr = String.valueOf(startTime); + String startTimeStr = df.format(new Date()); + String requestId = hdr.getServiceRequestId(); + + //MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:Migrate"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + MDC.put("startTime", startTimeStr); + MDC.put("target", "appc"); + logger.info(String.format("Starting ANY for request with id [%s]", requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", + startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "migrate"); + properties.put(Constants.CONTEXT_REQID, requestId); + properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + + UUID identityUrl = vnf.getIdentityUrl(); + if (identityUrl != null) { + properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + } + + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + /* + * Generate the appropriate response + */ + MDC.put("target", "appc"); + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("APPC0118I Migrate '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + + MigrateOutputBuilder mob = new MigrateOutputBuilder(); + + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + MDC.put("endTime", endTimeStr); + MDC.put("duration", durationStr); + mob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + mob.setVmId(new UUID(vmId)); + + auditLogger.info(String.format( + "Audit Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + metricsLogger.info(String.format( + "Metrics Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(mob.build()).build(); + return rpcResult; + } + + /** + * Restart a VM + * + * @param hdr + * The common request header + * @param vnf + * The identification of the VNF resource to be operated upon + * @return The rpc result of the restart operation + */ + public RpcResult restart(CommonRequestHeader hdr, VnfResource vnf) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + df.setTimeZone(tz); + // String startTimeStr = String.valueOf(startTime); + String startTimeStr = df.format(new Date()); + String requestId = hdr.getServiceRequestId(); + + //MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + MDC.put("startTime", Long.toString(startTime)); + MDC.put("target", "appc"); + logger.info(String.format("Starting RESTART for request with id [%s]", requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", + startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "restart"); + properties.put(Constants.CONTEXT_REQID, requestId); + properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + + UUID identityUrl = vnf.getIdentityUrl(); + if (identityUrl != null) { + properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + } + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + /* + * Generate the appropriate response + */ + MDC.put("target", "appc"); + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("APPC0119I Restart '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + + RestartOutputBuilder rob = new RestartOutputBuilder(); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + MDC.put("endTime", endTimeStr); + MDC.put("duration", durationStr); + rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + rob.setVmId(new UUID(vmId)); + + auditLogger.info(String.format( + "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + metricsLogger.info(String.format( + "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(rob.build()).build(); + return rpcResult; + } + + /** + * Rebuild a VM + * + * @param hdr + * The common request header + * @param vnf + * The identification of the VNF resource to be operated upon + * @return The rpc result of the rebuild operation + */ + public RpcResult rebuild(CommonRequestHeader hdr, VnfResource vnf) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + df.setTimeZone(tz); + // String startTimeStr = String.valueOf(startTime); + String startTimeStr = df.format(new Date()); + String requestId = hdr.getServiceRequestId(); + + //MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:Rebuild"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + MDC.put("startTime", startTimeStr); + MDC.put("target", "appc"); + logger.info(String.format("Starting REBUILD for request with id [%s]", requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", + startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "rebuild"); + properties.put(Constants.CONTEXT_REQID, requestId); + properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + + UUID identityUrl = vnf.getIdentityUrl(); + if (identityUrl != null) { + properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + } + + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + /* + * Generate the appropriate response + */ + MDC.put("target", "appc"); + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("APPC0120I Rebuild '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + + RebuildOutputBuilder rob = new RebuildOutputBuilder(); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + MDC.put("endTime", endTimeStr); + MDC.put("duration", durationStr); + rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + rob.setOriginalVmId(new UUID(vmId)); + rob.setNewVmId(new UUID(vmId)); + + auditLogger.info(String.format( + "Audit Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + metricsLogger.info(String.format( + "Metrics Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(rob.build()).build(); + return rpcResult; + } + + /** + * Snapshot a VM + * + * @param hdr + * The common request header + * @param vnf + * The identification of the VNF resource to be operated upon + * @return The rpc result of the restart operation + */ + public RpcResult snapshot(CommonRequestHeader hdr, VnfResource vnf) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + df.setTimeZone(tz); + // String startTimeStr = String.valueOf(startTime); + String startTimeStr = df.format(new Date()); + String requestId = hdr.getServiceRequestId(); + + //MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:Snapshot"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + MDC.put("startTime", Long.toString(startTime)); + MDC.put("target", "appc"); + logger.info(String.format("Starting SNAPSHOT for request with id [%s]", requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C Snapshot initiated. Start Time: [%s]. Request ID: [%s]", + startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "snapshot"); + properties.put(Constants.CONTEXT_REQID, requestId); + properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + + UUID identityUrl = vnf.getIdentityUrl(); + if (identityUrl != null) { + properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + } + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + /* + * Generate the appropriate response + */ + MDC.put("target", "appc"); + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("APPC0119I Snapshot '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + + SnapshotOutputBuilder sob = new SnapshotOutputBuilder(); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String endTimeStr = String.valueOf(endTime); + String durationStr = String.valueOf(duration); + MDC.put("endTime", endTimeStr); + MDC.put("duration", durationStr); + sob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + sob.setVmId(new UUID(vmId)); + + auditLogger.info(String.format( + "Audit Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + metricsLogger.info(String.format( + "Metrics Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", + requestId, statusStr, startTime, endTime, duration, requestId, reason)); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(sob.build()).build(); + return rpcResult; + } + +/**************************************************/ + + public RpcResult vmstatuscheck(CommonRequestHeader hdr, VnfResource vnf) { + long startTime = System.currentTimeMillis(); + String requestId = hdr.getServiceRequestId(); + + MDC.clear(); + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, requestId); + MDC.put(MDC_SERVICE_NAME, "App-C Provider:vmstatuscheck"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + e.printStackTrace(); + } + MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); + MDC.put(MDC_ALERT_SEVERITY, "0"); + logger.info(String.format("Starting VMSTATUSCHECK for request with id [%s]", requestId)); + + performanceLogger.info(String.format("Performance Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); + auditLogger.info(String.format("Audit Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); + metricsLogger.info(String.format("Metrics Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); + + /* + * Copy any needed inputs or other values into the properties to be passed to the DG model + */ + UUID vmId = vnf.getVmId(); + Properties properties = new Properties(); + properties.put(Constants.CONTEXT_ACTION, "vmstatuschecking"); + properties.put(Constants.CONTEXT_REQID, requestId); + properties.put(Constants.CONTEXT_VMID, vmId.getValue()); + properties.put(Constants.STATUS_GETTER, "checking"); + + + + + UUID identityUrl = vnf.getIdentityUrl(); + if (identityUrl != null) { + properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); + } + /* + * Attempt to call the DG with the appropriate properties + */ + boolean success = callGraph(properties); + + /* + * Generate the appropriate response + */ + String statusStr = success ? "SUCCESS" : "FAILURE"; + String infomsg = + String.format("VMSTATUSCHECK '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); + logger.info(infomsg); + long endTime = System.currentTimeMillis(); + auditLogger.info(String.format("Audit Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason)); + metricsLogger.info(String.format("Metrics Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason)); + //logger.info(String.format("Step1 [%s]", Constants.STATUS_GETTER)); + String tempstring2 = properties.getProperty(Constants.STATUS_GETTER).trim(); + //logger.info(String.format("Step2 [%s]", tempstring2)); + + + VmstatuscheckOutputBuilder vob = new VmstatuscheckOutputBuilder(); + long duration = System.currentTimeMillis() - startTime; + vob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); + vob.setStatMsg(tempstring2); + + // Status must be set to true to indicate that our return is expected + RpcResult rpcResult = + RpcResultBuilder. status(true).withResult(vob.build()).build(); + return rpcResult; + } + + /*************************************************/ + + + + private boolean callGraph(Properties props) { + String moduleName = configuration.getProperty(Constants.PROPERTY_MODULE_NAME); + String methodName = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_METHOD); + String version = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_VERSION); + String mode = Constants.SYNC_MODE; + return callGraph(moduleName, methodName, version, mode, props); + } + + /** + * Calls a specified directed graph with the specified properties and returns the response + * + * @param module + * The module name to be used to locate the graph + * @param method + * The method name to be executed (rpc) + * @param version + * The version of the graph to be used, or null for the latest + * @param mode + * the execution mode of the graph, sync or async + * @param props + * A set of name-value properties to be passed to the graph for context variables. + */ + private boolean callGraph(String module, String method, String version, String mode, Properties props) { + String graphName = String.format(("%s:%s:%s"), module, method, version); + logger.debug(String.format("Calling Graph %s", graphName)); + metricsLogger.info(String.format("Calling Graph %s", graphName)); + + boolean success = false; + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + AppcProviderClient svcLogicClient = new AppcProviderClient(); + try { + if (svcLogicClient.hasGraph(module, method, version, mode)) { + try { + Properties respProps = svcLogicClient.execute(module, method, version, mode, props); + success = false; // Assume it failed unless proven otherwise + reason = "Failed"; // Assume it failed unless proven otherwise + + logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_HEADER, appName, graphName, + Integer.toString(respProps.size()))); + for (String key : respProps.stringPropertyNames()) { + logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_DETAIL, appName, graphName, + key, (String) respProps.get(key))); + } + + // TODO - Find docs and see if there is a better way to handle this + // Bad requests have errors + if (respProps.containsKey(Constants.ATTRIBUTE_ERROR_CODE)) { + // || respProps.containsKey(Constants.ATTRIBUTE_ERROR_MESSAGE)) { + String errorCodeProperty = respProps.getProperty(Constants.ATTRIBUTE_ERROR_CODE).trim(); + int errorCode = 200; + try { + errorCode = Integer.parseInt(errorCodeProperty); + if (errorCode >= 300) { + reason = EELFResourceManager.format(Msg.DG_FAILED_RESPONSE, appName, graphName, + errorCodeProperty, respProps.getProperty(Constants.ATTRIBUTE_ERROR_MESSAGE)); + logger.error(reason); + success = false; + } else { + success = true; + reason = "Success"; + } + } catch (NumberFormatException e) { + reason = EELFResourceManager.format(Msg.PARAMETER_NOT_NUMERIC, appName, graphName, + Constants.ATTRIBUTE_ERROR_CODE, errorCodeProperty); + logger.error(reason); + success = false; + } + } else { + /* + * Added code that requires error code to now be defined in ALL cases. If not, it is an error + * and the response will be set to failed regardless if the DG worked or not. + */ + reason = EELFResourceManager.format(Msg.PARAMETER_IS_MISSING, appName, graphName, + Constants.ATTRIBUTE_ERROR_CODE); + logger.error(reason); + success = false; + } + } catch (Exception e) { + success = false; + reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName, + e.getClass().getSimpleName(), graphName, e.getMessage()); + logger.error(reason); + } + } else { + success = false; + reason = EELFResourceManager.format(Msg.GRAPH_NOT_FOUND, appName, graphName); + logger.error(reason); + } + } catch (Exception e) { + success = false; + reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName, e.getClass().getSimpleName(), + graphName, e.getMessage()); + logger.error(reason); + } + + return success; + } + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModule.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModule.java new file mode 100644 index 000000000..e2fef3447 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModule.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523; + +import org.onap.appc.provider.AppcProvider; + +/** + * This was generated code. It was generated into the source tree because it has to be manually modified. + * + */ +public class AppcProviderModule extends + org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule { + + /** + * @param identifier + * @param dependencyResolver + */ + @SuppressWarnings("javadoc") + public AppcProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, + org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + /** + * @param identifier + * @param dependencyResolver + * @param oldModule + * @param oldInstance + */ + @SuppressWarnings("javadoc") + public AppcProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, + org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, + org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AppcProviderModule oldModule, + java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + /** + * @see org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule#customValidation() + */ + @Override + public void customValidation() { + // add custom validation form module attributes here. + } + + /** + * This method is manually updated to actually invoke the provider implementation + * + * @see org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule#createInstance() + */ + @Override + public java.lang.AutoCloseable createInstance() { + + final AppcProvider provider = + new AppcProvider(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); + return new AutoCloseable() { + + @Override + public void close() throws Exception { + provider.close(); + } + }; + + } + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModuleFactory.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModuleFactory.java new file mode 100644 index 000000000..3623c2623 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/impl/rev140523/AppcProviderModuleFactory.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/** + * Generated file Generated from: yang module name: appc-provider-impl yang module local name: appc-provider-impl + * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator Generated at: Tue Sep 01 + * 13:56:34 CDT 2015 Do not modify this file unless it is present under src/main directory + */ +package org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523; + +/** + * Generated code + * + */ +public class AppcProviderModuleFactory extends + org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModuleFactory { + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java new file mode 100644 index 000000000..41362624e --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108; + +import org.onap.appc.provider.AppcProviderLcm; + +public class AppcProviderLcmModule extends org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AbstractAppcProviderLcmModule { + public AppcProviderLcmModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public AppcProviderLcmModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AppcProviderLcmModule oldModule, java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void customValidation() { + // add custom validation form module attributes here. + } + + @Override + public java.lang.AutoCloseable createInstance() { + final AppcProviderLcm provider = + new AppcProviderLcm(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); + return new AutoCloseable() { + + @Override + public void close() throws Exception { + provider.close(); + } + }; + } + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java new file mode 100644 index 000000000..b2046de47 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +/* +* Generated file +* +* Generated from: yang module name: appc-provider-lcm-impl yang module local name: appc-provider-lcm-impl +* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator +* Generated at: Tue Aug 16 10:40:21 IDT 2016 +* +* Do not modify this file unless it is present under src/main directory +*/ +package org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108; +public class AppcProviderLcmModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AbstractAppcProviderLcmModuleFactory { + +} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModule.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModule.java deleted file mode 100644 index e2fef3447..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModule.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523; - -import org.onap.appc.provider.AppcProvider; - -/** - * This was generated code. It was generated into the source tree because it has to be manually modified. - * - */ -public class AppcProviderModule extends - org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule { - - /** - * @param identifier - * @param dependencyResolver - */ - @SuppressWarnings("javadoc") - public AppcProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, - org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - /** - * @param identifier - * @param dependencyResolver - * @param oldModule - * @param oldInstance - */ - @SuppressWarnings("javadoc") - public AppcProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, - org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, - org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AppcProviderModule oldModule, - java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - /** - * @see org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule#customValidation() - */ - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - /** - * This method is manually updated to actually invoke the provider implementation - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModule#createInstance() - */ - @Override - public java.lang.AutoCloseable createInstance() { - - final AppcProvider provider = - new AppcProvider(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); - return new AutoCloseable() { - - @Override - public void close() throws Exception { - provider.close(); - } - }; - - } - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModuleFactory.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModuleFactory.java deleted file mode 100644 index 3623c2623..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/impl/rev140523/AppcProviderModuleFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/** - * Generated file Generated from: yang module name: appc-provider-impl yang module local name: appc-provider-impl - * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator Generated at: Tue Sep 01 - * 13:56:34 CDT 2015 Do not modify this file unless it is present under src/main directory - */ -package org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523; - -/** - * Generated code - * - */ -public class AppcProviderModuleFactory extends - org.opendaylight.yang.gen.v1.org.onap.appc.provider.impl.rev140523.AbstractAppcProviderModuleFactory { - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java deleted file mode 100644 index 41362624e..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModule.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108; - -import org.onap.appc.provider.AppcProviderLcm; - -public class AppcProviderLcmModule extends org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AbstractAppcProviderLcmModule { - public AppcProviderLcmModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public AppcProviderLcmModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AppcProviderLcmModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - final AppcProviderLcm provider = - new AppcProviderLcm(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); - return new AutoCloseable() { - - @Override - public void close() throws Exception { - provider.close(); - } - }; - } - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java b/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java deleted file mode 100644 index b2046de47..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/provider/lcm/impl/rev160108/AppcProviderLcmModuleFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -/* -* Generated file -* -* Generated from: yang module name: appc-provider-lcm-impl yang module local name: appc-provider-lcm-impl -* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator -* Generated at: Tue Aug 16 10:40:21 IDT 2016 -* -* Do not modify this file unless it is present under src/main directory -*/ -package org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108; -public class AppcProviderLcmModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.provider.lcm.impl.rev160108.AbstractAppcProviderLcmModuleFactory { - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProvider.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProvider.java deleted file mode 100644 index 990576422..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProvider.java +++ /dev/null @@ -1,261 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.util.concurrent.Futures; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import org.onap.appc.provider.topology.TopologyService; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -/* ADDED FOR FUSION SERVICE CODE */ - -@SuppressWarnings("JavaDoc") -/** - * Defines the APPC service provider. - *

- * The rpc definition in the YANG model is shown below. This model is used to generate code to manage the inputs and - * outputs of the RPC service. For example, the input is defined by a class named {@link ConfigurationOperationInput}, - * which is generated from the name of the RPC and the "input" definition of the RPC. This class encapsulates the - * various objects that are passed to the RPC and is used to obtain values from the input parameters. - *

- *

- * Likewise, the outputs are defined by a class named {@link ConfigurationOperationOutput}. This class encapsulates the - * defined outputs. To make construction of the outputs easier, there are also generated builder classes that are named - * for the various elements of the output they "build", such as {@link ConfigurationResponseBuilder}. - *

- * - *
- *   rpc configuration-operation {
- *      description "An operation to view, change, or audit the configuration of a VM";
- *      input {
- *          uses configuration-request-header;
- *          uses configuration-request;
- *      }
- *      output {
- *          uses common-response-header;
- *          uses configuration-response;
- *      }
- *  }
- * 
- * - */ -public class AppcProvider implements AutoCloseable, AppcProviderService { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderClient.class); - - private final ExecutorService executor; - - /** - * The ODL data store broker. Provides access to a conceptual data tree store and also provides the ability to - * subscribe for changes to data under a given branch of the tree. - */ - protected DataBroker dataBroker; - - /** - * ODL Notification Service that provides publish/subscribe capabilities for YANG modeled notifications. - */ - protected NotificationProviderService notificationService; - - /** - * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are defined in YANG models. - */ - protected RpcProviderRegistry rpcRegistry; - - /** - * Represents our RPC implementation registration - */ - protected BindingAwareBroker.RpcRegistration rpcRegistration; - - /** - * The configuration - */ - private Configuration configuration = ConfigurationFactory.getConfiguration(); - - /** - * @param dataBroker2 - * @param notificationProviderService - * @param rpcProviderRegistry - */ - @SuppressWarnings({ - "javadoc", "nls" - }) - public AppcProvider(DataBroker dataBroker2, NotificationProviderService notificationProviderService, - RpcProviderRegistry rpcProviderRegistry) { - - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - logger.info(Msg.COMPONENT_INITIALIZING, appName, "provider"); - - executor = Executors.newFixedThreadPool(1); - dataBroker = dataBroker2; - notificationService = notificationProviderService; - rpcRegistry = rpcProviderRegistry; - - if (rpcRegistry != null) { - rpcRegistration = rpcRegistry.addRpcImplementation(AppcProviderService.class, this); - } - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "provider"); - } - - /** - * Implements the close of the service - * - * @see java.lang.AutoCloseable#close() - */ - @SuppressWarnings("nls") - @Override - public void close() throws Exception { - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - logger.info(Msg.COMPONENT_TERMINATING, appName, "provider"); - executor.shutdown(); - if (rpcRegistration != null) { - rpcRegistration.close(); - } - logger.info(Msg.COMPONENT_TERMINATED, appName, "provider"); - } - - public Future> modifyConfig(ModifyConfigInput input) { - CommonRequestHeader hdr = input.getCommonRequestHeader(); - ConfigPayload data = input.getConfigPayload(); - RpcResult result = getTopologyService().modifyConfig(hdr, data); - return Futures.immediateFuture(result); - } - - /** - * Rebuilds a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#rebuild(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput) - */ - @Override - public Future> rebuild(RebuildInput input) { - - CommonRequestHeader hdr = input.getCommonRequestHeader(); - VnfResource vnf = input.getVnfResource(); - - RpcResult result = getTopologyService().rebuild(hdr, vnf); - return Futures.immediateFuture(result); - } - - /** - * Restarts a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#restart(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput) - */ - @Override - public Future> restart(RestartInput input) { - CommonRequestHeader hdr = input.getCommonRequestHeader(); - VnfResource vnf = input.getVnfResource(); - - RpcResult result = getTopologyService().restart(hdr, vnf); - return Futures.immediateFuture(result); - } - - /** - * Migrates a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#migrate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput) - */ - @Override - public Future> migrate(MigrateInput input) { - CommonRequestHeader hdr = input.getCommonRequestHeader(); - VnfResource vnf = input.getVnfResource(); - - RpcResult result = getTopologyService().migrate(hdr, vnf); - return Futures.immediateFuture(result); - } - - /** - * Evacuates a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#evacuate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput) - */ - @Override - public Future> evacuate(EvacuateInput input) { - - return null; - } - - /** - * Evacuates a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.AppcProviderService#evacuate(org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput) - */ - @Override - public Future> snapshot(SnapshotInput input) { - CommonRequestHeader hdr = input.getCommonRequestHeader(); - VnfResource vnf = input.getVnfResource(); - - RpcResult result = getTopologyService().snapshot(hdr, vnf); - return Futures.immediateFuture(result); - } - - /** - * Checks status of a VM - */ - @Override - public Future> vmstatuscheck(VmstatuscheckInput input) { - CommonRequestHeader hdr = input.getCommonRequestHeader(); - VnfResource vnf = input.getVnfResource(); - - TopologyService topology = getTopologyService(); - RpcResult result = getTopologyService().vmstatuscheck(hdr, vnf); - return Futures.immediateFuture(result); - } - - TopologyService getTopologyService() { - return new TopologyService(this); - } -} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderClient.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderClient.java deleted file mode 100644 index 6195521be..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderClient.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.onap.appc.util.StringHelper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.MDC; - -import static com.att.eelf.configuration.Configuration.*; - -import java.util.Properties; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -public class AppcProviderClient { - - private static EELFLogger LOG = EELFManager.getInstance().getApplicationLogger(); - private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - - private SvcLogicService svcLogic = null; - - public AppcProviderClient() { - BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext(); - //Handle BundleContext returning null - if (bctx == null){ - LOG.warn("Cannot find bundle context for " + SvcLogicService.NAME); - } - else{ - // Get SvcLogicService reference - ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); - if (sref != null) { - svcLogic = (SvcLogicService) bctx.getService(sref); - - } else { - LOG.warn("Cannot find service reference for " + SvcLogicService.NAME); - - } - } - } - - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { - LOG.debug(String.format("Checking for graph. %s %s %s %s", module, rpc, version, mode)); - return (svcLogic.hasGraph(module, rpc, version, mode)); - } - - public Properties execute(String module, String rpc, String version, String mode, Properties parms) - throws SvcLogicException { - - /* - * Set End time for Metrics Logger - */ - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - String startTimeStr = df.format(new Date()); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "sli"); - MDC.put("TargetServiceName", "execute"); - MDC.put("ClassName", "org.onap.appc.provider.AppcProviderClient"); - - LOG.debug("Parameters passed to SLI: " + StringHelper.propertiesToString(parms)); - metricsLogger.info("Parameters passed to SLI: " + StringHelper.propertiesToString(parms)); - - Properties respProps = svcLogic.execute(module, rpc, version, mode, parms); - - /* - * Set End time for Metrics Logger - */ - endTime = System.currentTimeMillis(); - duration = endTime - startTime; - endTimeStr = String.valueOf(endTime); - durationStr = String.valueOf(duration); - endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - - LOG.debug("Parameters returned by SLI: " + StringHelper.propertiesToString(respProps)); - metricsLogger.info("Parameters returned by SLI: " + StringHelper.propertiesToString(respProps)); - - return respProps; - } -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderLcm.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderLcm.java deleted file mode 100644 index 66e8909bd..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderLcm.java +++ /dev/null @@ -1,1208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import com.google.common.util.concurrent.Futures; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AppcProviderLcmService; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.ActionLevel; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.i18n.Msg; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.provider.lcm.util.RequestInputBuilder; -import org.onap.appc.provider.lcm.util.ValidationService; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; - -import java.text.ParseException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.Collection; - -public class AppcProviderLcm implements AutoCloseable, AppcProviderLcmService { - - private Configuration configuration = ConfigurationFactory.getConfiguration(); - private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderLcm.class); - - private final ExecutorService executor; - - private final String COMMON_ERROR_MESSAGE_TEMPLATE = "Error processing %s input : %s"; - - /** - * The ODL data store broker. Provides access to a conceptual data tree store and also provides the ability to - * subscribe for changes to data under a given branch of the tree. - */ - protected DataBroker dataBroker; - - /** - * ODL Notification Service that provides publish/subscribe capabilities for YANG modeled notifications. - */ - protected NotificationProviderService notificationService; - - /** - * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are defined in YANG models. - */ - protected RpcProviderRegistry rpcRegistry; - - /** - * Represents our RPC implementation registration - */ - protected BindingAwareBroker.RpcRegistration rpcRegistration; - - - /** - * @param dataBroker - * @param notificationProviderService - * @param rpcProviderRegistry - */ - @SuppressWarnings({ - "javadoc", "nls" - }) - public AppcProviderLcm(DataBroker dataBroker, NotificationProviderService notificationProviderService, - RpcProviderRegistry rpcProviderRegistry) { - - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - logger.info(Msg.COMPONENT_INITIALIZING, appName, "provider-lcm"); - - executor = Executors.newFixedThreadPool(1); - this.dataBroker = dataBroker; - this.notificationService = notificationProviderService; - this.rpcRegistry = rpcProviderRegistry; - - if (this.rpcRegistry != null) { - rpcRegistration = rpcRegistry.addRpcImplementation(AppcProviderLcmService.class, this); - } - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "provider"); - } - - /** - * Implements the close of the service - * - * @see java.lang.AutoCloseable#close() - */ - @SuppressWarnings("nls") - @Override - public void close() throws Exception { - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - logger.info(Msg.COMPONENT_TERMINATING, appName, "provider"); - executor.shutdown(); - if (rpcRegistration != null) { - rpcRegistration.close(); - } - logger.info(Msg.COMPONENT_TERMINATED, appName, "provider"); - } - - - /** - * Rebuilds a specific VNF - * - * @see AppcProviderLcmService#rebuild(RebuildInput) - */ - @Override - public Future> rebuild(RebuildInput input) { - logger.debug("Input received : " + input.toString()); - - RebuildOutputBuilder outputBuilder = new RebuildOutputBuilder(); - String action = Action.Rebuild.toString() ; - String rpcName = Action.Rebuild.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - /** - * Restarts a specific VNF - * - * @see org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AppcProviderLcmService#restart(RestartInput) - */ - @Override - public Future> restart(RestartInput input) { - logger.debug("Input received : " + input.toString()); - - RestartOutputBuilder outputBuilder = new RestartOutputBuilder(); - String action = Action.Restart.toString() ; - String rpcName = Action.Restart.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()) - .action(action) - .rpcName(rpcName) - .build(); - - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - /** - * Migrates a specific VNF - * - * @see AppcProviderLcmService#migrate(MigrateInput) - */ - @Override - public Future> migrate(MigrateInput input) { - logger.debug("Input received : " + input.toString()); - - MigrateOutputBuilder outputBuilder = new MigrateOutputBuilder(); - String action = Action.Migrate.toString() ; - String rpcName = Action.Migrate.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - /** - * Evacuates a specific VNF - * - * @see AppcProviderLcmService#evacuate(EvacuateInput) - */ - @Override - public Future> evacuate(EvacuateInput input) { - logger.debug("Input received : " + input.toString()); - - EvacuateOutputBuilder outputBuilder = new EvacuateOutputBuilder(); - String action = Action.Evacuate.toString() ; - String rpcName = Action.Evacuate.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - /** - * Evacuates a specific VNF - * - * @see AppcProviderLcmService#snapshot(SnapshotInput) - */ - @Override - public Future> snapshot(SnapshotInput input) { - logger.debug("Input received : " + input.toString()); - - SnapshotOutputBuilder outputBuilder = new SnapshotOutputBuilder(); - String action = Action.Snapshot.toString() ; - String rpcName = Action.Snapshot.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - String identityUrl = input.getIdentityUrl(); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName) - .additionalContext("identity-url", identityUrl).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> rollback(RollbackInput input) { - logger.debug("Input received : " + input.toString()); - - RollbackOutputBuilder outputBuilder = new RollbackOutputBuilder(); - String rpcName = Action.Rollback.toString() ; - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), rpcName); - String identityUrl = input.getIdentityUrl(); - String snapshotId = input.getSnapshotId(); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).additionalContext("identity-url", identityUrl) - .additionalContext("snapshot-id", snapshotId).action(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, rpcName, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> sync(SyncInput input) { - logger.debug("Input received : " + input.toString()); - SyncOutputBuilder outputBuilder = new SyncOutputBuilder(); - String action = Action.Sync.toString() ; - String rpcName = Action.Sync.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - private Status buildParsingErrorStatus(ParseException e){ - LCMCommandStatus requestParsingFailure = LCMCommandStatus.REQUEST_PARSING_FAILED; - String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - Params params = new Params().addParam("errorMsg", errorMessage); - return buildStatus(requestParsingFailure.getResponseCode(), requestParsingFailure.getFormattedMessage(params)); - } - - private Status buildStatus(Integer code,String message){ - StatusBuilder status = new StatusBuilder(); - status.setCode(code); - status.setMessage(message); - return status.build(); - } - - private Status buildStatusWithDispatcherOutput(RequestHandlerOutput requestHandlerOutput){ - Integer statusCode = requestHandlerOutput.getResponseContext().getStatus().getCode(); - String statusMessage = requestHandlerOutput.getResponseContext().getStatus().getMessage(); - return buildStatus(statusCode, statusMessage); - } - - private RequestHandlerOutput createErrorRequestHandlerObj(RequestHandlerInput request, - LCMCommandStatus cmdStatus, - Msg msg, - Exception e) { - final String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - final String reason = EELFResourceManager.format(msg, e, - appName, e.getClass().getSimpleName(), "", e.getMessage()); - - RequestHandlerOutput requestHandlerOutput = new RequestHandlerOutput(); - final ResponseContext responseContext = new ResponseContext(); - requestHandlerOutput.setResponseContext(responseContext); - responseContext.setCommonHeader(request.getRequestContext().getCommonHeader()); - - String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - Params params = new Params().addParam("errorMsg", errorMessage); - responseContext.setStatus(cmdStatus.toStatus(params)); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - reason, - this.getClass().getName()); - - return requestHandlerOutput; - } - - private RequestHandler getRequestHandler(ActionLevel actionLevel){ - final BundleContext context = FrameworkUtil.getBundle(RequestHandler.class).getBundleContext(); - if (context != null) { - String filter = null; - try { - filter = "(level=" + actionLevel.name() + ")"; - Collection> serviceReferences = context.getServiceReferences(RequestHandler.class, filter); - if (serviceReferences.size() != 1) { - logger.error("Cannot find service reference for " + RequestHandler.class.getName()); - throw new RuntimeException(); - } - ServiceReference serviceReference = serviceReferences.iterator().next(); - return context.getService(serviceReference); - } catch (InvalidSyntaxException e) { - logger.error("Cannot find service reference for " + RequestHandler.class.getName() + ": Invalid Syntax " + filter, e); - throw new RuntimeException(e); - } - } - return null; - } - - @Override - public Future> terminate(TerminateInput input) { - logger.debug("Input received : " + input.toString()); - TerminateOutputBuilder outputBuilder = new TerminateOutputBuilder(); - String action = Action.Terminate.toString() ; - String rpcName = Action.Terminate.name().toLowerCase(); - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = - RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> configure(ConfigureInput input) { - logger.debug("Input received : " + input.toString()); - ConfigureOutputBuilder outputBuilder = new ConfigureOutputBuilder(); - String action = Action.Configure.toString() ; - String rpcName = "configure"; - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = - RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> configModify(ConfigModifyInput input) { - logger.debug("Input received : " + input.toString()); - ConfigModifyOutputBuilder outputBuilder = new ConfigModifyOutputBuilder(); - String action = Action.ConfigModify.toString() ; - String rpcName = "config-modify"; - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = - RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> configScaleout(ConfigScaleoutInput input) { - logger.debug("Input received : " + input.toString()); - ConfigScaleoutOutputBuilder outputBuilder = new ConfigScaleoutOutputBuilder(); - String action = Action.ConfigScaleOut.toString() ; - String rpcName = "config-scaleout"; - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = - RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> configRestore(ConfigRestoreInput input) { - logger.debug("Input received : " + input.toString()); - ConfigRestoreOutputBuilder outputBuilder = new ConfigRestoreOutputBuilder(); - String action = Action.ConfigRestore.toString() ; - String rpcName = "config-restore"; - Status status = - ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = - RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> test(TestInput input) { - logger.debug("Input received : " + input.toString()); - TestOutputBuilder outputBuilder = new TestOutputBuilder(); - String action = Action.Test.toString() ; - String rpcName = Action.Test.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> stop(StopInput input) { - logger.debug("Input received : " + input.toString()); - StopOutputBuilder outputBuilder = new StopOutputBuilder(); - String action = Action.Stop.toString() ; - String rpcName = Action.Stop.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - /** - * Starts a specific VNF - * - * @see AppcProviderLcmService#start(StartInput) - */ - @Override - public Future> start(StartInput input) { - logger.debug("Input received : " + input.toString()); - - StartOutputBuilder outputBuilder = new StartOutputBuilder(); - String action = Action.Start.toString() ; - String rpcName = Action.Start.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()) - .action(action) - .rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> audit(AuditInput input) { - logger.debug("Input received : " + input.toString()); - AuditOutputBuilder outputBuilder = new AuditOutputBuilder(); - String action = Action.Audit.toString(); - String rpcName = Action.Audit.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> softwareUpload(SoftwareUploadInput input) { - logger.debug("Input received : " + input.toString()); - SoftwareUploadOutputBuilder outputBuilder = new SoftwareUploadOutputBuilder(); - String action = Action.SoftwareUpload.toString() ; - String rpcName = convertActionNameToUrl(action); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder(). - requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> healthCheck(HealthCheckInput input) { - logger.debug("Input received : " + input.toString()); - HealthCheckOutputBuilder outputBuilder = new HealthCheckOutputBuilder(); - String action = Action.HealthCheck.toString() ; - String rpcName = convertActionNameToUrl(action); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> liveUpgrade(LiveUpgradeInput input) { - logger.debug("Input received : " + input.toString()); - LiveUpgradeOutputBuilder outputBuilder = new LiveUpgradeOutputBuilder(); - String action = Action.LiveUpgrade.toString() ; - String rpcName = convertActionNameToUrl(action); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> lock(LockInput input) { - logger.debug("Input received : " + input.toString()); - LockOutputBuilder outputBuilder = new LockOutputBuilder(); - String action = Action.Lock.toString() ; - String rpcName = Action.Lock.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> unlock(UnlockInput input) { - logger.debug("Input received : " + input.toString()); - UnlockOutputBuilder outputBuilder = new UnlockOutputBuilder(); - String action = Action.Unlock.toString() ; - String rpcName = Action.Unlock.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> checkLock(CheckLockInput input) { - logger.debug("Input received : " + input.toString()); - CheckLockOutputBuilder outputBuilder = new CheckLockOutputBuilder(); - String action = Action.CheckLock.toString(); - String rpcName = Action.CheckLock.name().toLowerCase(); - RequestHandlerOutput requestHandlerOutput = null; - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), - input.getAction(), action); - if (null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input - .getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action) - .rpcName(rpcName).build(); - requestHandlerOutput = executeRequest(request); - - status = buildStatusWithDispatcherOutput(requestHandlerOutput); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", - input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - if (requestHandlerOutput != null && requestHandlerOutput.getResponseContext().getStatus().getCode() == 400) { - outputBuilder.setLocked(CheckLockOutput.Locked.valueOf(requestHandlerOutput.getResponseContext() - .getAdditionalContext().get("locked").toUpperCase())); - } - RpcResult result = RpcResultBuilder.status(true) - .withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - @Override - public Future> configBackup(ConfigBackupInput input) { - logger.debug("Input received : " + input.toString()); - ConfigBackupOutputBuilder outputBuilder = new ConfigBackupOutputBuilder(); - String action = Action.ConfigBackup.toString() ; - String rpcName = Action.ConfigBackup.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> configBackupDelete(ConfigBackupDeleteInput input) { - logger.debug("Input received : " + input.toString()); - ConfigBackupDeleteOutputBuilder outputBuilder = new ConfigBackupDeleteOutputBuilder(); - String action = Action.ConfigBackupDelete.toString() ; - String rpcName = Action.ConfigBackupDelete.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - - @Override - public Future> configExport(ConfigExportInput input) { - logger.debug("Input received : " + input.toString()); - ConfigExportOutputBuilder outputBuilder = new ConfigExportOutputBuilder(); - String action = Action.ConfigExport.toString() ; - String rpcName = Action.ConfigExport.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - @Override - public Future> startApplication(StartApplicationInput input) { - logger.debug("Input received : " + input.toString()); - - StartApplicationOutputBuilder outputBuilder = new StartApplicationOutputBuilder(); - String action = Action.StartApplication.toString() ; - String rpcName = Action.StartApplication.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext() - .commonHeader(input.getCommonHeader()) - .actionIdentifiers(input.getActionIdentifiers()) - .payload(input.getPayload()) - .action(action) - .rpcName(rpcName) - .build(); - - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - @Override - public Future> stopApplication(StopApplicationInput input){ - logger.debug("Input received : " + input.toString()); - StopApplicationOutputBuilder outputBuilder = new StopApplicationOutputBuilder(); - String action = Action.StopApplication.toString() ; - String rpcName = Action.StopApplication.name().toLowerCase(); - Status status = ValidationService.getInstance().validateInput(input.getCommonHeader(), input.getAction(), action); - if(null == status) { - try { - RequestHandlerInput request = new RequestInputBuilder().requestContext().commonHeader(input.getCommonHeader()).actionIdentifiers(input.getActionIdentifiers()).payload(input.getPayload()).action(action).rpcName(rpcName).build(); - status = buildStatusWithDispatcherOutput(executeRequest(request)); - logger.info(String.format("Execute of '%s' finished with status %s. Reason: %s", input.getActionIdentifiers(), status.getCode(), status.getMessage())); - } catch (ParseException e) { - status = buildParsingErrorStatus(e); - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.APPC_PROVIDER, - String.format(COMMON_ERROR_MESSAGE_TEMPLATE, action, e.getMessage()), - this.getClass().getName()); - - } - } - outputBuilder.setCommonHeader(input.getCommonHeader()); - outputBuilder.setStatus(status); - RpcResult result = RpcResultBuilder. status(true).withResult(outputBuilder.build()).build(); - return Futures.immediateFuture(result); - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } - - RequestHandlerOutput executeRequest(RequestHandlerInput request){ - RequestHandler handler = getRequestHandler(request.getRequestContext().getActionLevel()); - RequestHandlerOutput requestHandlerOutput; - if (handler != null) { - try { - requestHandlerOutput = handler.handleRequest(request); - } catch (Exception e) { - logger.info("UNEXPECTED FAILURE while executing " + request.getRequestContext().getAction().name()); - requestHandlerOutput = createErrorRequestHandlerObj(request, - LCMCommandStatus.UNEXPECTED_ERROR, Msg.EXCEPTION_CALLING_DG, e); - } - } else { - String errorMsg = "LCM request cannot be processed at the moment because APPC isn't running"; - requestHandlerOutput = createErrorRequestHandlerObj(request, - LCMCommandStatus.REJECTED, Msg.REQUEST_HANDLER_UNAVAILABLE, new APPCException(errorMsg)); - } - return requestHandlerOutput; - } -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/ResponseHeaderBuilder.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/ResponseHeaderBuilder.java deleted file mode 100644 index 7c479ddc0..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/ResponseHeaderBuilder.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.TIMESTAMP; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeaderBuilder; -import org.onap.appc.util.Time; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - - -/** - * Builds the responses from the APP-C services according to the YANG domainmodel - * - * @since Nov 16, 2015 - * @version $Id$ - */ -public class ResponseHeaderBuilder { - - /** - * The date/time formatter to format timestamps. - */ - @SuppressWarnings("nls") - public static final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); - public static final DateFormat ZULU_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); - - /** - * Private default constructor prevents instantiation - */ - private ResponseHeaderBuilder() { - } - - /** - * This method builds the common response header and returns it to the caller for integration into the response - * - * @param success - * True or false indicating the outcome of the operation. True indicates that the operation was - * successful, false indicates it failed. - * @param requestId - * The original request id for the service - * @param reason - * The reason for the failure if the success flag is false. If success is true, the reason is not used. - * @param duration - * The duration of the request processing - * @return The common response header to be returned to the caller. - */ - @SuppressWarnings("nls") - public static CommonResponseHeader buildHeader(Boolean success, String requestId, String reason, long duration) { - CommonResponseHeaderBuilder builder = new CommonResponseHeaderBuilder(); - - TIMESTAMP timestamp = new TIMESTAMP(FORMATTER.format(Time.utcDate())); - builder.setServiceRequestId(requestId); - builder.setCompleted(timestamp); - builder.setDuration(duration); - builder.setSuccess(success); - - if (success.equals(Boolean.TRUE)) { - builder.setReason("Success"); - } else { - builder.setReason(reason); - } - - return builder.build(); - } - - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/LCMConstants.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/LCMConstants.java deleted file mode 100644 index 40e632e7f..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/LCMConstants.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider.lcm.util; - -public final class LCMConstants { - private LCMConstants() { - } - - public static final String CODE = "Status"; - public static final String VALUE = "Value"; - //flags - public static final String FORCE = "FORCE"; - public static final String MODE = "MODE"; - public static final String TTL = "TTL"; - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/RequestInputBuilder.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/RequestInputBuilder.java deleted file mode 100644 index 979c834de..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/RequestInputBuilder.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider.lcm.util; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -import org.apache.commons.lang.StringUtils; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Payload; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiers; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; -import org.onap.appc.domainmodel.lcm.Flags.Mode; -import org.onap.appc.domainmodel.lcm.ActionLevel; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - - -public class RequestInputBuilder { - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - private static final String FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - - private RequestContext requestContext; - private String rpcName; - - public RequestInputBuilder() { - } - - - public RequestInputBuilder requestContext() { - this.requestContext = new RequestContext(); - return this; - } - - public RequestInputBuilder action(String action) { - this.requestContext.setAction(VNFOperation.findByString(action)); - return this; - } - - - public RequestInputBuilder additionalContext(String key, String value) { - this.requestContext.addKeyValueToAdditionalContext(key, value); - return this; - } - - public RequestInputBuilder payload(Payload payload) { - if (payload != null) { - this.requestContext.setPayload(payload.getValue()); - } - return this; - } - - public RequestHandlerInput build (){ - RequestHandlerInput request = new RequestHandlerInput(); - request.setRequestContext(this.requestContext); - request.setRpcName(rpcName); - return request; - } - - public RequestInputBuilder rpcName(String rpcName) { - this.rpcName = rpcName; - return this; - } - - public RequestInputBuilder commonHeader(CommonHeader commonHeader) throws ParseException { - org.onap.appc.domainmodel.lcm.CommonHeader header = new org.onap.appc.domainmodel.lcm.CommonHeader(); - this.requestContext.setCommonHeader(header); - - try { - if(null != commonHeader.getTimestamp()) { - SimpleDateFormat format = new SimpleDateFormat(FORMAT); - format.setLenient(false); - format.setTimeZone(TimeZone.getTimeZone("UTC")); - header.setTimestamp(format.parse(commonHeader.getTimestamp().getValue()).toInstant()); - }else{ - throw new ParseException("Missing mandatory parameter : timestamp " , 0); - } - } catch (ParseException e) { - logger.error(String.format("DATE format is incorrect: %s", e.getMessage())); - throw e; - } - header.setApiVer(commonHeader.getApiVer()); - header.setRequestId(commonHeader.getRequestId()); - header.setOriginatorId(commonHeader.getOriginatorId()); - header.setSubRequestId(commonHeader.getSubRequestId()); - - Flags inFlags = commonHeader.getFlags(); - boolean force = false; - Mode mode = null; - int ttl = 0; - if (inFlags != null) { - - if (null != inFlags.getForce()) { - force = Boolean.parseBoolean(inFlags.getForce().toString().toLowerCase()); - } - if (null != inFlags.getMode()) { - mode = Mode.valueOf(inFlags.getMode().name()); - } - if (null != inFlags.getTtl()) { - ttl = inFlags.getTtl(); - } - - } - this.requestContext.getCommonHeader().setFlags(new org.onap.appc.domainmodel.lcm.Flags(mode, force, ttl)); - return this; - } - - public RequestInputBuilder actionIdentifiers(ActionIdentifiers actionIdentifiers) throws ParseException { - if(null!= actionIdentifiers) { - org.onap.appc.domainmodel.lcm.ActionIdentifiers actionIds = new org.onap.appc.domainmodel.lcm.ActionIdentifiers(); - actionIds.setServiceInstanceId(actionIdentifiers.getServiceInstanceId()); - actionIds.setVnfcName(actionIdentifiers.getVnfcName()); - actionIds.setvServerId(actionIdentifiers.getVserverId()); - actionIds.setVnfId(actionIdentifiers.getVnfId()); - actionIds.setVfModuleId(actionIdentifiers.getVfModuleId()); - this.requestContext.setActionIdentifiers(actionIds); - - ActionLevel actionLevel = readActionLevel(actionIds); - this.requestContext.setActionLevel(actionLevel); - return this; - }else{ - throw new ParseException("Missing action identifier" , 0); - } - } - - private ActionLevel readActionLevel(org.onap.appc.domainmodel.lcm.ActionIdentifiers actionIds) { - if(!StringUtils.isEmpty(actionIds.getVserverId())){ - return ActionLevel.VM; - } - return ActionLevel.VNF; - } - - -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/ValidationService.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/ValidationService.java deleted file mode 100644 index 69e100b57..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/ValidationService.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider.lcm.util; - -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.i18n.Msg; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; - -import javax.swing.*; - - - -public class ValidationService { - - private static class ValidationServiceHolder { - private static final ValidationService INSTANCE = new ValidationService(); - } - - private final EELFLogger logger = EELFManager.getInstance().getLogger(ValidationService.class); - - private Configuration configuration = ConfigurationFactory.getConfiguration(); - - public static ValidationService getInstance(){ - return ValidationServiceHolder.INSTANCE; - } - - public Status validateInput (CommonHeader commonHeader, Action action , String rpcName) { - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - String reason ; - StringBuilder paramName = new StringBuilder(""); - if (!isEmpty(commonHeader) && !isEmpty(commonHeader.getApiVer())&& !isEmpty(commonHeader.getTimestamp()) && !isEmpty(commonHeader.getRequestId()) && !isEmpty(action) && !isEmpty(commonHeader.getOriginatorId())){ - if(!action.toString().equalsIgnoreCase(rpcName)) logger.warn("action in input request '" + action.toString() + "' is different from endpoint '" + rpcName + "'"); - return null; - } else{ - if(isEmpty(commonHeader)){ - paramName.append("common-header"); - }else{ - if (isEmpty(commonHeader.getApiVer())) paramName.append("api-ver"); - if (isEmpty(commonHeader.getTimestamp())) paramName.append(isEmpty(paramName) ? "timestamp" : " , timestamp" ); - if (isEmpty(commonHeader.getRequestId())) paramName.append(isEmpty(paramName) ? "request-id" : " , request-id" ); - if (isEmpty(commonHeader.getOriginatorId())) paramName.append(isEmpty(paramName) ? "originator-id" : " , originator-id" ); - } - if (isEmpty(action)) paramName.append(isEmpty(paramName) ? "action" : " , action" ); - } - - - - reason = EELFResourceManager.format(Msg.NULL_OR_INVALID_ARGUMENT, appName, rpcName, paramName.toString() , ""); - logger.info("Mandatory parameter/s" + paramName.toString() + " is/are missing"); - logger.error(reason); - LCMCommandStatus lcmCommandStatus = LCMCommandStatus.MISSING_MANDATORY_PARAMETER; - Params params = new Params().addParam("paramName", paramName.toString()); - StatusBuilder status = new StatusBuilder(); - status.setCode(lcmCommandStatus.getResponseCode()); - status.setMessage(lcmCommandStatus.getFormattedMessage(params)); - return status.build(); - } - - private boolean isEmpty (Object object){ - return (null == object || "".equalsIgnoreCase(object.toString())); - } -} diff --git a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/topology/TopologyService.java b/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/topology/TopologyService.java deleted file mode 100644 index ea1d3f1ee..000000000 --- a/appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/topology/TopologyService.java +++ /dev/null @@ -1,800 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider.topology; - -import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; -import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -import java.net.InetAddress; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; -import java.util.TimeZone; - -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.UUID; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutputBuilder; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import org.onap.appc.provider.AppcProvider; -import org.onap.appc.provider.AppcProviderClient; -import org.onap.appc.provider.ResponseHeaderBuilder; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.slf4j.MDC; - -/** - * This class is used to implement the topology services API and invoke the appropriate directed graphs based on the - * service being requested. - * - */ -public class TopologyService { - - /** - * The loggers we are using - */ - // private static EELFLogger logger = LoggerFactory.getLogger(TopologyService.class); - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); - private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private static EELFLogger performanceLogger = EELFManager.getInstance().getPerformanceLogger(); - - /** - * The provider we are servicing - */ - private AppcProvider provider; - - /** - * The reason associated with the last DG call - */ - private String reason; - - /** - * The APPC configuration properties - */ - private Configuration configuration = ConfigurationFactory.getConfiguration(); - - /** - * Create the topology services implementation for the specific appc provider (api) implementation - * - * @param provider - * The provider we are servicing - */ - public TopologyService(AppcProvider provider) { - this.provider = provider; - } - - // /** - // * Processes the topology request - // * - // * @param input - // * The request to be processed - // * @return The result of processing - // */ - // public RpcResult process(TopologyOperationInput input) { - // RpcResult response; - // - // String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - // logger.info(String.format("%s:topology operations called...", appName)); - // - // /* - // * Properties used to pass information to the DG - // */ - // Properties properties = new Properties(); - // - // if (input == null || input.getTopologyRequest().getVmId() == null) { - // String msg = - // String.format("%s: topology operation failed, invalid input. Null or empty argument '%s'", appName, - // "vm_id"); - // logger.debug(msg); - // response = generateTopologyOperationResponse(Boolean.FALSE, "UNKNOWN", msg, "UNDEFINED"); - // } else { - // // CommonRequestHeader crh = input.getCommonRequestHeader(); - // TopologyHeader hdr = input.getTopologyHeader(); - // TopologyRequest req = input.getTopologyRequest(); - // - // // String requestId = crh.getServiceRequestId(); - // String requestId = hdr.getSvcRequestId(); - // properties.put(Constants.CONTEXT_REQID, requestId); - // - // String infomsg = String.format("Topology request '%s' (%s) received.", requestId, hdr.getSvcAction()); - // - // // switch (req.getSvcAction()) { - // switch (hdr.getSvcAction()) { - // case Restart: - // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_RESTART); - // response = restart(input, properties); - // logger.info(infomsg); - // break; - // - // case Rebuild: - // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_REBUILD); - // response = rebuild(input, properties); - // logger.info(infomsg); - // break; - // - // default: - // String msg = String.format("Invalid request type [%s] for request id [%s]", req, requestId); - // response = generateTopologyOperationResponse(Boolean.FALSE, requestId, msg, "N/A"); - // } - // } - // - // return response; - // } - - /** - * Restart a VM - * - * @param hdr - * The common request header - * @param vnf - * The identification of the VNF resource to be operated upon - * @return The rpc result of the restart operation - */ - public RpcResult modifyConfig(CommonRequestHeader hdr, ConfigPayload data) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - df.setTimeZone(tz); - // String startTimeStr = String.valueOf(startTime); - String startTimeStr = df.format(new Date()); - String requestId = hdr.getServiceRequestId(); - - //MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - MDC.put("startTime", Long.toString(startTime)); - MDC.put("target", "appc"); - logger.info(String.format("Starting RESTART for request with id [%s]", requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", - startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - //UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "modifyConfig"); - properties.put(Constants.CONTEXT_REQID, requestId); - //properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - String url = configuration.getProperty("appc.provider.vfodl.url"); - try{ - if(url.contains("NODE_NAME")){ - url = url.replace("NODE_NAME", data.getConfigUrl()); - } - }catch(Exception e){ - url = configuration.getProperty("appc.provider.vfodl.url"); - } - logger.trace("Final URL to VF ODL: "+url); - properties.put("org.onap.appc.configURL", url); - properties.put("org.onap.appc.configJson", data.getConfigJson()); - - //UUID identityUrl = vnf.getIdentityUrl(); - //if (identityUrl != null) { - // properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - //} - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - - MDC.put("target", "appc"); - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("APPC0119I ModifyConfig '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - - ModifyConfigOutputBuilder rob = new ModifyConfigOutputBuilder(); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - MDC.put("endTime", endTimeStr); - MDC.put("duration", durationStr); - rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - //rob.setVmId(new UUID(vmId)); - - auditLogger.info(String.format( - "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - metricsLogger.info(String.format( - "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(rob.build()).build(); - return rpcResult; - - } - - - - - /** - * Restart a VM - * - * @param hdr - * The common request header - * @param vnf - * The identification of the VNF resource to be operated upon - * @return The rpc result of the restart operation - */ - public RpcResult migrate(CommonRequestHeader hdr, VnfResource vnf) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - df.setTimeZone(tz); - // String startTimeStr = String.valueOf(startTime); - String startTimeStr = df.format(new Date()); - String requestId = hdr.getServiceRequestId(); - - //MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:Migrate"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - MDC.put("startTime", startTimeStr); - MDC.put("target", "appc"); - logger.info(String.format("Starting ANY for request with id [%s]", requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", - startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "migrate"); - properties.put(Constants.CONTEXT_REQID, requestId); - properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - - UUID identityUrl = vnf.getIdentityUrl(); - if (identityUrl != null) { - properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - } - - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - /* - * Generate the appropriate response - */ - MDC.put("target", "appc"); - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("APPC0118I Migrate '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - - MigrateOutputBuilder mob = new MigrateOutputBuilder(); - - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - MDC.put("endTime", endTimeStr); - MDC.put("duration", durationStr); - mob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - mob.setVmId(new UUID(vmId)); - - auditLogger.info(String.format( - "Audit Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - metricsLogger.info(String.format( - "Metrics Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(mob.build()).build(); - return rpcResult; - } - - /** - * Restart a VM - * - * @param hdr - * The common request header - * @param vnf - * The identification of the VNF resource to be operated upon - * @return The rpc result of the restart operation - */ - public RpcResult restart(CommonRequestHeader hdr, VnfResource vnf) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - df.setTimeZone(tz); - // String startTimeStr = String.valueOf(startTime); - String startTimeStr = df.format(new Date()); - String requestId = hdr.getServiceRequestId(); - - //MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - MDC.put("startTime", Long.toString(startTime)); - MDC.put("target", "appc"); - logger.info(String.format("Starting RESTART for request with id [%s]", requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", - startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "restart"); - properties.put(Constants.CONTEXT_REQID, requestId); - properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - - UUID identityUrl = vnf.getIdentityUrl(); - if (identityUrl != null) { - properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - } - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - /* - * Generate the appropriate response - */ - MDC.put("target", "appc"); - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("APPC0119I Restart '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - - RestartOutputBuilder rob = new RestartOutputBuilder(); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - MDC.put("endTime", endTimeStr); - MDC.put("duration", durationStr); - rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - rob.setVmId(new UUID(vmId)); - - auditLogger.info(String.format( - "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - metricsLogger.info(String.format( - "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(rob.build()).build(); - return rpcResult; - } - - /** - * Rebuild a VM - * - * @param hdr - * The common request header - * @param vnf - * The identification of the VNF resource to be operated upon - * @return The rpc result of the rebuild operation - */ - public RpcResult rebuild(CommonRequestHeader hdr, VnfResource vnf) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - df.setTimeZone(tz); - // String startTimeStr = String.valueOf(startTime); - String startTimeStr = df.format(new Date()); - String requestId = hdr.getServiceRequestId(); - - //MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:Rebuild"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - MDC.put("startTime", startTimeStr); - MDC.put("target", "appc"); - logger.info(String.format("Starting REBUILD for request with id [%s]", requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]", - startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "rebuild"); - properties.put(Constants.CONTEXT_REQID, requestId); - properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - - UUID identityUrl = vnf.getIdentityUrl(); - if (identityUrl != null) { - properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - } - - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - /* - * Generate the appropriate response - */ - MDC.put("target", "appc"); - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("APPC0120I Rebuild '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - - RebuildOutputBuilder rob = new RebuildOutputBuilder(); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - MDC.put("endTime", endTimeStr); - MDC.put("duration", durationStr); - rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - rob.setOriginalVmId(new UUID(vmId)); - rob.setNewVmId(new UUID(vmId)); - - auditLogger.info(String.format( - "Audit Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - metricsLogger.info(String.format( - "Metrics Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(rob.build()).build(); - return rpcResult; - } - - /** - * Snapshot a VM - * - * @param hdr - * The common request header - * @param vnf - * The identification of the VNF resource to be operated upon - * @return The rpc result of the restart operation - */ - public RpcResult snapshot(CommonRequestHeader hdr, VnfResource vnf) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - df.setTimeZone(tz); - // String startTimeStr = String.valueOf(startTime); - String startTimeStr = df.format(new Date()); - String requestId = hdr.getServiceRequestId(); - - //MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:Snapshot"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - MDC.put("startTime", Long.toString(startTime)); - MDC.put("target", "appc"); - logger.info(String.format("Starting SNAPSHOT for request with id [%s]", requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C Snapshot initiated. Start Time: [%s]. Request ID: [%s]", - startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "snapshot"); - properties.put(Constants.CONTEXT_REQID, requestId); - properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - - UUID identityUrl = vnf.getIdentityUrl(); - if (identityUrl != null) { - properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - } - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - /* - * Generate the appropriate response - */ - MDC.put("target", "appc"); - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("APPC0119I Snapshot '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - - SnapshotOutputBuilder sob = new SnapshotOutputBuilder(); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String endTimeStr = String.valueOf(endTime); - String durationStr = String.valueOf(duration); - MDC.put("endTime", endTimeStr); - MDC.put("duration", durationStr); - sob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - sob.setVmId(new UUID(vmId)); - - auditLogger.info(String.format( - "Audit Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - metricsLogger.info(String.format( - "Metrics Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s", - requestId, statusStr, startTime, endTime, duration, requestId, reason)); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(sob.build()).build(); - return rpcResult; - } - -/**************************************************/ - - public RpcResult vmstatuscheck(CommonRequestHeader hdr, VnfResource vnf) { - long startTime = System.currentTimeMillis(); - String requestId = hdr.getServiceRequestId(); - - MDC.clear(); - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - MDC.put(MDC_SERVICE_NAME, "App-C Provider:vmstatuscheck"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - } catch (Exception e) { - e.printStackTrace(); - } - MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString()); - MDC.put(MDC_ALERT_SEVERITY, "0"); - logger.info(String.format("Starting VMSTATUSCHECK for request with id [%s]", requestId)); - - performanceLogger.info(String.format("Performance Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); - auditLogger.info(String.format("Audit Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); - metricsLogger.info(String.format("Metrics Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId)); - - /* - * Copy any needed inputs or other values into the properties to be passed to the DG model - */ - UUID vmId = vnf.getVmId(); - Properties properties = new Properties(); - properties.put(Constants.CONTEXT_ACTION, "vmstatuschecking"); - properties.put(Constants.CONTEXT_REQID, requestId); - properties.put(Constants.CONTEXT_VMID, vmId.getValue()); - properties.put(Constants.STATUS_GETTER, "checking"); - - - - - UUID identityUrl = vnf.getIdentityUrl(); - if (identityUrl != null) { - properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue()); - } - /* - * Attempt to call the DG with the appropriate properties - */ - boolean success = callGraph(properties); - - /* - * Generate the appropriate response - */ - String statusStr = success ? "SUCCESS" : "FAILURE"; - String infomsg = - String.format("VMSTATUSCHECK '%s' finished with status %s. Reason: %s", requestId, statusStr, reason); - logger.info(infomsg); - long endTime = System.currentTimeMillis(); - auditLogger.info(String.format("Audit Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason)); - metricsLogger.info(String.format("Metrics Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason)); - //logger.info(String.format("Step1 [%s]", Constants.STATUS_GETTER)); - String tempstring2 = properties.getProperty(Constants.STATUS_GETTER).trim(); - //logger.info(String.format("Step2 [%s]", tempstring2)); - - - VmstatuscheckOutputBuilder vob = new VmstatuscheckOutputBuilder(); - long duration = System.currentTimeMillis() - startTime; - vob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration)); - vob.setStatMsg(tempstring2); - - // Status must be set to true to indicate that our return is expected - RpcResult rpcResult = - RpcResultBuilder. status(true).withResult(vob.build()).build(); - return rpcResult; - } - - /*************************************************/ - - - - private boolean callGraph(Properties props) { - String moduleName = configuration.getProperty(Constants.PROPERTY_MODULE_NAME); - String methodName = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_METHOD); - String version = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_VERSION); - String mode = Constants.SYNC_MODE; - return callGraph(moduleName, methodName, version, mode, props); - } - - /** - * Calls a specified directed graph with the specified properties and returns the response - * - * @param module - * The module name to be used to locate the graph - * @param method - * The method name to be executed (rpc) - * @param version - * The version of the graph to be used, or null for the latest - * @param mode - * the execution mode of the graph, sync or async - * @param props - * A set of name-value properties to be passed to the graph for context variables. - */ - private boolean callGraph(String module, String method, String version, String mode, Properties props) { - String graphName = String.format(("%s:%s:%s"), module, method, version); - logger.debug(String.format("Calling Graph %s", graphName)); - metricsLogger.info(String.format("Calling Graph %s", graphName)); - - boolean success = false; - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - AppcProviderClient svcLogicClient = new AppcProviderClient(); - try { - if (svcLogicClient.hasGraph(module, method, version, mode)) { - try { - Properties respProps = svcLogicClient.execute(module, method, version, mode, props); - success = false; // Assume it failed unless proven otherwise - reason = "Failed"; // Assume it failed unless proven otherwise - - logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_HEADER, appName, graphName, - Integer.toString(respProps.size()))); - for (String key : respProps.stringPropertyNames()) { - logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_DETAIL, appName, graphName, - key, (String) respProps.get(key))); - } - - // TODO - Find docs and see if there is a better way to handle this - // Bad requests have errors - if (respProps.containsKey(Constants.ATTRIBUTE_ERROR_CODE)) { - // || respProps.containsKey(Constants.ATTRIBUTE_ERROR_MESSAGE)) { - String errorCodeProperty = respProps.getProperty(Constants.ATTRIBUTE_ERROR_CODE).trim(); - int errorCode = 200; - try { - errorCode = Integer.parseInt(errorCodeProperty); - if (errorCode >= 300) { - reason = EELFResourceManager.format(Msg.DG_FAILED_RESPONSE, appName, graphName, - errorCodeProperty, respProps.getProperty(Constants.ATTRIBUTE_ERROR_MESSAGE)); - logger.error(reason); - success = false; - } else { - success = true; - reason = "Success"; - } - } catch (NumberFormatException e) { - reason = EELFResourceManager.format(Msg.PARAMETER_NOT_NUMERIC, appName, graphName, - Constants.ATTRIBUTE_ERROR_CODE, errorCodeProperty); - logger.error(reason); - success = false; - } - } else { - /* - * Added code that requires error code to now be defined in ALL cases. If not, it is an error - * and the response will be set to failed regardless if the DG worked or not. - */ - reason = EELFResourceManager.format(Msg.PARAMETER_IS_MISSING, appName, graphName, - Constants.ATTRIBUTE_ERROR_CODE); - logger.error(reason); - success = false; - } - } catch (Exception e) { - success = false; - reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName, - e.getClass().getSimpleName(), graphName, e.getMessage()); - logger.error(reason); - } - } else { - success = false; - reason = EELFResourceManager.format(Msg.GRAPH_NOT_FOUND, appName, graphName); - logger.error(reason); - } - } catch (Exception e) { - success = false; - reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName, e.getClass().getSimpleName(), - graphName, e.getMessage()); - logger.error(reason); - } - - return success; - } - -} diff --git a/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/default.properties b/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..5e9258a09 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,58 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# This property file supplies the configuration defaults for the APP-C controller +# +# Default values are supplied so that all defined properties have well-known values and are +# valid even if a configuration file is not supplied. This is done to ensure that a runnable, +# stable, and defined configuration exists at all times. The reason the defaults are supplied +# via this property file and not in the code is so that the properties can be changed +# easily if needed in the future. Use of the "getProperty(name, default)" method is +# discouraged because if the default value needs to be changed, everywhere in the code it +# is used would have to be changed. By loading the defaults in this property file, all +# values can be defined in one place and support is easier. This does mean that all +# properties that are defined must have a default value supplied here. Which also means +# this file documents all defined properties (not a bad thing either). +# +#-------------------------------------------------------------------------------------------- +# The path and file used to load user-supplied configuration settings, if any +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# The path to search for logging configuration document, and the name of the document +# +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + +# +# The DG properties +# +appc.service.logic.module.name=APPC +appc.topology.dg.method=topology-operation-all +appc.topology.dg.version=2.0.0 + diff --git a/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/logback.xml b/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/logback.xml new file mode 100644 index 000000000..0dffe75e0 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/main/resources/org/onap/appc/logback.xml @@ -0,0 +1,287 @@ + + + + + + + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + + + + + + + ${logDirectory}/cdp.log + + ${logDirectory}/cdp.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-security.log + + ${logDirectory}/cdp-security.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + 0 + + + + + + ${logDirectory}/cdp-performance.log + + ${logDirectory}/cdp-performance.%i.log.zip + + 1 + 9 + + + 5MB + + + true + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-server.log + + ${logDirectory}/cdp-server.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} + %X{Path}] - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-coordinator.log + + ${logDirectory}/cdp-coordinator.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + 256 + + + + + + ${logDirectory}/cdp-policy.log + + ${logDirectory}/cdp-policy.%i.log.zip + + 1 + 9 + + + 5MB + + + + %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level + %-36.36logger - %msg%n + + + + 256 + + + + ${debugLogDirectory}/appc-debug.log + + ${logDirectory}/command-executor.%i.log.zip + + 1 + 9 + + + 5MB + + + + + %d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%X{InstanceUUID}|%-5.5p|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%c{3}]|%m%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 5e9258a09..000000000 --- a/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,58 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# -# This property file supplies the configuration defaults for the APP-C controller -# -# Default values are supplied so that all defined properties have well-known values and are -# valid even if a configuration file is not supplied. This is done to ensure that a runnable, -# stable, and defined configuration exists at all times. The reason the defaults are supplied -# via this property file and not in the code is so that the properties can be changed -# easily if needed in the future. Use of the "getProperty(name, default)" method is -# discouraged because if the default value needs to be changed, everywhere in the code it -# is used would have to be changed. By loading the defaults in this property file, all -# values can be defined in one place and support is easier. This does mean that all -# properties that are defined must have a default value supplied here. Which also means -# this file documents all defined properties (not a bad thing either). -# -#-------------------------------------------------------------------------------------------- -# The path and file used to load user-supplied configuration settings, if any -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -appc.application.name=APPC - -# -# The path to search for logging configuration document, and the name of the document -# -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - -# -# The DG properties -# -appc.service.logic.module.name=APPC -appc.topology.dg.method=topology-operation-all -appc.topology.dg.version=2.0.0 - diff --git a/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/logback.xml b/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/logback.xml deleted file mode 100644 index 0dffe75e0..000000000 --- a/appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/logback.xml +++ /dev/null @@ -1,287 +0,0 @@ - - - - - - - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - - - - - - - ${logDirectory}/cdp.log - - ${logDirectory}/cdp.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-security.log - - ${logDirectory}/cdp-security.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - 0 - - - - - - ${logDirectory}/cdp-performance.log - - ${logDirectory}/cdp-performance.%i.log.zip - - 1 - 9 - - - 5MB - - - true - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-server.log - - ${logDirectory}/cdp-server.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger [%X{User} %X{RemoteHost} %X{RequestId} %X{Method} - %X{Path}] - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-coordinator.log - - ${logDirectory}/cdp-coordinator.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - 256 - - - - - - ${logDirectory}/cdp-policy.log - - ${logDirectory}/cdp-policy.%i.log.zip - - 1 - 9 - - - 5MB - - - - %d{MM/dd-HH:mm:ss.SSS} [%-16thread] %.-5level - %-36.36logger - %msg%n - - - - 256 - - - - ${debugLogDirectory}/appc-debug.log - - ${logDirectory}/command-executor.%i.log.zip - - 1 - 9 - - - 5MB - - - - - %d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServiceName} - %X{bundle.id} - %X{bundle.name} - %X{bundle.version}|%X{InstanceUUID}|%-5.5p|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%c{3}]|%m%n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderClientTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderClientTest.java new file mode 100644 index 000000000..58ccc4735 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderClientTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.Properties; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AppcProviderClient.class, FrameworkUtil.class}) +public class AppcProviderClientTest { + @Mock + private SvcLogicService svcLogicService; + @Mock + private AppcProviderClient appcProviderClient; + + @Before + public void setUp() throws Exception { + // Prepare all mocks + mockStatic(FrameworkUtil.class); + Bundle mockedBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(SvcLogicService.class)).thenReturn(mockedBundle); + + BundleContext mockedBundleContext = mock(BundleContext.class); + Mockito.when(mockedBundle.getBundleContext()).thenReturn(mockedBundleContext); + + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(mockedBundleContext.getServiceReference(SvcLogicService.NAME)).thenReturn(svcRef); + + Mockito.when(mockedBundleContext.getService(svcRef)).thenReturn(svcLogicService); + + appcProviderClient = new AppcProviderClient(); + } + + @Test + public void testNonArgumentConstructor() { + AppcProviderClient appcProviderClient = new AppcProviderClient(); + Assert.assertEquals(Whitebox.getInternalState(appcProviderClient, "svcLogic"), svcLogicService); + } + + @Test + public void hasGraph() throws Exception { + doReturn(true).when(svcLogicService).hasGraph(any(), any(), any(), any()); + boolean hasGraph = appcProviderClient.hasGraph("test-module", "test-rpc", "test-version", "test-mode"); + Assert.assertTrue(hasGraph); + } + + @Test + public void execute() throws Exception { + Properties properties = new Properties(); + appcProviderClient.execute("test-module", "test-rpc", "test-version", "test-mode", properties); + verify(svcLogicService, times(1)).execute("test-module", "test-rpc", "test-version", "test-mode", + properties); + } + +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderLcmTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderLcmTest.java new file mode 100644 index 000000000..f25df9c44 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderLcmTest.java @@ -0,0 +1,1118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ZULU; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiers; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiersBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.provider.lcm.util.ValidationService; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +/** + * Integration Test class for AppcProviderLcm. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class, AppcProviderLcm.class, ValidationService.class}) +public class AppcProviderLcmTest extends AbstractDataBrokerTest { + private Status successStatus = new StatusBuilder().setCode(400).setMessage("success").build(); + private Status failStatus = new StatusBuilder().setCode(401).setMessage("failure").build(); + + private AppcProviderLcm appcProviderLcm; + private DataBroker dataBroker; + @Spy + private ValidationService validationService = ValidationService.getInstance(); + @Mock + private RequestHandlerOutput requestHandlerOutput; + @Mock + private ResponseContext responseContext; + @Mock + private org.onap.appc.domainmodel.lcm.Status successlcmStatus; + + /** + * The @Before annotation is defined in the AbstractDataBrokerTest class. The method setupWithDataBroker is invoked + * from inside the @Before method and is used to initialize the databroker with objects for a test runs. In our case + * we use this oportunity to create an instance of our provider and initialize it (which registers it as a listener + * etc). This method runs before every @Test method below. + */ + @Override + protected void setupWithDataBroker(DataBroker dataBroker) { + super.setupWithDataBroker(dataBroker); + + this.dataBroker = dataBroker; + } + + @Before + public void setUp() throws Exception { + //mock appcProviderLcm + NotificationProviderService nps = mock(NotificationProviderService.class); + RpcProviderRegistry registry = mock(RpcProviderRegistry.class); + BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); + PowerMockito.doReturn(rpcRegistration).when(registry).addRpcImplementation(any(), any()); + appcProviderLcm = spy(new AppcProviderLcm(dataBroker, nps, registry)); + //mock validationService + mockStatic(ValidationService.class); + PowerMockito.when(ValidationService.getInstance()).thenReturn(validationService); + + doReturn(successlcmStatus).when(responseContext).getStatus(); + doReturn(400).when(successlcmStatus).getCode(); + doReturn("success").when(successlcmStatus).getMessage(); + } + + @Test + public void testConstructor() throws Exception { + ExecutorService executorService = Whitebox.getInternalState(appcProviderLcm, "executor"); + Assert.assertNotNull(executorService); + BindingAwareBroker.RpcRegistration internalRpcRegistration = Whitebox.getInternalState(appcProviderLcm, + "rpcRegistration"); + Assert.assertNotNull(internalRpcRegistration); + } + + @Test + public void testClose() throws Exception { + ExecutorService executorService = spy(Executors.newFixedThreadPool(1)); + Whitebox.setInternalState(appcProviderLcm, "executor", executorService); + BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); + Whitebox.setInternalState(appcProviderLcm, "rpcRegistration", rpcRegistration); + appcProviderLcm.close(); + + verify(executorService, times(1)).shutdown(); + verify(rpcRegistration, times(1)).close(); + } + + @Test + public void testRebuild() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + RebuildInput rebuildInput = mock(RebuildInput.class); + doReturn(newCommonHeader("request-id-test")).when(rebuildInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(rebuildInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.rebuild(rebuildInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.rebuild(rebuildInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(rebuildInput).getActionIdentifiers(); + results = appcProviderLcm.rebuild(rebuildInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testRestart() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + RestartInput restartInput = mock(RestartInput.class); + doReturn(newCommonHeader("request-id-test")).when(restartInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(restartInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.restart(restartInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.restart(restartInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(restartInput).getActionIdentifiers(); + results = appcProviderLcm.restart(restartInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testStartApplication() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + StartApplicationInput startApplicationInput = mock(StartApplicationInput.class); + doReturn(newCommonHeader("request-id-test")).when(startApplicationInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(startApplicationInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.startApplication(startApplicationInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.startApplication(startApplicationInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(startApplicationInput).getActionIdentifiers(); + results = appcProviderLcm.startApplication(startApplicationInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testMigrate() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + MigrateInput migrateInput = mock(MigrateInput.class); + doReturn(newCommonHeader("request-id-test")).when(migrateInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(migrateInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.migrate(migrateInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.migrate(migrateInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(migrateInput).getActionIdentifiers(); + results = appcProviderLcm.migrate(migrateInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testEvacuate() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + EvacuateInput evacuateInput = mock(EvacuateInput.class); + doReturn(newCommonHeader("request-id-test")).when(evacuateInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(evacuateInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.evacuate(evacuateInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.evacuate(evacuateInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(evacuateInput).getActionIdentifiers(); + results = appcProviderLcm.evacuate(evacuateInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testSnapshot() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + SnapshotInput snapshotInput = mock(SnapshotInput.class); + doReturn(newCommonHeader("request-id-test")).when(snapshotInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(snapshotInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.snapshot(snapshotInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.snapshot(snapshotInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(snapshotInput).getActionIdentifiers(); + results = appcProviderLcm.snapshot(snapshotInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testRollback() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + RollbackInput rollbackInput = mock(RollbackInput.class); + doReturn(newCommonHeader("request-id-test")).when(rollbackInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(rollbackInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.rollback(rollbackInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.rollback(rollbackInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(rollbackInput).getActionIdentifiers(); + results = appcProviderLcm.rollback(rollbackInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testSync() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + SyncInput syncInput = mock(SyncInput.class); + doReturn(newCommonHeader("request-id-test")).when(syncInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(syncInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.sync(syncInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.sync(syncInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(syncInput).getActionIdentifiers(); + results = appcProviderLcm.sync(syncInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testTerminate() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + TerminateInput terminateInput = mock(TerminateInput.class); + doReturn(newCommonHeader("request-id-test")).when(terminateInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(terminateInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.terminate(terminateInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.terminate(terminateInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(terminateInput).getActionIdentifiers(); + results = appcProviderLcm.terminate(terminateInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigure() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigureInput configureInput = mock(ConfigureInput.class); + doReturn(newCommonHeader("request-id-test")).when(configureInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configureInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configure(configureInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configure(configureInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configureInput).getActionIdentifiers(); + results = appcProviderLcm.configure(configureInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigModify() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigModifyInput configModifyInput = mock(ConfigModifyInput.class); + doReturn(newCommonHeader("request-id-test")).when(configModifyInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configModifyInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configModify(configModifyInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configModify(configModifyInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configModifyInput).getActionIdentifiers(); + results = appcProviderLcm.configModify(configModifyInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigScaleout() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigScaleoutInput configScaleoutInput = mock(ConfigScaleoutInput.class); + doReturn(newCommonHeader("request-id-test")).when(configScaleoutInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configScaleoutInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configScaleout(configScaleoutInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configScaleout(configScaleoutInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configScaleoutInput).getActionIdentifiers(); + results = appcProviderLcm.configScaleout(configScaleoutInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigRestore() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigRestoreInput configRestoreInput = mock(ConfigRestoreInput.class); + doReturn(newCommonHeader("request-id-test")).when(configRestoreInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configRestoreInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configRestore(configRestoreInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configRestore(configRestoreInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configRestoreInput).getActionIdentifiers(); + results = appcProviderLcm.configRestore(configRestoreInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testTest() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + TestInput testInput = mock(TestInput.class); + doReturn(newCommonHeader("request-id-test")).when(testInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(testInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.test(testInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.test(testInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(testInput).getActionIdentifiers(); + results = appcProviderLcm.test(testInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testStop() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + StopInput stopInput = mock(StopInput.class); + doReturn(newCommonHeader("request-id-stop")).when(stopInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(stopInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.stop(stopInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.stop(stopInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(stopInput).getActionIdentifiers(); + results = appcProviderLcm.stop(stopInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testStart() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + StartInput startInput = mock(StartInput.class); + doReturn(newCommonHeader("request-id-start")).when(startInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(startInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.start(startInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.start(startInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(startInput).getActionIdentifiers(); + results = appcProviderLcm.start(startInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testAudit() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + AuditInput auditInput = mock(AuditInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(auditInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(auditInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.audit(auditInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.audit(auditInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(auditInput).getActionIdentifiers(); + results = appcProviderLcm.audit(auditInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testSoftwareUpload() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + SoftwareUploadInput softwareUploadInput = mock(SoftwareUploadInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(softwareUploadInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(softwareUploadInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.softwareUpload(softwareUploadInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.softwareUpload(softwareUploadInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(softwareUploadInput).getActionIdentifiers(); + results = appcProviderLcm.softwareUpload(softwareUploadInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testHealthCheck() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + HealthCheckInput healthCheckInput = mock(HealthCheckInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(healthCheckInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(healthCheckInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.healthCheck(healthCheckInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.healthCheck(healthCheckInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(healthCheckInput).getActionIdentifiers(); + results = appcProviderLcm.healthCheck(healthCheckInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testLiveUpgrade() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + LiveUpgradeInput liveUpgradeInput = mock(LiveUpgradeInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(liveUpgradeInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(liveUpgradeInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.liveUpgrade(liveUpgradeInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.liveUpgrade(liveUpgradeInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(liveUpgradeInput).getActionIdentifiers(); + results = appcProviderLcm.liveUpgrade(liveUpgradeInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testLock() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + LockInput lockInput = mock(LockInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(lockInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(lockInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.lock(lockInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.lock(lockInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(lockInput).getActionIdentifiers(); + results = appcProviderLcm.lock(lockInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testUnlock() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + UnlockInput unlockInput = mock(UnlockInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(unlockInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(unlockInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.unlock(unlockInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.unlock(unlockInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(unlockInput).getActionIdentifiers(); + results = appcProviderLcm.unlock(unlockInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testCheckLock() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + Map additionalContext = new HashMap<>(); + additionalContext.put("locked", "true"); + doReturn(additionalContext).when(responseContext).getAdditionalContext(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + CheckLockInput checkLockInput = mock(CheckLockInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(checkLockInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(checkLockInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.checkLock(checkLockInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.checkLock(checkLockInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(checkLockInput).getActionIdentifiers(); + results = appcProviderLcm.checkLock(checkLockInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigBackup() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigBackupInput configBackupInput = mock(ConfigBackupInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(configBackupInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configBackupInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configBackup(configBackupInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configBackup(configBackupInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configBackupInput).getActionIdentifiers(); + results = appcProviderLcm.configBackup(configBackupInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigBackupDelete() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigBackupDeleteInput configBackupDeleteInput = mock(ConfigBackupDeleteInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(configBackupDeleteInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configBackupDeleteInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configBackupDelete + (configBackupDeleteInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configBackupDelete(configBackupDeleteInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configBackupDeleteInput).getActionIdentifiers(); + results = appcProviderLcm.configBackupDelete(configBackupDeleteInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testConfigExport() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + ConfigExportInput configExportInput = mock(ConfigExportInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(configExportInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(configExportInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.configExport + (configExportInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.configExport(configExportInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(configExportInput).getActionIdentifiers(); + results = appcProviderLcm.configExport(configExportInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @Test + public void testStopApplication() throws Exception { + // Validation success + doReturn("Success").when(successlcmStatus).getMessage(); + doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); + doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); + doReturn(null).when(validationService).validateInput(any(), any(), any()); + + StopApplicationInput stopApplicationInput = mock(StopApplicationInput.class); + doReturn(newCommonHeader("request-id-aduit")).when(stopApplicationInput).getCommonHeader(); + doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) + .when(stopApplicationInput).getActionIdentifiers(); + + Future> results = appcProviderLcm.stopApplication + (stopApplicationInput); + Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); + Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // Validation failed + doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); + results = appcProviderLcm.stopApplication(stopApplicationInput); + Assert.assertEquals(failStatus, results.get().getResult().getStatus()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + + // parse exception + doReturn(null).when(validationService).validateInput(any(), any(), any()); + doReturn(null).when(stopApplicationInput).getActionIdentifiers(); + results = appcProviderLcm.stopApplication(stopApplicationInput); + Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() + == results.get().getResult().getStatus().getCode()); + verify(appcProviderLcm, times(1)).executeRequest(any()); + } + + @After + public void tearDown() throws Exception { + if (appcProviderLcm != null) { + appcProviderLcm.close(); + } + } + + private ActionIdentifiers newActionIdentifier(String vnfId, String vnfcId, String vserverId) { + ActionIdentifiersBuilder actionIdentifiersBuilder = new ActionIdentifiersBuilder(); + actionIdentifiersBuilder.setVnfId(vnfId); + actionIdentifiersBuilder.setVnfcName(vnfcId); + actionIdentifiersBuilder.setVserverId(vserverId); + return actionIdentifiersBuilder.build(); + } + + private CommonHeader newCommonHeader(String requestId) { + CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); + commonHeaderBuilder.setRequestId(requestId); + commonHeaderBuilder.setApiVer("2.0.0"); + commonHeaderBuilder.setOriginatorId("originatortest"); + commonHeaderBuilder.setTimestamp(ZULU.getDefaultInstance(LocalDateTime.now(Clock.systemUTC()).toString() + + "Z")); + return commonHeaderBuilder.build(); + } +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderTest.java new file mode 100644 index 000000000..31598c9c9 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/AppcProviderTest.java @@ -0,0 +1,225 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.provider.topology.TopologyService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AppcProvider.class}) +public class AppcProviderTest extends AbstractDataBrokerTest { + + @Mock + private CommonRequestHeader commonRequestHeader; + @Mock + private ConfigPayload configPayload; + @Mock + private VnfResource vnfResource; + @Mock + private TopologyService topologyService; + + private AppcProvider provider; + private DataBroker dataBroker; + + /** + * The @Before annotation is defined in the AbstractDataBrokerTest class. The method setupWithDataBroker is invoked + * from inside the @Before method and is used to initialize the databroker with objects for a test runs. In our case + * we use this oportunity to create an instance of our provider and initialize it (which registers it as a listener + * etc). This method runs before every @Test method below. + */ + @Override + protected void setupWithDataBroker(DataBroker dataBroker) { + super.setupWithDataBroker(dataBroker); + + this.dataBroker = dataBroker; + } + + @Before + public void setUp() throws Exception { + NotificationProviderService nps = mock(NotificationProviderService.class); + RpcProviderRegistry registry = mock(RpcProviderRegistry.class); + BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); + PowerMockito.doReturn(rpcRegistration).when(registry).addRpcImplementation(any(), any()); + + provider = spy(new AppcProvider(dataBroker, nps, registry)); + + PowerMockito.doReturn(topologyService).when(provider).getTopologyService(); + } + + @Test + public void testConstructor() throws Exception { + ExecutorService executorService = Whitebox.getInternalState(provider, "executor"); + Assert.assertNotNull(executorService); + BindingAwareBroker.RpcRegistration internalRpcRegistration = Whitebox.getInternalState(provider, + "rpcRegistration"); + Assert.assertNotNull(internalRpcRegistration); + } + + @Test + public void testClose() throws Exception { + ExecutorService executorService = spy(Executors.newFixedThreadPool(1)); + Whitebox.setInternalState(provider, "executor", executorService); + BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); + Whitebox.setInternalState(provider, "rpcRegistration", rpcRegistration); + provider.close(); + + verify(executorService, times(1)).shutdown(); + verify(rpcRegistration, times(1)).close(); + } + + @Test + public void testModifyConfig() throws Exception { + ModifyConfigInput modifyConfigInput = mock(ModifyConfigInput.class); + doReturn(commonRequestHeader).when(modifyConfigInput).getCommonRequestHeader(); + doReturn(configPayload).when(modifyConfigInput).getConfigPayload(); + // mock output + RpcResult modifyConfigOutput = mock(RpcResult.class); + PowerMockito.doReturn(modifyConfigOutput).when(topologyService).modifyConfig(any(), any()); + + Future> rpcResultFuture = provider.modifyConfig(modifyConfigInput); + + Assert.assertNotNull(rpcResultFuture); + } + + @Test + public void testRebuild() throws Exception { + RebuildInput input = mock(RebuildInput.class); + RpcResult output = mock(RpcResult.class); + doReturn(vnfResource).when(input).getVnfResource(); + doReturn(output).when(topologyService).rebuild(any(), any()); + + Future> rpcResultFuture = provider.rebuild(input); + + Assert.assertNotNull(rpcResultFuture); + } + + @Test + public void testRestart() throws Exception { + RestartInput input = mock(RestartInput.class); + RpcResult output = mock(RpcResult.class); + doReturn(vnfResource).when(input).getVnfResource(); + doReturn(output).when(topologyService).restart(any(), any()); + + Future> rpcResultFuture = provider.restart(input); + + Assert.assertNotNull(rpcResultFuture); + } + + @Test + public void testMigrate() throws Exception { + MigrateInput input = mock(MigrateInput.class); + RpcResult output = mock(RpcResult.class); + doReturn(vnfResource).when(input).getVnfResource(); + doReturn(output).when(topologyService).migrate(any(), any()); + + Future> rpcResultFuture = provider.migrate(input); + + Assert.assertNotNull(rpcResultFuture); + } + + @Test + public void testEvacuate() throws Exception { + EvacuateInput input = mock(EvacuateInput.class); + doReturn(vnfResource).when(input).getVnfResource(); + + Future> rpcResultFuture = provider.evacuate(input); + + Assert.assertNull(rpcResultFuture); + } + + @Test + public void testSnapshot() throws Exception { + SnapshotInput input = mock(SnapshotInput.class); + RpcResult output = mock(RpcResult.class); + doReturn(vnfResource).when(input).getVnfResource(); + doReturn(output).when(topologyService).snapshot(any(), any()); + + Future> rpcResultFuture = provider.snapshot(input); + + Assert.assertNotNull(rpcResultFuture); + } + + @Test + public void testVmstatuscheck() throws Exception { + VmstatuscheckInput input = mock(VmstatuscheckInput.class); + RpcResult output = mock(RpcResult.class); + doReturn(vnfResource).when(input).getVnfResource(); + doReturn(output).when(topologyService).vmstatuscheck(any(), any()); + + Future> rpcResultFuture = provider.vmstatuscheck(input); + + Assert.assertNotNull(rpcResultFuture); + } + + @After + public void tearDown() throws Exception { + if (provider != null) { + provider.close(); + } + } +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/ResponseHeaderBuilderTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/ResponseHeaderBuilderTest.java new file mode 100644 index 000000000..f910a908d --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/ResponseHeaderBuilderTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider; + +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeader; + +public class ResponseHeaderBuilderTest { + + @Test + public void buildHeader() throws Exception { + CommonResponseHeader commonResponseHeader = ResponseHeaderBuilder.buildHeader(true, "request-id", "reason", 1L); + Assert.assertNotNull(commonResponseHeader.getCompleted()); + } +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/topology/TopologyServiceTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/topology/TopologyServiceTest.java new file mode 100644 index 000000000..8bb84b544 --- /dev/null +++ b/appc-provider/appc-provider-bundle/src/test/java/org/onap/appc/provider/topology/TopologyServiceTest.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.provider.topology; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.UUID; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; +import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.provider.AppcProvider; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.internal.verification.VerificationModeFactory.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({TopologyService.class, ConfigurationFactory.class}) +public class TopologyServiceTest { + @Mock + private AppcProvider appcProvider; + private TopologyService topologyService; + + @Before + public void setUp() throws Exception { + mockStatic(ConfigurationFactory.class); + Configuration configuration = mock(Configuration.class); + when(ConfigurationFactory.getConfiguration()).thenReturn(configuration); + doReturn("NODE_NAME").when(configuration).getProperty("appc.provider.vfodl.url"); + + topologyService = spy(new TopologyService(appcProvider)); + } + + @Test + public void modifyConfig() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + ConfigPayload configPayload = mock(ConfigPayload.class); + doReturn("url").when(configPayload).getConfigUrl(); + doReturn("configJson").when(configPayload).getConfigJson(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.modifyConfig(commonRequestHeader, configPayload); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + + @Test + public void migrate() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + VnfResource vnfResource = mock(VnfResource.class); + UUID uuid = mock(UUID.class); + doReturn("uuid-value").when(uuid).getValue(); + doReturn(uuid).when(vnfResource).getVmId(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.migrate(commonRequestHeader, vnfResource); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + + @Test + public void restart() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + VnfResource vnfResource = mock(VnfResource.class); + UUID uuid = mock(UUID.class); + doReturn("uuid-value").when(uuid).getValue(); + doReturn(uuid).when(vnfResource).getVmId(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.restart(commonRequestHeader, vnfResource); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + + @Test + public void rebuild() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + VnfResource vnfResource = mock(VnfResource.class); + UUID uuid = mock(UUID.class); + doReturn("uuid-value").when(uuid).getValue(); + doReturn(uuid).when(vnfResource).getVmId(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.rebuild(commonRequestHeader, vnfResource); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + + @Test + public void snapshot() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + VnfResource vnfResource = mock(VnfResource.class); + UUID uuid = mock(UUID.class); + doReturn("uuid-value").when(uuid).getValue(); + doReturn(uuid).when(vnfResource).getVmId(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.snapshot(commonRequestHeader, vnfResource); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + + @Test + public void vmstatuscheck() throws Exception { + CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); + doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); + VnfResource vnfResource = mock(VnfResource.class); + UUID uuid = mock(UUID.class); + doReturn("uuid-value").when(uuid).getValue(); + doReturn(uuid).when(vnfResource).getVmId(); + PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); + + topologyService.vmstatuscheck(commonRequestHeader, vnfResource); + + verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); + } + +} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderClientTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderClientTest.java deleted file mode 100644 index 58ccc4735..000000000 --- a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderClientTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.Properties; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({AppcProviderClient.class, FrameworkUtil.class}) -public class AppcProviderClientTest { - @Mock - private SvcLogicService svcLogicService; - @Mock - private AppcProviderClient appcProviderClient; - - @Before - public void setUp() throws Exception { - // Prepare all mocks - mockStatic(FrameworkUtil.class); - Bundle mockedBundle = mock(Bundle.class); - PowerMockito.when(FrameworkUtil.getBundle(SvcLogicService.class)).thenReturn(mockedBundle); - - BundleContext mockedBundleContext = mock(BundleContext.class); - Mockito.when(mockedBundle.getBundleContext()).thenReturn(mockedBundleContext); - - ServiceReference svcRef = mock(ServiceReference.class); - Mockito.when(mockedBundleContext.getServiceReference(SvcLogicService.NAME)).thenReturn(svcRef); - - Mockito.when(mockedBundleContext.getService(svcRef)).thenReturn(svcLogicService); - - appcProviderClient = new AppcProviderClient(); - } - - @Test - public void testNonArgumentConstructor() { - AppcProviderClient appcProviderClient = new AppcProviderClient(); - Assert.assertEquals(Whitebox.getInternalState(appcProviderClient, "svcLogic"), svcLogicService); - } - - @Test - public void hasGraph() throws Exception { - doReturn(true).when(svcLogicService).hasGraph(any(), any(), any(), any()); - boolean hasGraph = appcProviderClient.hasGraph("test-module", "test-rpc", "test-version", "test-mode"); - Assert.assertTrue(hasGraph); - } - - @Test - public void execute() throws Exception { - Properties properties = new Properties(); - appcProviderClient.execute("test-module", "test-rpc", "test-version", "test-mode", properties); - verify(svcLogicService, times(1)).execute("test-module", "test-rpc", "test-version", "test-mode", - properties); - } - -} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderLcmTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderLcmTest.java deleted file mode 100644 index f25df9c44..000000000 --- a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderLcmTest.java +++ /dev/null @@ -1,1118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Spy; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.AuditOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.CheckLockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupDeleteOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigBackupOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigExportOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigModifyOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigRestoreOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigScaleoutOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ConfigureOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.EvacuateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.HealthCheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LiveUpgradeOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.LockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.MigrateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RebuildOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.RollbackOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SnapshotOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SoftwareUploadOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartApplicationOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopApplicationOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.StopOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.SyncOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TerminateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.TestOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.UnlockOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.ZULU; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiers; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.action.identifiers.ActionIdentifiersBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.provider.lcm.util.ValidationService; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.time.Clock; -import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -/** - * Integration Test class for AppcProviderLcm. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({FrameworkUtil.class, AppcProviderLcm.class, ValidationService.class}) -public class AppcProviderLcmTest extends AbstractDataBrokerTest { - private Status successStatus = new StatusBuilder().setCode(400).setMessage("success").build(); - private Status failStatus = new StatusBuilder().setCode(401).setMessage("failure").build(); - - private AppcProviderLcm appcProviderLcm; - private DataBroker dataBroker; - @Spy - private ValidationService validationService = ValidationService.getInstance(); - @Mock - private RequestHandlerOutput requestHandlerOutput; - @Mock - private ResponseContext responseContext; - @Mock - private org.onap.appc.domainmodel.lcm.Status successlcmStatus; - - /** - * The @Before annotation is defined in the AbstractDataBrokerTest class. The method setupWithDataBroker is invoked - * from inside the @Before method and is used to initialize the databroker with objects for a test runs. In our case - * we use this oportunity to create an instance of our provider and initialize it (which registers it as a listener - * etc). This method runs before every @Test method below. - */ - @Override - protected void setupWithDataBroker(DataBroker dataBroker) { - super.setupWithDataBroker(dataBroker); - - this.dataBroker = dataBroker; - } - - @Before - public void setUp() throws Exception { - //mock appcProviderLcm - NotificationProviderService nps = mock(NotificationProviderService.class); - RpcProviderRegistry registry = mock(RpcProviderRegistry.class); - BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); - PowerMockito.doReturn(rpcRegistration).when(registry).addRpcImplementation(any(), any()); - appcProviderLcm = spy(new AppcProviderLcm(dataBroker, nps, registry)); - //mock validationService - mockStatic(ValidationService.class); - PowerMockito.when(ValidationService.getInstance()).thenReturn(validationService); - - doReturn(successlcmStatus).when(responseContext).getStatus(); - doReturn(400).when(successlcmStatus).getCode(); - doReturn("success").when(successlcmStatus).getMessage(); - } - - @Test - public void testConstructor() throws Exception { - ExecutorService executorService = Whitebox.getInternalState(appcProviderLcm, "executor"); - Assert.assertNotNull(executorService); - BindingAwareBroker.RpcRegistration internalRpcRegistration = Whitebox.getInternalState(appcProviderLcm, - "rpcRegistration"); - Assert.assertNotNull(internalRpcRegistration); - } - - @Test - public void testClose() throws Exception { - ExecutorService executorService = spy(Executors.newFixedThreadPool(1)); - Whitebox.setInternalState(appcProviderLcm, "executor", executorService); - BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); - Whitebox.setInternalState(appcProviderLcm, "rpcRegistration", rpcRegistration); - appcProviderLcm.close(); - - verify(executorService, times(1)).shutdown(); - verify(rpcRegistration, times(1)).close(); - } - - @Test - public void testRebuild() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - RebuildInput rebuildInput = mock(RebuildInput.class); - doReturn(newCommonHeader("request-id-test")).when(rebuildInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(rebuildInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.rebuild(rebuildInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.rebuild(rebuildInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(rebuildInput).getActionIdentifiers(); - results = appcProviderLcm.rebuild(rebuildInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testRestart() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - RestartInput restartInput = mock(RestartInput.class); - doReturn(newCommonHeader("request-id-test")).when(restartInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(restartInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.restart(restartInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.restart(restartInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(restartInput).getActionIdentifiers(); - results = appcProviderLcm.restart(restartInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testStartApplication() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - StartApplicationInput startApplicationInput = mock(StartApplicationInput.class); - doReturn(newCommonHeader("request-id-test")).when(startApplicationInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(startApplicationInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.startApplication(startApplicationInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.startApplication(startApplicationInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(startApplicationInput).getActionIdentifiers(); - results = appcProviderLcm.startApplication(startApplicationInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testMigrate() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - MigrateInput migrateInput = mock(MigrateInput.class); - doReturn(newCommonHeader("request-id-test")).when(migrateInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(migrateInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.migrate(migrateInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.migrate(migrateInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(migrateInput).getActionIdentifiers(); - results = appcProviderLcm.migrate(migrateInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testEvacuate() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - EvacuateInput evacuateInput = mock(EvacuateInput.class); - doReturn(newCommonHeader("request-id-test")).when(evacuateInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(evacuateInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.evacuate(evacuateInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.evacuate(evacuateInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(evacuateInput).getActionIdentifiers(); - results = appcProviderLcm.evacuate(evacuateInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testSnapshot() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - SnapshotInput snapshotInput = mock(SnapshotInput.class); - doReturn(newCommonHeader("request-id-test")).when(snapshotInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(snapshotInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.snapshot(snapshotInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.snapshot(snapshotInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(snapshotInput).getActionIdentifiers(); - results = appcProviderLcm.snapshot(snapshotInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testRollback() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - RollbackInput rollbackInput = mock(RollbackInput.class); - doReturn(newCommonHeader("request-id-test")).when(rollbackInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(rollbackInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.rollback(rollbackInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.rollback(rollbackInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(rollbackInput).getActionIdentifiers(); - results = appcProviderLcm.rollback(rollbackInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testSync() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - SyncInput syncInput = mock(SyncInput.class); - doReturn(newCommonHeader("request-id-test")).when(syncInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(syncInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.sync(syncInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.sync(syncInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(syncInput).getActionIdentifiers(); - results = appcProviderLcm.sync(syncInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testTerminate() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - TerminateInput terminateInput = mock(TerminateInput.class); - doReturn(newCommonHeader("request-id-test")).when(terminateInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(terminateInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.terminate(terminateInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.terminate(terminateInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(terminateInput).getActionIdentifiers(); - results = appcProviderLcm.terminate(terminateInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigure() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigureInput configureInput = mock(ConfigureInput.class); - doReturn(newCommonHeader("request-id-test")).when(configureInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configureInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configure(configureInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configure(configureInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configureInput).getActionIdentifiers(); - results = appcProviderLcm.configure(configureInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigModify() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigModifyInput configModifyInput = mock(ConfigModifyInput.class); - doReturn(newCommonHeader("request-id-test")).when(configModifyInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configModifyInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configModify(configModifyInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configModify(configModifyInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configModifyInput).getActionIdentifiers(); - results = appcProviderLcm.configModify(configModifyInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigScaleout() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigScaleoutInput configScaleoutInput = mock(ConfigScaleoutInput.class); - doReturn(newCommonHeader("request-id-test")).when(configScaleoutInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configScaleoutInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configScaleout(configScaleoutInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configScaleout(configScaleoutInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configScaleoutInput).getActionIdentifiers(); - results = appcProviderLcm.configScaleout(configScaleoutInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigRestore() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigRestoreInput configRestoreInput = mock(ConfigRestoreInput.class); - doReturn(newCommonHeader("request-id-test")).when(configRestoreInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configRestoreInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configRestore(configRestoreInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configRestore(configRestoreInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configRestoreInput).getActionIdentifiers(); - results = appcProviderLcm.configRestore(configRestoreInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testTest() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - TestInput testInput = mock(TestInput.class); - doReturn(newCommonHeader("request-id-test")).when(testInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(testInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.test(testInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.test(testInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(testInput).getActionIdentifiers(); - results = appcProviderLcm.test(testInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testStop() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - StopInput stopInput = mock(StopInput.class); - doReturn(newCommonHeader("request-id-stop")).when(stopInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(stopInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.stop(stopInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.stop(stopInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(stopInput).getActionIdentifiers(); - results = appcProviderLcm.stop(stopInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testStart() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - StartInput startInput = mock(StartInput.class); - doReturn(newCommonHeader("request-id-start")).when(startInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(startInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.start(startInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.start(startInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(startInput).getActionIdentifiers(); - results = appcProviderLcm.start(startInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testAudit() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - AuditInput auditInput = mock(AuditInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(auditInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(auditInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.audit(auditInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.audit(auditInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(auditInput).getActionIdentifiers(); - results = appcProviderLcm.audit(auditInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testSoftwareUpload() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - SoftwareUploadInput softwareUploadInput = mock(SoftwareUploadInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(softwareUploadInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(softwareUploadInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.softwareUpload(softwareUploadInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.softwareUpload(softwareUploadInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(softwareUploadInput).getActionIdentifiers(); - results = appcProviderLcm.softwareUpload(softwareUploadInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testHealthCheck() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - HealthCheckInput healthCheckInput = mock(HealthCheckInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(healthCheckInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(healthCheckInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.healthCheck(healthCheckInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.healthCheck(healthCheckInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(healthCheckInput).getActionIdentifiers(); - results = appcProviderLcm.healthCheck(healthCheckInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testLiveUpgrade() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - LiveUpgradeInput liveUpgradeInput = mock(LiveUpgradeInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(liveUpgradeInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(liveUpgradeInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.liveUpgrade(liveUpgradeInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.liveUpgrade(liveUpgradeInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(liveUpgradeInput).getActionIdentifiers(); - results = appcProviderLcm.liveUpgrade(liveUpgradeInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testLock() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - LockInput lockInput = mock(LockInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(lockInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(lockInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.lock(lockInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.lock(lockInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(lockInput).getActionIdentifiers(); - results = appcProviderLcm.lock(lockInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testUnlock() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - UnlockInput unlockInput = mock(UnlockInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(unlockInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(unlockInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.unlock(unlockInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.unlock(unlockInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(unlockInput).getActionIdentifiers(); - results = appcProviderLcm.unlock(unlockInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testCheckLock() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - Map additionalContext = new HashMap<>(); - additionalContext.put("locked", "true"); - doReturn(additionalContext).when(responseContext).getAdditionalContext(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - CheckLockInput checkLockInput = mock(CheckLockInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(checkLockInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(checkLockInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.checkLock(checkLockInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.checkLock(checkLockInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(checkLockInput).getActionIdentifiers(); - results = appcProviderLcm.checkLock(checkLockInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigBackup() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigBackupInput configBackupInput = mock(ConfigBackupInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(configBackupInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configBackupInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configBackup(configBackupInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configBackup(configBackupInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configBackupInput).getActionIdentifiers(); - results = appcProviderLcm.configBackup(configBackupInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigBackupDelete() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigBackupDeleteInput configBackupDeleteInput = mock(ConfigBackupDeleteInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(configBackupDeleteInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configBackupDeleteInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configBackupDelete - (configBackupDeleteInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configBackupDelete(configBackupDeleteInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configBackupDeleteInput).getActionIdentifiers(); - results = appcProviderLcm.configBackupDelete(configBackupDeleteInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testConfigExport() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - ConfigExportInput configExportInput = mock(ConfigExportInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(configExportInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(configExportInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.configExport - (configExportInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.configExport(configExportInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(configExportInput).getActionIdentifiers(); - results = appcProviderLcm.configExport(configExportInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @Test - public void testStopApplication() throws Exception { - // Validation success - doReturn("Success").when(successlcmStatus).getMessage(); - doReturn(responseContext).when(requestHandlerOutput).getResponseContext(); - doReturn(requestHandlerOutput).when(appcProviderLcm).executeRequest(any()); - doReturn(null).when(validationService).validateInput(any(), any(), any()); - - StopApplicationInput stopApplicationInput = mock(StopApplicationInput.class); - doReturn(newCommonHeader("request-id-aduit")).when(stopApplicationInput).getCommonHeader(); - doReturn(newActionIdentifier("vnf-id", "vnfc-id", "vserver-id")) - .when(stopApplicationInput).getActionIdentifiers(); - - Future> results = appcProviderLcm.stopApplication - (stopApplicationInput); - Assert.assertTrue(400 == results.get().getResult().getStatus().getCode()); - Assert.assertEquals("Success", results.get().getResult().getStatus().getMessage()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // Validation failed - doReturn(failStatus).when(validationService).validateInput(any(), any(), any()); - results = appcProviderLcm.stopApplication(stopApplicationInput); - Assert.assertEquals(failStatus, results.get().getResult().getStatus()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - - // parse exception - doReturn(null).when(validationService).validateInput(any(), any(), any()); - doReturn(null).when(stopApplicationInput).getActionIdentifiers(); - results = appcProviderLcm.stopApplication(stopApplicationInput); - Assert.assertTrue(LCMCommandStatus.REQUEST_PARSING_FAILED.getResponseCode() - == results.get().getResult().getStatus().getCode()); - verify(appcProviderLcm, times(1)).executeRequest(any()); - } - - @After - public void tearDown() throws Exception { - if (appcProviderLcm != null) { - appcProviderLcm.close(); - } - } - - private ActionIdentifiers newActionIdentifier(String vnfId, String vnfcId, String vserverId) { - ActionIdentifiersBuilder actionIdentifiersBuilder = new ActionIdentifiersBuilder(); - actionIdentifiersBuilder.setVnfId(vnfId); - actionIdentifiersBuilder.setVnfcName(vnfcId); - actionIdentifiersBuilder.setVserverId(vserverId); - return actionIdentifiersBuilder.build(); - } - - private CommonHeader newCommonHeader(String requestId) { - CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); - commonHeaderBuilder.setRequestId(requestId); - commonHeaderBuilder.setApiVer("2.0.0"); - commonHeaderBuilder.setOriginatorId("originatortest"); - commonHeaderBuilder.setTimestamp(ZULU.getDefaultInstance(LocalDateTime.now(Clock.systemUTC()).toString() + - "Z")); - return commonHeaderBuilder.build(); - } -} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderTest.java deleted file mode 100644 index 31598c9c9..000000000 --- a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/AppcProviderTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.EvacuateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.MigrateOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.ModifyConfigOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RebuildOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.RestartOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.SnapshotOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.VmstatuscheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.onap.appc.provider.topology.TopologyService; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({AppcProvider.class}) -public class AppcProviderTest extends AbstractDataBrokerTest { - - @Mock - private CommonRequestHeader commonRequestHeader; - @Mock - private ConfigPayload configPayload; - @Mock - private VnfResource vnfResource; - @Mock - private TopologyService topologyService; - - private AppcProvider provider; - private DataBroker dataBroker; - - /** - * The @Before annotation is defined in the AbstractDataBrokerTest class. The method setupWithDataBroker is invoked - * from inside the @Before method and is used to initialize the databroker with objects for a test runs. In our case - * we use this oportunity to create an instance of our provider and initialize it (which registers it as a listener - * etc). This method runs before every @Test method below. - */ - @Override - protected void setupWithDataBroker(DataBroker dataBroker) { - super.setupWithDataBroker(dataBroker); - - this.dataBroker = dataBroker; - } - - @Before - public void setUp() throws Exception { - NotificationProviderService nps = mock(NotificationProviderService.class); - RpcProviderRegistry registry = mock(RpcProviderRegistry.class); - BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); - PowerMockito.doReturn(rpcRegistration).when(registry).addRpcImplementation(any(), any()); - - provider = spy(new AppcProvider(dataBroker, nps, registry)); - - PowerMockito.doReturn(topologyService).when(provider).getTopologyService(); - } - - @Test - public void testConstructor() throws Exception { - ExecutorService executorService = Whitebox.getInternalState(provider, "executor"); - Assert.assertNotNull(executorService); - BindingAwareBroker.RpcRegistration internalRpcRegistration = Whitebox.getInternalState(provider, - "rpcRegistration"); - Assert.assertNotNull(internalRpcRegistration); - } - - @Test - public void testClose() throws Exception { - ExecutorService executorService = spy(Executors.newFixedThreadPool(1)); - Whitebox.setInternalState(provider, "executor", executorService); - BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); - Whitebox.setInternalState(provider, "rpcRegistration", rpcRegistration); - provider.close(); - - verify(executorService, times(1)).shutdown(); - verify(rpcRegistration, times(1)).close(); - } - - @Test - public void testModifyConfig() throws Exception { - ModifyConfigInput modifyConfigInput = mock(ModifyConfigInput.class); - doReturn(commonRequestHeader).when(modifyConfigInput).getCommonRequestHeader(); - doReturn(configPayload).when(modifyConfigInput).getConfigPayload(); - // mock output - RpcResult modifyConfigOutput = mock(RpcResult.class); - PowerMockito.doReturn(modifyConfigOutput).when(topologyService).modifyConfig(any(), any()); - - Future> rpcResultFuture = provider.modifyConfig(modifyConfigInput); - - Assert.assertNotNull(rpcResultFuture); - } - - @Test - public void testRebuild() throws Exception { - RebuildInput input = mock(RebuildInput.class); - RpcResult output = mock(RpcResult.class); - doReturn(vnfResource).when(input).getVnfResource(); - doReturn(output).when(topologyService).rebuild(any(), any()); - - Future> rpcResultFuture = provider.rebuild(input); - - Assert.assertNotNull(rpcResultFuture); - } - - @Test - public void testRestart() throws Exception { - RestartInput input = mock(RestartInput.class); - RpcResult output = mock(RpcResult.class); - doReturn(vnfResource).when(input).getVnfResource(); - doReturn(output).when(topologyService).restart(any(), any()); - - Future> rpcResultFuture = provider.restart(input); - - Assert.assertNotNull(rpcResultFuture); - } - - @Test - public void testMigrate() throws Exception { - MigrateInput input = mock(MigrateInput.class); - RpcResult output = mock(RpcResult.class); - doReturn(vnfResource).when(input).getVnfResource(); - doReturn(output).when(topologyService).migrate(any(), any()); - - Future> rpcResultFuture = provider.migrate(input); - - Assert.assertNotNull(rpcResultFuture); - } - - @Test - public void testEvacuate() throws Exception { - EvacuateInput input = mock(EvacuateInput.class); - doReturn(vnfResource).when(input).getVnfResource(); - - Future> rpcResultFuture = provider.evacuate(input); - - Assert.assertNull(rpcResultFuture); - } - - @Test - public void testSnapshot() throws Exception { - SnapshotInput input = mock(SnapshotInput.class); - RpcResult output = mock(RpcResult.class); - doReturn(vnfResource).when(input).getVnfResource(); - doReturn(output).when(topologyService).snapshot(any(), any()); - - Future> rpcResultFuture = provider.snapshot(input); - - Assert.assertNotNull(rpcResultFuture); - } - - @Test - public void testVmstatuscheck() throws Exception { - VmstatuscheckInput input = mock(VmstatuscheckInput.class); - RpcResult output = mock(RpcResult.class); - doReturn(vnfResource).when(input).getVnfResource(); - doReturn(output).when(topologyService).vmstatuscheck(any(), any()); - - Future> rpcResultFuture = provider.vmstatuscheck(input); - - Assert.assertNotNull(rpcResultFuture); - } - - @After - public void tearDown() throws Exception { - if (provider != null) { - provider.close(); - } - } -} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/ResponseHeaderBuilderTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/ResponseHeaderBuilderTest.java deleted file mode 100644 index f910a908d..000000000 --- a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/ResponseHeaderBuilderTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.response.header.CommonResponseHeader; - -public class ResponseHeaderBuilderTest { - - @Test - public void buildHeader() throws Exception { - CommonResponseHeader commonResponseHeader = ResponseHeaderBuilder.buildHeader(true, "request-id", "reason", 1L); - Assert.assertNotNull(commonResponseHeader.getCompleted()); - } -} \ No newline at end of file diff --git a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/topology/TopologyServiceTest.java b/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/topology/TopologyServiceTest.java deleted file mode 100644 index 8bb84b544..000000000 --- a/appc-provider/appc-provider-bundle/src/test/java/org/openecomp/appc/provider/topology/TopologyServiceTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.provider.topology; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.UUID; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.common.request.header.CommonRequestHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.config.payload.ConfigPayload; -import org.opendaylight.yang.gen.v1.org.onap.appc.rev160104.vnf.resource.VnfResource; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.provider.AppcProvider; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.internal.verification.VerificationModeFactory.times; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.verifyPrivate; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({TopologyService.class, ConfigurationFactory.class}) -public class TopologyServiceTest { - @Mock - private AppcProvider appcProvider; - private TopologyService topologyService; - - @Before - public void setUp() throws Exception { - mockStatic(ConfigurationFactory.class); - Configuration configuration = mock(Configuration.class); - when(ConfigurationFactory.getConfiguration()).thenReturn(configuration); - doReturn("NODE_NAME").when(configuration).getProperty("appc.provider.vfodl.url"); - - topologyService = spy(new TopologyService(appcProvider)); - } - - @Test - public void modifyConfig() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - ConfigPayload configPayload = mock(ConfigPayload.class); - doReturn("url").when(configPayload).getConfigUrl(); - doReturn("configJson").when(configPayload).getConfigJson(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.modifyConfig(commonRequestHeader, configPayload); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - - @Test - public void migrate() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - VnfResource vnfResource = mock(VnfResource.class); - UUID uuid = mock(UUID.class); - doReturn("uuid-value").when(uuid).getValue(); - doReturn(uuid).when(vnfResource).getVmId(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.migrate(commonRequestHeader, vnfResource); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - - @Test - public void restart() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - VnfResource vnfResource = mock(VnfResource.class); - UUID uuid = mock(UUID.class); - doReturn("uuid-value").when(uuid).getValue(); - doReturn(uuid).when(vnfResource).getVmId(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.restart(commonRequestHeader, vnfResource); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - - @Test - public void rebuild() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - VnfResource vnfResource = mock(VnfResource.class); - UUID uuid = mock(UUID.class); - doReturn("uuid-value").when(uuid).getValue(); - doReturn(uuid).when(vnfResource).getVmId(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.rebuild(commonRequestHeader, vnfResource); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - - @Test - public void snapshot() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - VnfResource vnfResource = mock(VnfResource.class); - UUID uuid = mock(UUID.class); - doReturn("uuid-value").when(uuid).getValue(); - doReturn(uuid).when(vnfResource).getVmId(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.snapshot(commonRequestHeader, vnfResource); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - - @Test - public void vmstatuscheck() throws Exception { - CommonRequestHeader commonRequestHeader = mock(CommonRequestHeader.class); - doReturn("request-id").when(commonRequestHeader).getServiceRequestId(); - VnfResource vnfResource = mock(VnfResource.class); - UUID uuid = mock(UUID.class); - doReturn("uuid-value").when(uuid).getValue(); - doReturn(uuid).when(vnfResource).getVmId(); - PowerMockito.doReturn(true).when(topologyService, "callGraph", any()); - - topologyService.vmstatuscheck(commonRequestHeader, vnfResource); - - verifyPrivate(topologyService, times(1)).invoke("callGraph", any()); - } - -} \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/ArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/ArtifactProcessor.java new file mode 100644 index 000000000..12b6373f7 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/ArtifactProcessor.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts; + +import org.onap.appc.exceptions.APPCException; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; + +/** + * This interface provides api processArtifact which cab have multiple implementation + * for type of artifact app-c receives from sdc + */ +public interface ArtifactProcessor extends Runnable { + /** + * Processes the artifact received from sdc + * @param result an instance of IDistributionClientDownloadResult + * @throws APPCException + */ + void processArtifact(IDistributionClientDownloadResult result) throws APPCException; +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/ArtifactStorageService.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/ArtifactStorageService.java new file mode 100644 index 000000000..044fbd187 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/ArtifactStorageService.java @@ -0,0 +1,329 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.helper; + +import org.apache.commons.lang.StringUtils; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.sdc.artifacts.object.SDCReference; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import javax.sql.rowset.CachedRowSet; +import java.sql.SQLException; +import java.util.ArrayList; + +import static org.onap.appc.sdc.artifacts.helper.Constants.COMMA; +import static org.onap.appc.sdc.artifacts.helper.Constants.AND; + +/** + * Provides methods for storing sdc artifacts into app-c database + */ +public class ArtifactStorageService { + + private DbLibService dbLibService; + + private static final String SCHEMA = "sdnctl"; + + private static final String SELECT_QUERY = Constants.SELECT_FROM + Constants.SDC_ARTIFACTS + + Constants.WHERE + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + Constants.QUERY_PLACEHOLDER + + AND + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + Constants.QUERY_PLACEHOLDER + + AND + Constants.ARTIFACT_TYPE + Constants.QUERY_PLACEHOLDER; + + private static final String SELECT_QUERY_SDC_REFERENCE = Constants.SELECT_FROM + Constants.SDC_REFERENCE + + Constants.WHERE + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + Constants.QUERY_PLACEHOLDER + + AND + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + Constants.QUERY_PLACEHOLDER ; + + private static final String INSERT_QUERY = Constants.INSERT + Constants.SDC_ARTIFACTS + + " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + + Constants.ARTIFACT_NAME +COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + private static final String INSERT_QUERY_WITH_INT_VER = Constants.INSERT + Constants.SDC_ARTIFACTS + + " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + + Constants.ARTIFACT_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + private static final String SDC_REF_INSERT_QUERY = Constants.INSERT + Constants.SDC_REFERENCE + + "( "+ Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + COMMA + + Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE+ COMMA + + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY +COMMA + + Constants.SDC_REFERENCE_FIELDS.ACTION +COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.ARTIFACT_NAME + " ) values (?,?,?,?,?,?)"; + + private static final String SELECT_MAX_INT_VERSION = "SELECT coalesce(max(" + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + ")+1,1) as " + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + + " FROM " + Constants.SDC_ARTIFACTS + Constants.WHERE + Constants.ARTIFACT_NAME + Constants.QUERY_PLACEHOLDER; + + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactStorageService.class); + + /** + * Stores Artifact received from SDC into APP-C database + * @param artifact - SDC Artifact object + * @throws APPCException + */ + public void storeSDCArtifact(SDCArtifact artifact) throws APPCException { + if(logger.isDebugEnabled()){ + logger.debug("Entering storeSDCArtifact with : " + artifact.toString()); + } + try { + initializeDBLibService(); + ArrayList arguments = prepareArguments(artifact); + dbLibService.writeData(INSERT_QUERY,arguments,SCHEMA); + } catch (SQLException e) { + logger.error("Error storing artifact in database : " +artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + if(logger.isDebugEnabled()){ + logger.debug("Exiting storeSDCArtifact"); + } + } + + /** + * Stores Artifact received from SDC and its Reference into APP-C database if it does not exist + * @param artifact - SDC Artifact object + * @param reference - SDC reference object + * @throws APPCException + */ + public void storeSDCArtifactWithReference(SDCArtifact artifact , SDCReference reference) throws APPCException { + if(logger.isDebugEnabled()){ + logger.debug("Entering storeSDCArtifactWithReference with : " + artifact.toString()); + } + try { + initializeDBLibService(); + SDCArtifact existingArtifact = retrieveSDCArtifact(artifact.getResourceName(), artifact.getResourceVersion(),artifact.getArtifactType()); + if (existingArtifact ==null) { // new resource + logger.debug(String.format("Artifact not found for vnfType = %s, version = %s and artifactType = %s. Inserting data." , + artifact.getResourceName(),artifact.getResourceVersion() ,artifact.getArtifactType())); + ArrayList arguments = prepareArguments(artifact); + Integer version = getNextInternalVersion(artifact.getArtifactName()); + arguments.add(version.toString()); + dbLibService.writeData(INSERT_QUERY_WITH_INT_VER,arguments,SCHEMA); + } else { // duplicate + logger.debug(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", + artifact.getArtifactType() , artifact.getResourceName() , artifact.getResourceVersion())); + } + + SDCReference existingReference = retrieveSDCReference(reference.getVnfType(),reference.getFileCategory()); + if(existingReference == null){ + logger.debug("Inserting SDC Reference data: " +reference.toString()); + ArrayList arguments = prepareReferenceArguments(reference); + dbLibService.writeData(SDC_REF_INSERT_QUERY,arguments,SCHEMA); + }else{ + logger.debug("Artifact reference already exists for: " +reference.toString()); + } + } catch (SQLException e) { + logger.error("Error storing artifact to database: " + artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + if(logger.isDebugEnabled()){ + logger.debug("Exiting storeSDCArtifactWithReference"); + } + } + + private Integer getNextInternalVersion(String artifactName) throws APPCException { + if (logger.isDebugEnabled()) { + logger.debug("Entering getNextInternalVersion with artifactName:" + artifactName); + } + Integer version = 1; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(artifactName); + CachedRowSet rowSet = dbLibService.getData(SELECT_MAX_INT_VERSION, arguments, SCHEMA); + if (rowSet.first()) { + version = rowSet.getInt(Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION .toString()); + } + }catch (SQLException e) { + logger.error("Error getting internal version for artifact name " + artifactName , e); + throw new APPCException(e); + } + if (logger.isDebugEnabled()) { + logger.debug("Exiting getNextInternalVersion with retrieved version:" + version.toString()); + } + return version; + } + + private void initializeDBLibService() { + if(dbLibService == null){ + BundleContext context = FrameworkUtil.getBundle(DbLibService.class).getBundleContext(); + ServiceReference serviceReference = context.getServiceReference(DbLibService.class.getName()); + dbLibService = (DbLibService)context.getService(serviceReference); + } + } + + private ArrayList prepareReferenceArguments(SDCReference reference) { + ArrayList arguments = new ArrayList<>(); + arguments.add(reference.getVnfType()); + arguments.add(reference.getVnfcType()); + arguments.add(reference.getFileCategory()); + arguments.add(reference.getAction()); + arguments.add(reference.getArtifactType()); + arguments.add(reference.getArtifactName()); + return arguments; + } + + private ArrayList prepareArguments(SDCArtifact artifact) { + ArrayList arguments = new ArrayList<>(); + arguments.add(artifact.getServiceUUID()); + arguments.add(artifact.getDistributionId()); + arguments.add(artifact.getServiceName()); + arguments.add(truncateServiceDescription(artifact.getServiceDescription())); + arguments.add(artifact.getResourceUUID()); + arguments.add(artifact.getResourceInstanceName()); + arguments.add(artifact.getResourceName()); + arguments.add(artifact.getResourceVersion()); + arguments.add(artifact.getResourceType()); + arguments.add(artifact.getArtifactUUID()); + arguments.add(artifact.getArtifactType()); + arguments.add(artifact.getArtifactVersion()); + arguments.add(artifact.getArtifactDescription()); + arguments.add(artifact.getCreationDate()); + arguments.add(artifact.getArtifactName()); + arguments.add(artifact.getArtifactContent()); + return arguments; + } + + private String truncateServiceDescription(String serviceDescription){ + if (!StringUtils.isBlank(serviceDescription) && serviceDescription.length()>255){ + logger.info("Truncating the SERVICE_DESCRIPTION to 255 characters"); + serviceDescription=serviceDescription.substring(0,255); + } + return serviceDescription; + } + + /** + * Reads the SDC artifact from APP-C database + * @param resourceName - resource Name from SDC Artifact + * @param resourceVersion - resource version from SDC Artifact + * @param artifactType artifact type from SDC Artifact + * @return - SDC_ARTIFACT record if data exists + * @throws APPCException + */ + public SDCArtifact retrieveSDCArtifact(String resourceName, String resourceVersion, String artifactType) throws APPCException { + SDCArtifact artifact = null; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(resourceName); + arguments.add(resourceVersion); + arguments.add(artifactType); + CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY, arguments, SCHEMA); + if (rowSet.first()) { + artifact = new SDCArtifact(); + artifact.setArtifactUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID.toString())); + artifact.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); + artifact.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); + artifact.setArtifactVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION.toString())); + artifact.setArtifactDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION.toString())); + artifact.setArtifactContent(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT.toString())); + + artifact.setResourceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID.toString())); + artifact.setResourceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME.toString())); + artifact.setResourceType(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE.toString())); + artifact.setResourceVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.toString())); + artifact.setResourceInstanceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME.toString())); + + artifact.setServiceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID.toString())); + artifact.setServiceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME.toString())); + artifact.setServiceDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION.toString())); + + artifact.setCreationDate(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE.toString())); + artifact.setDistributionId(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID.toString())); + } + + } catch (SQLException e) { + logger.error("Error query artifact for " + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + " = " + resourceName + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + " = " + resourceVersion + + Constants.ARTIFACT_TYPE + " = " + artifactType, e); + throw new APPCException(e); + } + return artifact; + } + + /** + * Reads the SDC reference from APP-C database + * @param vnfType - vnf Type from SDC reference + * @param fileCategory - file category from SDC reference + * @return - SDC_ARTIFACT record if data exists + * @throws APPCException + */ + public SDCReference retrieveSDCReference(String vnfType, String fileCategory) throws APPCException { + SDCReference reference = null; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(vnfType); + arguments.add(fileCategory); + CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY_SDC_REFERENCE, arguments, SCHEMA); + if (rowSet.first()) { + reference = new SDCReference(); + reference.setVnfType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNF_TYPE.toString())); + reference.setVnfcType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE.toString())); + reference.setFileCategory(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY.toString())); + reference.setAction(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.ACTION.toString())); + reference.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); + reference.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); + } + } catch (SQLException e) { + logger.error("Error querying SDC_REFERENCE for " + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + " = " + vnfType + + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + " = " + fileCategory , e); + throw new APPCException(e); + } + return reference; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/Constants.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/Constants.java new file mode 100644 index 000000000..eacfb5db6 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/Constants.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.helper; + +/** + * Constants required in SDC listener module + */ +public class Constants { + static final String SDC_ARTIFACTS = "ASDC_ARTIFACTS"; + static final String SDC_REFERENCE = "ASDC_REFERENCE"; + + static final String AND = " AND "; + + static final String ARTIFACT_TYPE = "ARTIFACT_TYPE"; + static final String ARTIFACT_NAME = "ARTIFACT_NAME"; + + static final String VF_LICENSE = "VF_LICENSE"; + + public enum SDC_ARTIFACTS_FIELDS { + SERVICE_UUID, + DISTRIBUTION_ID, + SERVICE_NAME, + SERVICE_DESCRIPTION, + RESOURCE_UUID, + RESOURCE_INSTANCE_NAME, + RESOURCE_NAME, + RESOURCE_VERSION, + RESOURCE_TYPE, + ARTIFACT_UUID, + ARTIFACT_VERSION, + ARTIFACT_DESCRIPTION, + INTERNAL_VERSION, + CREATION_DATE, + ARTIFACT_CONTENT + } + + public enum SDC_REFERENCE_FIELDS{ + SDC_REFERENCE_ID, + VNF_TYPE, + VNFC_TYPE, + FILE_CATEGORY, + ACTION + } + + static final String COMMA = " , "; + static final String QUERY_PLACEHOLDER = " = ? "; + static final String SELECT_FROM = "SELECT * FROM " ; + static final String WHERE = " WHERE "; + static final String INSERT = "INSERT INTO "; +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/DependencyModelGenerator.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/DependencyModelGenerator.java new file mode 100644 index 000000000..295ee47c8 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/helper/DependencyModelGenerator.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.helper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.exceptions.APPCException; + +import java.util.ArrayList; +import java.util.List; + +/** + * Provides method for genrating Dependency JSON from Tosca model + */ +public class DependencyModelGenerator { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelGenerator.class); + + /** + * + * @param tosca - tosca string from SDC + * @param vnfType - Vnf Type from tosca + * @return - Dependency JSON in String format + * @throws APPCException is thrown if error occurs + */ + public String getDependencyModel(String tosca, String vnfType) throws APPCException { + logger.debug(String.format("Generating dependency model for vnfType : %s , TOSCA: %s ", vnfType ,tosca)); + String dependencyJson; + DependencyModelParser dependencyModelParser = new DependencyModelParser(); + VnfcDependencyModel vnfcDependencyModel = dependencyModelParser.generateDependencyModel(tosca, vnfType); + + if (vnfcDependencyModel != null && !vnfcDependencyModel.getDependencies().isEmpty()) { + logger.debug(String.format("Dependency Model generated : %s ", vnfcDependencyModel.toString())); + List vnfcs = new ArrayList<>(); + + for (Node node : vnfcDependencyModel.getDependencies()) { + org.onap.appc.sdc.artifacts.object.Vnfc vnfc = new org.onap.appc.sdc.artifacts.object.Vnfc(); + vnfc.setVnfcType(node.getChild().getVnfcType()); + vnfc.setMandatory(node.getChild().isMandatory()); + vnfc.setResilienceType(node.getChild().getResilienceType()); + if (node.getParents() != null && !node.getParents().isEmpty()) { + List parents = new ArrayList<>(); + for (Vnfc parentNode : node.getParents()) { + parents.add(parentNode.getVnfcType()); + } + vnfc.setParents(parents); + } + vnfcs.add(vnfc); + } + ObjectMapper objectMapper = new ObjectMapper(); + + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure + (MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true).writer().withRootName("vnfcs"); + try { + dependencyJson = writer.writeValueAsString(vnfcs); + } catch (JsonProcessingException e) { + logger.error("Error converting dependency model to JSON"); + throw new APPCException("Error converting dependency model to JSON",e); + } + } else { + logger.error("Error generating dependency model from tosca. Empty dependency model"); + throw new APPCException("Error generating dependency model from tosca. Empty dependency model"); + } + return dependencyJson; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java new file mode 100644 index 000000000..7438d3047 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.impl; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventHeader; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.adapter.message.event.EventStatus; +import org.onap.appc.sdc.listener.Util; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.sdc.artifacts.ArtifactProcessor; +import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Provides abstrace implementation for SDC artifact processor + */ +public abstract class AbstractArtifactProcessor implements ArtifactProcessor { + + public static final String PAYLOAD_CHARSET = "UTF-8"; + private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss"; + + protected IDistributionClient client; + protected EventSender eventSender; + + protected INotificationData notification; + protected IResourceInstance resource; + protected IArtifactInfo artifact; + protected URI storeUri; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractArtifactProcessor.class); + + protected ArtifactStorageService artifactStorageService; + + private AbstractArtifactProcessor(){ + artifactStorageService = new ArtifactStorageService(); + } + + AbstractArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri){ + + this(); + this.client = client; + this.eventSender = eventSender; + this.notification = notification; + this.resource = resource; + this.artifact = artifact; + this.storeUri = storeUri; + } + + @Override + public void run(){ + + try{ + logger.info(String.format("Attempting to download artifact %s", artifact)); + // Download artifact + IDistributionClientDownloadResult download = client.download(artifact); + + logger.info(String.format("Download of artifact %s completed with status %s", artifact.getArtifactUUID(), download)); + + // Notify of download status + if (download.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, + DistributionStatusEnum.DOWNLOAD_ERROR), download.getDistributionMessageResult()); + sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), "Download is failed."); + return; + } + + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DOWNLOAD_OK)); + + processArtifact(download); + + client.sendDeploymentStatus( + Util.buildDistributionStatusMessage(client, notification, this.artifact, DistributionStatusEnum.DEPLOY_OK)); + } + catch (Exception e){ + logger.error("Error processing artifact " + this.artifact.toString() ,e); + + client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact, + DistributionStatusEnum.DEPLOY_ERROR), e.getMessage()); + sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), e.getMessage()); + } + } + + + @Override + public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { + String data = null; + if(logger.isDebugEnabled()){ + logger.debug("Entry processArtifact in AbstractArtifactProcessor"); + } + try { + if (download.getArtifactPayload() != null) { + data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET); + } + } catch (UnsupportedEncodingException e) { + logger.error("Error reading artifact with " + PAYLOAD_CHARSET + " encoding" + new String(download.getArtifactPayload()) ,e); + throw new APPCException(e); + } + + SDCArtifact sdcArtifact = getArtifactObject(data); + logger.debug("Constructed SDCArtifact = " + sdcArtifact); + processArtifact(sdcArtifact); + + if(logger.isDebugEnabled()){ + logger.debug("Exit processArtifact in AbstractArtifactProcessor"); + } + } + + protected abstract void processArtifact(SDCArtifact artifact) throws APPCException; + + protected SDCArtifact getArtifactObject(String data){ + + SDCArtifact sdcArtifact = new SDCArtifact(); + + sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); + sdcArtifact.setArtifactName(this.artifact.getArtifactName()); + sdcArtifact.setArtifactType(this.artifact.getArtifactType()); + sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); + sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); + sdcArtifact.setArtifactContent(data); + sdcArtifact.setCreationDate(getCurrentDateTime()); + + sdcArtifact.setDistributionId(this.notification.getDistributionID()); + sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); + sdcArtifact.setServiceName(this.notification.getServiceName()); + sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); + + sdcArtifact.setResourceName(this.resource.getResourceName()); + sdcArtifact.setResourceType(this.resource.getResourceType()); + sdcArtifact.setResourceVersion(this.resource.getResourceVersion()); + sdcArtifact.setResourceUUID(this.resource.getResourceUUID()); + sdcArtifact.setResourceInstanceName(this.resource.getResourceInstanceName()); + + return sdcArtifact; + } + + protected String getCurrentDateTime() { + DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); + Date date = new Date(); + return dateFormat.format(date); + } + + private void sendDCAEEvent(String distributionID, String serviceName, String serviceVersion, String errorMessage) { + if (null == eventSender){ + return; + } + String errorDescription = String.format("SDC distribution of service '%s', version '%s' is failed with reason: '%s'", + serviceName, serviceVersion, errorMessage); + + EventMessage eventMessage = new EventMessage( + new EventHeader((new Date()).toString(), serviceVersion, distributionID), + new EventStatus(401, errorDescription)); + + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java new file mode 100644 index 000000000..293974b79 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.sdc.artifacts.ArtifactProcessor; +import org.onap.appc.sdc.artifacts.object.ArtifactType; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.URI; + +/** + * Factory class for creating instance of Artifact Processor + */ +public class ArtifactProcessorFactory { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactProcessorFactory.class); + + public ArtifactProcessorFactory (){ + + } + + /** + * Provides and instance of Artifact Processor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri + * @return + */ + public ArtifactProcessor getArtifactProcessor(IDistributionClient client, EventSender eventSender, + INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri) { + + logger.debug("Creating artifact processor for artifact type = " + artifact.getArtifactType()); + ArtifactType artifactType = ArtifactType.getArtifactType(artifact.getArtifactType()); + if(artifactType == null){ + return null; + } + ArtifactProcessor artifactProcessor = null; + switch (artifactType){ + case APPC_CONFIG : + artifactProcessor = new ConfigArtifactProcessor(client, eventSender, notification, resource, + artifact, storeUri); + break; + case VF_LICENSE: + artifactProcessor = new LicenseArtifactProcessor(client,eventSender,notification,resource, + artifact,storeUri); + break; + default: + break; + } + return artifactProcessor; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java new file mode 100644 index 000000000..41230ea30 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.impl; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.sdc.listener.ProviderOperations; +import org.onap.appc.sdc.listener.ProviderResponse; +import org.onap.appc.sdc.listener.Util; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.MalformedURLException; +import java.net.URI; + +/** + * Artifact processor for config artifact type + */ +public class ConfigArtifactProcessor extends AbstractArtifactProcessor { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ConfigArtifactProcessor.class); + + /** + * returns an instance of ConfigArtifactProcessor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri an instance of URI + */ + public ConfigArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { + super(client,eventSender,notification,resource,artifact,storeUri); + } + + @Override + public void processArtifact(SDCArtifact artifact) throws APPCException { + String postData = Util.toSdcStoreDocumentInput(notification, resource, super.artifact, artifact.getArtifactContent()); + try { + ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null); + if (result.getStatus() == 200) { + Util.parseResponse(result.getBody()); + } + } catch (MalformedURLException | APPCException e) { + logger.error("Error processing artifact : " + this.artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java new file mode 100644 index 000000000..fe5099785 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.impl; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.licmgr.Constants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang.StringUtils; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.URI; + +/** + * Artifact processor for VNF license artifact type + */ +public class LicenseArtifactProcessor extends AbstractArtifactProcessor { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(LicenseArtifactProcessor.class); + + /** + * returns an instance of ConfigArtifactProcessor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri an instance of URI + */ + public LicenseArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { + super(client,eventSender,notification,resource,artifact,storeUri); + } + + @Override + public void processArtifact(SDCArtifact artifact) throws APPCException { + + String vnfType = artifact.getResourceName(); + String version = artifact.getResourceVersion(); + String packageArtifactID = artifact.getArtifactUUID(); + + if (StringUtils.isEmpty(vnfType) || + StringUtils.isEmpty(version) || + StringUtils.isEmpty(packageArtifactID)) { + String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); + logger.error(errStr); + throw new APPCException(errStr); + } + + try { + SDCArtifact existingArtifact = artifactStorageService.retrieveSDCArtifact(vnfType, version,artifact.getArtifactType()); + + if (existingArtifact ==null) { // new resource + logger.debug("Artifact not found from database for vnfType = " + vnfType + " , version = " + version + " , artifactType = " + artifact.getArtifactType()); + artifactStorageService.storeSDCArtifact(artifact); + } else { // duplicate + logger.debug("Artifact retrieved from database = " + existingArtifact); + logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version)); + } + + } catch (Exception e) { + logger.error("Error processing artifact : " + artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java new file mode 100644 index 000000000..e38188432 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java @@ -0,0 +1,241 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.impl; + +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.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.apache.commons.lang.StringUtils; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.licmgr.Constants; +import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator; +import org.onap.appc.sdc.artifacts.object.Resource; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.onap.appc.sdc.artifacts.object.SDCReference; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; + +import javax.json.Json; +import java.io.*; +import java.net.URI; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ToscaCsarArtifactProcessor extends AbstractArtifactProcessor{ + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ToscaCsarArtifactProcessor.class); + + private DependencyModelGenerator dependencyModelGenerator; + + public ToscaCsarArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri){ + super(client,eventSender,notification,resource,artifact,storeUri); + dependencyModelGenerator = new DependencyModelGenerator(); + } + + @Override + public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { + logger.debug("processing artifact " + super.artifact.getArtifactType()); + byte[] byteArray = download.getArtifactPayload(); + String serviceFileName = ""; + String serviceTemplateContent = ""; + List resources = null; + Map csarFiles = new HashMap<>(); + try (ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(byteArray))) { + ZipEntry entry = inputStream.getNextEntry(); + logger.debug("First Entry = " +entry); + while(entry!= null){ + String filename = entry.getName(); + logger.debug("Next Entry = "+ filename); + + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + String str = null; + StringBuilder sb = new StringBuilder(); + while((str = bufferedReader.readLine()) != null){ + sb.append(new String(str)).append(System.getProperty("line.separator")); + } + csarFiles.put(filename,sb.toString()); + entry = inputStream.getNextEntry(); + } + + } catch (IOException e) { + logger.error("Error Reading TOSCA.meta from CSAR",e); + throw new APPCException(e); + } + serviceFileName = readServiceFileName(csarFiles.get("TOSCA-Metadata/TOSCA.meta")); + logger.debug("Service File Name = " + serviceFileName); + serviceTemplateContent = csarFiles.get(serviceFileName); + + try { + resources = readResources (serviceTemplateContent); + } catch (Exception e) { + logger.error("Error reading resources from " + ", serviceFileName = " + serviceFileName + + ", TOSCA Metadata = " + csarFiles.get("TOSCA-Metadata/TOSCA.meta"),e); + throw new APPCException(e); + } + + for(Resource resource:resources){ + String resourceTemplate = csarFiles.get("Definitions/resource-" + resource.getFileNameTag() + "-template.yml"); + SDCArtifact artifact = this.getArtifactObject(resource,resourceTemplate); + processArtifact(artifact); + } + } + + private String readServiceFileName(String toscaMetadata) { + toscaMetadata = toscaMetadata.substring(toscaMetadata.indexOf("Entry-Definitions"), toscaMetadata.indexOf(System.getProperty("line.separator"),toscaMetadata.indexOf("Entry-Definitions"))); + toscaMetadata =toscaMetadata.split(":")[1].trim(); + return toscaMetadata; + } + + protected SDCArtifact getArtifactObject(Resource resource, String data){ + + SDCArtifact sdcArtifact = new SDCArtifact(); + + sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); + sdcArtifact.setArtifactName(this.artifact.getArtifactName()); + sdcArtifact.setArtifactType(this.artifact.getArtifactType()); + sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); + sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); + sdcArtifact.setArtifactContent(data); + sdcArtifact.setCreationDate(super.getCurrentDateTime()); + + sdcArtifact.setDistributionId(this.notification.getDistributionID()); + sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); + sdcArtifact.setServiceName(this.notification.getServiceName()); + sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); + + sdcArtifact.setResourceName(resource.getName()); + sdcArtifact.setResourceType(resource.getType()); + sdcArtifact.setResourceVersion(resource.getVersion()); + sdcArtifact.setResourceUUID(resource.getUuid()); + sdcArtifact.setResourceInstanceName(resource.getInstanceName()); + + return sdcArtifact; + } + + private List readResources(String serviceTemplateContent) throws IOException { + List resources = new LinkedList<>(); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + JsonNode root = mapper.readTree(serviceTemplateContent); + JsonNode topologyTemplate = root.get("topology_template"); + JsonNode nodeTemplates = topologyTemplate.get("node_templates"); + Iterator> itr = nodeTemplates.fields(); + while(itr.hasNext()){ + Map.Entry entry = itr.next(); + String instanceName = entry.getKey(); + JsonNode nodeTemplate = entry.getValue(); + + String fileNameTag = nodeTemplate.get("type").asText(); + logger.debug("Resource type in Service Template = " + fileNameTag); + fileNameTag = fileNameTag.substring(fileNameTag.lastIndexOf(".")+1,fileNameTag.length()); + String version = nodeTemplate.get("metadata").get("version").asText(); + String uuid = nodeTemplate.get("metadata").get("UUID").asText(); + String name = nodeTemplate.get("metadata").get("name").asText(); + String type = nodeTemplate.get("metadata").get("type").asText(); + + if(!"VF".equalsIgnoreCase(type)){ + continue; + } + + Resource resource = new Resource(); + resource.setFileNameTag(fileNameTag); + resource.setVersion(version); + resource.setUuid(uuid); + resource.setInstanceName(instanceName); + resource.setName(name); + resource.setType(type); + + resources.add(resource); + } + return resources; + } + + + @Override + protected void processArtifact(SDCArtifact artifact) throws APPCException { + String vnfType = artifact.getResourceName(); + String version = artifact.getResourceVersion(); + String packageArtifactID = artifact.getArtifactUUID(); + + if (StringUtils.isEmpty(vnfType) || + StringUtils.isEmpty(version) || + StringUtils.isEmpty(packageArtifactID)) { + String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); + logger.error(errStr); + throw new APPCException(errStr); + } + try { + SDCReference reference = new SDCReference(); + reference.setVnfType(vnfType); + reference.setFileCategory("tosca_model"); + reference.setArtifactName(artifact.getArtifactName()); + logger.debug("Storing TOSCA to SDC Artifact"); + artifactStorageService.storeSDCArtifactWithReference(artifact,reference); + + SDCArtifact dependencyArtifact = getDependencyArtifact(artifact); + SDCReference dependencyReference = new SDCReference(); + dependencyReference.setVnfType(vnfType); + dependencyReference.setFileCategory("tosca_dependency_model"); + dependencyReference.setArtifactName(dependencyArtifact.getArtifactName()); + logger.debug("Storing Dependency to SDC Artifact"); + artifactStorageService.storeSDCArtifactWithReference(dependencyArtifact,dependencyReference); + } catch (Exception e) { + logger.error("Error processing artifact : " + artifact.toString() ); + throw new APPCException(e.getMessage(),e); + } + } + + private SDCArtifact getDependencyArtifact(SDCArtifact toscaArtifact) throws APPCException { + SDCArtifact artifact = new SDCArtifact(); + artifact.setArtifactName("dependency_"+toscaArtifact.getArtifactName()); + String dependencyModel = dependencyModelGenerator.getDependencyModel(toscaArtifact.getArtifactContent(),toscaArtifact.getResourceName()); + artifact.setArtifactContent(dependencyModel); + artifact.setArtifactType("DEPENDENCY_MODEL"); + + artifact.setArtifactUUID(toscaArtifact.getArtifactUUID()); + artifact.setArtifactVersion(toscaArtifact.getArtifactVersion()); + artifact.setArtifactDescription(toscaArtifact.getArtifactDescription()); + artifact.setCreationDate(super.getCurrentDateTime()); + artifact.setDistributionId(toscaArtifact.getDistributionId()); + artifact.setServiceUUID(toscaArtifact.getServiceUUID()); + artifact.setServiceName(toscaArtifact.getServiceName()); + artifact.setServiceDescription(toscaArtifact.getServiceDescription()); + artifact.setResourceName(toscaArtifact.getResourceName()); + artifact.setResourceType(toscaArtifact.getResourceType()); + artifact.setResourceVersion(toscaArtifact.getResourceVersion()); + artifact.setResourceUUID(toscaArtifact.getResourceUUID()); + artifact.setResourceInstanceName(toscaArtifact.getResourceInstanceName()); + return artifact; + } + + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/ArtifactType.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/ArtifactType.java new file mode 100644 index 000000000..790ad2381 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/ArtifactType.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.object; + +/** + * Enummration listing SDC artifact types + */ +public enum ArtifactType { + APPC_CONFIG,VF_LICENSE,TOSCA_CSAR; + + /** + * returns ArtifactType for the input string type + * @param artifactTypeStr + * @return + */ + public static ArtifactType getArtifactType(String artifactTypeStr){ + for(ArtifactType artifactType: ArtifactType.values()){ + if(artifactType.name().equals(artifactTypeStr)){ + return artifactType; + } + } + return null; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Resource.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Resource.java new file mode 100644 index 000000000..6ae441c18 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Resource.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.object; + +public class Resource { + private String name; + private String type; + private String version; + private String uuid; + private String instanceName; + private String fileNameTag; + + public Resource(){ + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public String getFileNameTag() { + return fileNameTag; + } + + public void setFileNameTag(String fileNameTag) { + this.fileNameTag = fileNameTag; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCArtifact.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCArtifact.java new file mode 100644 index 000000000..d5376b570 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCArtifact.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.object; + +/** + * POJO containing metadata about SDC artifact + */ +public class SDCArtifact { + + private String artifactUUID; + + private String artifactName; + + private String artifactType; + + private String artifactVersion; + + private String artifactContent; + + private String artifactDescription; + + private String creationDate; + + private String distributionId; + + + + private String resourceUUID; + + private String resourceName; + + private String resourceType; + + private String resourceVersion; + + private String resourceInstanceName; + + + private String serviceUUID; + + private String serviceName; + + private String serviceDescription; + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactContent() { + return artifactContent; + } + + public void setArtifactContent(String artifactContent) { + this.artifactContent = artifactContent; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getDistributionId() { + return distributionId; + } + + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceUUID() { + return serviceUUID; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + + @Override + public String toString() { + return "artifactUUID = " + artifactUUID + + " , artifactName = " + artifactName + + " , artifactType = " + artifactType + + " , artifactVersion = " + artifactVersion + + " , artifactContent = " + artifactContent + + " , artifactDescription = " + artifactDescription + + " , creationDate = " + creationDate + + " , distributionId = " +distributionId + + " , resourceUUID = " + resourceUUID + + " , resourceName = " + resourceName + + " , resourceType = " + resourceType + + " , resourceVersion = " + resourceVersion + + " , resourceInstanceName = " + resourceInstanceName + + " , serviceUUID = " + serviceUUID + + " , serviceName = " + serviceName + + " , serviceDescription = " + serviceDescription; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCReference.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCReference.java new file mode 100644 index 000000000..2ee6d7c85 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/SDCReference.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.object; + +public class SDCReference { + + private String vnfType; + private String vnfcType; + private String fileCategory; + private String action; + private String artifactType; + private String artifactName; + + public String getVnfType() { + return vnfType; + } + + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public String getVnfcType() { + return vnfcType; + } + + public void setVnfcType(String vnfcType) { + this.vnfcType = vnfcType; + } + + public String getFileCategory() { + return fileCategory; + } + + public void setFileCategory(String fileCategory) { + this.fileCategory = fileCategory; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + @Override + public String toString() { + return "vnfType = " + vnfType+ + ", vnfType = " + vnfType+ + ", fileCategory = " + fileCategory+ + ", action = " + action+ + ", artifactType = " + artifactType+ + ", artifactName = " + artifactName+ + ", vnfType = " + vnfType; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Vnfc.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Vnfc.java new file mode 100644 index 000000000..3e0d3a749 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/artifacts/object/Vnfc.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.artifacts.object; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.List; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonPropertyOrder({"vnfc-type","mandatory","resilience","parents"}) +public class Vnfc { + + @JsonProperty("vnfc-type") + private String vnfcType; + @JsonProperty("mandatory") + private boolean mandatory; + @JsonProperty("resilience") + private String resilienceType; + @JsonProperty("parents") + private List parents; + + public String getVnfcType() { + return vnfcType; + } + + public void setVnfcType(String vnfcType) { + this.vnfcType = vnfcType; + } + public boolean isMandatory() { + return mandatory; + } + + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } + + public String getResilienceType() { + return resilienceType; + } + + public void setResilienceType(String resilienceType) { + this.resilienceType = resilienceType; + } + + public List getParents() { + return parents; + } + + public void setParents(List parents) { + this.parents = parents; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderOperations.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderOperations.java new file mode 100644 index 000000000..fa8340ac7 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderOperations.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.Socket; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; +import java.util.Map.Entry; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ProviderOperations { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); + + private static String basic_auth; + + public static ProviderResponse post(URL url, String json, Map adtl_headers) throws APPCException { + if (json == null) { + throw new APPCException("Provided message was null"); + } + + HttpPost post = null; + try { + post = new HttpPost(url.toExternalForm()); + post.setHeader("Content-Type", "application/json"); + post.setHeader("Accept", "application/json"); + + // Set Auth + if (basic_auth != null) { + post.setHeader("Authorization", "Basic " + basic_auth); + } + + if (adtl_headers != null) { + for (Entry header : adtl_headers.entrySet()) { + post.setHeader(header.getKey(), header.getValue()); + } + } + + StringEntity entity = new StringEntity(json); + entity.setContentType("application/json"); + post.setEntity(new StringEntity(json)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(url); + + int httpCode = 0; + String respBody = null; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + return new ProviderResponse(httpCode, respBody); + } catch (IOException e) { + throw new APPCException(e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user + * The user with optional domain name (for AAF) + * @param password + * The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basic_auth = null; + } + return basic_auth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient(URL url) throws APPCException { + HttpClient client; + if (url.getProtocol().equals("https")) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); + registry.register(new Scheme("https", sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + client = new DefaultHttpClient(); + } + } else if (url.getProtocol().equals("http")) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + public static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + + public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[] { + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderResponse.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderResponse.java new file mode 100644 index 000000000..bf91332c5 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/ProviderResponse.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +public class ProviderResponse { + + private int status; + private String body; + + public ProviderResponse(int status, String body) { + this.status = status; + this.body = body; + } + + public String getBody() { + return body; + } + + public int getStatus() { + return status; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcCallback.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcCallback.java new file mode 100644 index 000000000..8be458200 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcCallback.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.sdc.artifacts.ArtifactProcessor; +import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.INotificationCallback; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.utils.DistributionStatusEnum; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.net.URI; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +public class SdcCallback implements INotificationCallback { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCallback.class); + private ArtifactProcessorFactory artifactProcessorFactory=new ArtifactProcessorFactory(); + + private URI storeUri; + private IDistributionClient client; + + private EventSender eventSender = null; + + private ThreadPoolExecutor executor; + private int threadCount = 10; + + private AtomicBoolean isRunning = new AtomicBoolean(false); + + + public SdcCallback(URI storeUri, IDistributionClient client) { + this.storeUri = storeUri; + this.client = client; + + // Create the thread pool + executor = new ThreadPoolExecutor(threadCount, threadCount, 1, TimeUnit.SECONDS, + new ArrayBlockingQueue(threadCount * 2)); + + // Custom Named thread factory + BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build(); + executor.setThreadFactory(threadFactory); + + isRunning.set(true); + } + + @Override + public void activateCallback(INotificationData data) { + if (null == eventSender) { + try { + BundleContext bctx = FrameworkUtil.getBundle(EventSender.class).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(EventSender.class); + eventSender = (EventSender) bctx.getService(sref); + } catch (Exception e) { + logger.error("SdcCallback failed on initializing EventSender", e); + } + } + + if (isRunning.get()) { + + for(IArtifactInfo artifact:data.getServiceArtifacts()){ + ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(client, eventSender, data, null, artifact, storeUri); + if(artifactProcessor!=null){ + executor.submit(artifactProcessor); + } + } + + for (IResourceInstance resource : data.getResources()) { + for (IArtifactInfo artifact : resource.getArtifacts()) { + logger.info(Util.toSdcStoreDocumentInput(data, resource, artifact, "abc")); + if (executor.getQueue().size() >= threadCount) { + // log warning about job backlog + } + ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(client, eventSender, data, resource, artifact, storeUri); + if(artifactProcessor != null){ + executor.submit(artifactProcessor); + } + else{ + /* Before refactoring of the DownloadAndStoreOp class, the approach was to download all the + artifacts, send the download status, and then perform the processing of artifact if it is + required. Now that we are downloading the artifacts only when its processing is required, + we are sending the download status as positive just to have the same behaviour as before + refactoring. + */ + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK)); + logger.error("Artifact type not supported : " + artifact.getArtifactType()); + } + } + } + } else { + // TODO - return a failed result so sdc knows we are shut down + } + } + + public void stop() { + stop(10); + } + + public void stop(int waitSec) { + isRunning.set(false); + logger.info(String.format("Stopping the SDC listener and waiting up to %ds for %d pending jobs", waitSec, + executor.getQueue().size())); + boolean cleanShutdown = false; + executor.shutdown(); + try { + cleanShutdown = executor.awaitTermination(waitSec, TimeUnit.SECONDS); + executor.shutdownNow(); // In case of timeout + } catch (InterruptedException e) { + logger.error("Error in SdcCallback for stop(int waitSec) method due to InterruptedException: reason= " + e.getMessage(), e); + } + logger.info(String.format("Attempting to shutdown cleanly: %s", cleanShutdown ? "SUCCESS" : "FAILURE")); + logger.info("Shutdown complete."); + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcConfig.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcConfig.java new file mode 100644 index 000000000..86ba9e1f5 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcConfig.java @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.sdc.api.consumer.IConfiguration; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class SdcConfig implements IConfiguration { + + private String host; + private String consumer; + private String consumerId; + private String env; + private String keystorePath; + private String keystorePass; + /** Polling internal is time between listening sessions */ + private int pollingInterval; + /** Polling timeout is the time to listen for (dmaap timeout url param)/1000 */ + private int pollingTimeout; + private List types = new ArrayList<>(); + private String user; + private String pass; + + private URI storeOp; + + private Properties props; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcConfig.class); + + SdcConfig(Properties props) throws Exception { + this.props = props; + init(); + } + + private void init() throws Exception { + if (props == null) { + logger.error("SdcConfig init is skipped due to properties is null"); + return; + } + + // Keystore for ca cert + keystorePath = props.getProperty("appc.sdc.keystore.path"); + keystorePass = props.getProperty("appc.sdc.keystore.pass"); + + // ASDC host + host = props.getProperty("appc.sdc.host"); + env = props.getProperty("appc.sdc.env"); + user = props.getProperty("appc.sdc.user"); + pass = props.getProperty("appc.sdc.pass"); + + // DMaaP properties + consumer = props.getProperty("appc.sdc.consumer"); + consumerId = props.getProperty("appc.sdc.consumer.id"); + + pollingInterval = Integer.valueOf(props.getProperty("interval", "60")); + + // Client uses cambriaClient-0.2.4 which throws non relevant (wrong) + // exceptions with times > 30s + pollingTimeout = Integer.valueOf(props.getProperty("timeout", "25")); + + // Anything less than 60 and we risk 429 Too Many Requests + if (pollingInterval < 60) { + pollingInterval = 60; + } + + if (pollingInterval > pollingTimeout) { + logger.warn(String.format( + "Message acknowledgement may be delayed by %ds in the ADSC listener. [Listening Time: %s, Poll Period: %s]", + pollingInterval - pollingTimeout, pollingTimeout, pollingInterval)); + } + + logParams(); + + // Download type + /* + This types seems redundant, as it looks from the code that they are not being used anywhere + */ + types.add("APPC_CONFIG"); + types.add("VF_LICENSE"); + // types.add("TOSCA_CSAR"); commenting it out as we are not listening to TOSCA_CSAR + + storeOp = new URI(props.getProperty("appc.sdc.provider.url")); + } + + @Override + public boolean activateServerTLSAuth() { + return false; + } + + public boolean isFilterInEmptyResources() { + return false; + } + + @Override + public String getAsdcAddress() { + return host; + } + + @Override + public String getConsumerGroup() { + return consumer; + } + + @Override + public String getConsumerID() { + return consumerId; + } + + @Override + public String getEnvironmentName() { + return env; + } + + @Override + public String getKeyStorePassword() { + return keystorePass; + } + + @Override + public String getKeyStorePath() { + return keystorePath; + } + + @Override + public String getPassword() { + return pass; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + @Override + public List getRelevantArtifactTypes() { + return types; + } + + @Override + public String getUser() { + return user; + } + + @Override + public Boolean isUseHttpsWithDmaap(){ + return true; + } + + URI getStoreOpURI() { + return storeOp; + } + + /** + * Logs the relevant parameters + */ + private void logParams() { + Map params = new HashMap<>(); + params.put("SDC Host", getAsdcAddress()); + params.put("SDC Environment", getEnvironmentName()); + params.put("Consumer Name", getConsumerGroup()); + params.put("Consumer ID", getConsumerID()); + params.put("Poll Active Wait", String.valueOf(getPollingInterval())); + params.put("Poll Timeout", String.valueOf(getPollingTimeout())); + + logger.info(String.format("SDC Params: %s", params)); + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcListener.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcListener.java new file mode 100644 index 000000000..b204a54f7 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/SdcListener.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.results.IDistributionClientResult; +import org.openecomp.sdc.impl.DistributionClientFactory; +import org.openecomp.sdc.utils.DistributionActionResultEnum; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * SDC listener handles bundle start and stop through start and stop method.

+ * Register connection with SDC server based on properties file configuration when start, + * and disconnect with SDC server when stop. + */ +public class SdcListener { + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcListener.class); + + /** + * The bundle context + */ + private IDistributionClient client; + private SdcCallback callback; + private SdcConfig config; + private CountDownLatch latch; + + private Thread startThread = null; + + @SuppressWarnings("unused") + public void start() throws Exception { + // Add timestamp to the log to differentiate the jmeter run testing calls. + final long timeStamp = System.currentTimeMillis(); + logger.info(String.format("[%d] Starting SDC Listener", timeStamp)); + + Configuration configuration = ConfigurationFactory.getConfiguration(); + Properties props = configuration.getProperties(); + config = new SdcConfig(props); + logger.debug(String.format("[%d] created SDC config", timeStamp)); + + client = DistributionClientFactory.createDistributionClient(); + logger.debug(String.format("[%d] created SDC client", timeStamp)); + + callback = new SdcCallback(config.getStoreOpURI(), client); + logger.debug(String.format("[%d] created SDC callback", timeStamp)); + + latch = new CountDownLatch(1); + + startThread = new Thread(new StartRunnable(timeStamp)); + startThread.setName(String.format("[%d] sdcListener start", timeStamp)); + logger.debug(String.format("[%d] created SDC initialization thread", timeStamp)); + startThread.start(); + } + + @SuppressWarnings("unused") + public void stop() throws InterruptedException { + // Add timestamp to the log to differentiate the jmeter run testing calls. + final long timeStamp = System.currentTimeMillis(); + logger.info(String.format("[%d] Stopping SDC Listener", timeStamp)); + + stopStartThread(timeStamp); + + if (latch != null) { + logger.debug(String.format("[%d] waiting SDC latch count to 0 for 10 seconds", timeStamp)); + latch.await(10, TimeUnit.SECONDS); + latch = null; + } + + if (callback != null) { + logger.debug(String.format("[%d] stopping SDC callback", timeStamp)); + callback.stop(); + callback = null; + } + if (client != null) { + logger.debug(String.format("[%d] stopping SDC client", timeStamp)); + client.stop(); + client = null; + + } + logger.info(String.format("[%d] SDC Listener stopped successfully", timeStamp)); + } + + void stopStartThread(long timeStamp) throws InterruptedException { + if (startThread == null) { + return; + } + + if (startThread.getState() == Thread.State.TERMINATED) { + logger.debug(String.format("[%d] SDC thread(%s) is already terminated.", + timeStamp, startThread.getName())); + } else { + logger.debug(String.format("[%d] SDC thread(%s) is to be interrupted with state(%s)", + timeStamp, startThread.getName(), startThread.getState().toString())); + + startThread.interrupt(); + + logger.debug(String.format("[%d] SDC thread(%s) has been interrupted(%s) with state(%s)", + timeStamp, startThread.getName(), startThread.isInterrupted(), + startThread.getState().toString())); + } + startThread = null; + } + + /** + * Runnable implementation for actual initialization during SDC listener start + */ + class StartRunnable implements Runnable { + private final long timeStamp; + + StartRunnable(long theTimeStamp) { + timeStamp = theTimeStamp; + } + + /** + * This run method calls SDC client for init and start which are synchronized calls along with stop. + * To interrupt this thread at stop time, we added thread interrupted checking in each step + * for earlier interruption. + */ + @Override + public void run() { + if (!initialRegistration()) { + logger.warn(String.format("[%d] SDC thread initial registration failed.", timeStamp)); + } + + if (isThreadInterrupted("after initial registration")) { + return; + } + + IDistributionClientResult result = client.init(config, callback); + + if (isThreadInterrupted("after client init")) { + return; + } + + if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { + client.start(); + } else { + logger.error(String.format("[%d] Could not register SDC client. %s - %s", + timeStamp, result.getDistributionActionResult(), result.getDistributionMessageResult())); + } + + latch.countDown(); + } + + private boolean initialRegistration() { + try { + final String jsonTemplate = + "{\"consumerName\": \"%s\",\"consumerSalt\": \"%s\",\"consumerPassword\":\"%s\"}"; + String saltedPassStr = org.openecomp.tlv.sdc.security.Passwords.hashPassword(config.getPassword()); + if (saltedPassStr == null || !saltedPassStr.contains(":")) { + return false; + } + + String[] saltedPass = saltedPassStr.split(":"); + String json = String.format(jsonTemplate, config.getUser(), saltedPass[0], saltedPass[1]); + + Map headers = new HashMap<>(); + // TODO - Replace the header below to sdc's requirements. What should the new value be + headers.put("USER_ID", "test"); + + // TODO - How to format the url. Always same endpoint or ports? + String host = config.getAsdcAddress(); + URL url = new URL(String.format("http%s://%s/sdc2/rest/v1/consumers", + host.contains("443") ? "s" : "", host)); + + logger.info(String.format("Attempting to register user %s on %s with salted pass of %s", + config.getUser(), url, saltedPass[1])); + + ProviderOperations providerOperations = new ProviderOperations(); + ProviderResponse result = providerOperations.post(url, json, headers); + return result.getStatus() == 200; + } catch (Exception e) { + logger.error( + "Error performing initial registration with SDC server. User may not be able to connect", + e); + return false; + } + } + + private boolean isThreadInterrupted(String details) { + if (Thread.currentThread().isInterrupted()) { + logger.info(String.format("[%d] SDC thread interrupted %s.", timeStamp, details)); + return true; + } + return false; + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/Util.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/Util.java new file mode 100644 index 000000000..bc4b4a896 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/appc/sdc/listener/Util.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.appc.exceptions.APPCException; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +public class Util { + + // TODO - Use the yang builder instead + public static String toSdcStoreDocumentInput(INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, String data) { + JSONObject json = new JSONObject(); + + JSONObject requestInfo = new JSONObject(); + requestInfo.put("request-id", notification.getServiceUUID()); + requestInfo.put("request-action", "StoreSdcDocumentRequest"); + requestInfo.put("source", "SDC"); + + JSONObject docParams = new JSONObject(); + docParams.put("service-uuid", notification.getServiceUUID()); + docParams.put("distribution-id", notification.getDistributionID()); + docParams.put("service-name", notification.getServiceName()); + docParams.put("service-description", notification.getServiceDescription()); + docParams.put("service-artifacts", "[]"); + docParams.put("resource-uuid", resource.getResourceUUID()); + docParams.put("resource-instance-name", resource.getResourceInstanceName()); + docParams.put("resource-name", resource.getResourceName()); + docParams.put("resource-version", resource.getResourceVersion()); + docParams.put("resource-type", resource.getResourceType()); + docParams.put("artifact-uuid", artifact.getArtifactUUID()); + docParams.put("artifact-name", artifact.getArtifactName()); + docParams.put("artifact-type", artifact.getArtifactType()); + docParams.put("artifact-version", artifact.getArtifactVersion()); + docParams.put("artifact-description", artifact.getArtifactDescription()); + docParams.put("artifact-contents", data); + + json.put("request-information", requestInfo); + json.put("document-parameters", docParams); + + return String.format("{\"input\": %s}", json.toString()); + } + + public static boolean parseResponse(String input) throws APPCException { + JSONObject result, output, response; + try { + result = new JSONObject(input); + output = result.getJSONObject("output"); + response = output.getJSONObject("config-document-response"); + String id = response.getString("request-id"); + String status = response.getString("status"); + if (status.equals(DistributionStatusEnum.DEPLOY_OK.toString())) { + return true; + } else { + String error = response.optString("error-reason"); + String msg = error.isEmpty() ? "No Reason Provided" : error; + throw new APPCException(msg); + } + } catch (JSONException jse) { + throw new APPCException("Did not get valid json from provider.", jse); + } + } + + public static IDistributionStatusMessage buildDistributionStatusMessage(final IDistributionClient client, + final INotificationData data, final IArtifactInfo relevantArtifact, final DistributionStatusEnum status) { + IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { + + @Override + public long getTimestamp() { + long currentTimeMillis = System.currentTimeMillis(); + return currentTimeMillis; + } + + @Override + public DistributionStatusEnum getStatus() { + return status; + } + + @Override + public String getDistributionID() { + return data.getDistributionID(); + } + + @Override + public String getConsumerID() { + return client.getConfiguration().getConsumerID(); + } + + @Override + public String getArtifactURL() { + return relevantArtifact.getArtifactURL(); + } + }; + return statusMessage; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/tlv/sdc/security/Passwords.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/tlv/sdc/security/Passwords.java new file mode 100644 index 000000000..30b275a51 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/onap/tlv/sdc/security/Passwords.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.tlv.sdc.security; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Random; + +/** + * A copy from the org.openecomp.sdc:security-utils artifact that works with java 7. + */ +public class Passwords { + + private static final Random RANDOM = new SecureRandom(); + private static final int SALT = 0; + private static final int HASH = 1; + private static final String HASH_ALGORITHM = "SHA-256"; + + /** + * static utility class + */ + private Passwords() { + } + + /** + * the method calculates a hash with a generated salt for the given password + * + * @param password + * @return a "salt:hash" value + */ + public static String hashPassword(String password) { + byte[] salt = getNextSalt(); + byte byteData[] = hash(salt, password.getBytes()); + if (byteData != null) { + return toHex(salt) + ":" + toHex(byteData); + } + return null; + + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param expectedHash + * @return + */ + public static boolean isExpectedPassword(String password, String expectedHash) { + String[] params = expectedHash.split(":"); + return isExpectedPassword(password, params[SALT], params[HASH]); + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param salt + * @param hash + * the hash generated using the salt + * @return true if the password matched the hash + */ + public static boolean isExpectedPassword(String password, String salt, String hash) { + byte[] saltBytes = fromHex(salt); + byte[] hashBytes = fromHex(hash); + + byte byteData[] = hash(saltBytes, password.getBytes()); + if (byteData != null) { + return Arrays.equals(byteData, hashBytes); + } + return false; + } + + public static void main(String[] args) { + if (args.length > 1 || args.length > 0) { + System.out.println("[" + hashPassword(args[0]) + "]"); + } else { + System.out.println("no passward passed."); + } + + } + + /** + * Returns a random salt to be used to hash a password. + * + * @return a 16 bytes random salt + */ + private static byte[] getNextSalt() { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + return salt; + } + + /** + * hase's the salt and value using the chosen algorithm + * + * @param salt + * @param password + * @return an array of bytes resulting from the hash + */ + private static byte[] hash(byte[] salt, byte[] password) { + MessageDigest md; + byte[] byteData = null; + try { + md = MessageDigest.getInstance(HASH_ALGORITHM); + md.update(salt); + md.update(password); + byteData = md.digest(); + } catch (NoSuchAlgorithmException e) { + System.out.println("in vlide algorithem name"); + } + return byteData; + } + + /** + * Converts a string of hexadecimal characters into a byte array. + * + * @param hex + * the hex string + * @return the hex string decoded into a byte array + */ + private static byte[] fromHex(String hex) { + byte[] binary = new byte[hex.length() / 2]; + for (int i = 0; i < binary.length; i++) { + binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); + } + return binary; + } + + /** + * Converts a byte array into a hexadecimal string. + * + * @param array + * the byte array to convert + * @return a length*2 character string encoding the byte array + */ + private static String toHex(byte[] array) { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = (array.length * 2) - hex.length(); + if (paddingLength > 0) + return String.format("%0" + paddingLength + "d", 0) + hex; + else + return hex; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java deleted file mode 100644 index 12b6373f7..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts; - -import org.onap.appc.exceptions.APPCException; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; - -/** - * This interface provides api processArtifact which cab have multiple implementation - * for type of artifact app-c receives from sdc - */ -public interface ArtifactProcessor extends Runnable { - /** - * Processes the artifact received from sdc - * @param result an instance of IDistributionClientDownloadResult - * @throws APPCException - */ - void processArtifact(IDistributionClientDownloadResult result) throws APPCException; -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java deleted file mode 100644 index 044fbd187..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java +++ /dev/null @@ -1,329 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.helper; - -import org.apache.commons.lang.StringUtils; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.sdc.artifacts.object.SDCReference; -import org.onap.ccsdk.sli.core.dblib.DbLibService; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import javax.sql.rowset.CachedRowSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import static org.onap.appc.sdc.artifacts.helper.Constants.COMMA; -import static org.onap.appc.sdc.artifacts.helper.Constants.AND; - -/** - * Provides methods for storing sdc artifacts into app-c database - */ -public class ArtifactStorageService { - - private DbLibService dbLibService; - - private static final String SCHEMA = "sdnctl"; - - private static final String SELECT_QUERY = Constants.SELECT_FROM + Constants.SDC_ARTIFACTS + - Constants.WHERE + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + Constants.QUERY_PLACEHOLDER + - AND + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + Constants.QUERY_PLACEHOLDER + - AND + Constants.ARTIFACT_TYPE + Constants.QUERY_PLACEHOLDER; - - private static final String SELECT_QUERY_SDC_REFERENCE = Constants.SELECT_FROM + Constants.SDC_REFERENCE + - Constants.WHERE + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + Constants.QUERY_PLACEHOLDER + - AND + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + Constants.QUERY_PLACEHOLDER ; - - private static final String INSERT_QUERY = Constants.INSERT + Constants.SDC_ARTIFACTS + - " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + - Constants.ARTIFACT_TYPE + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + - Constants.ARTIFACT_NAME +COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - private static final String INSERT_QUERY_WITH_INT_VER = Constants.INSERT + Constants.SDC_ARTIFACTS + - " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + - Constants.ARTIFACT_TYPE + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + - Constants.ARTIFACT_NAME + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + COMMA + - Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - private static final String SDC_REF_INSERT_QUERY = Constants.INSERT + Constants.SDC_REFERENCE + - "( "+ Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + COMMA + - Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE+ COMMA + - Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY +COMMA + - Constants.SDC_REFERENCE_FIELDS.ACTION +COMMA + - Constants.ARTIFACT_TYPE + COMMA + - Constants.ARTIFACT_NAME + " ) values (?,?,?,?,?,?)"; - - private static final String SELECT_MAX_INT_VERSION = "SELECT coalesce(max(" + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + ")+1,1) as " + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + - " FROM " + Constants.SDC_ARTIFACTS + Constants.WHERE + Constants.ARTIFACT_NAME + Constants.QUERY_PLACEHOLDER; - - - private final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactStorageService.class); - - /** - * Stores Artifact received from SDC into APP-C database - * @param artifact - SDC Artifact object - * @throws APPCException - */ - public void storeSDCArtifact(SDCArtifact artifact) throws APPCException { - if(logger.isDebugEnabled()){ - logger.debug("Entering storeSDCArtifact with : " + artifact.toString()); - } - try { - initializeDBLibService(); - ArrayList arguments = prepareArguments(artifact); - dbLibService.writeData(INSERT_QUERY,arguments,SCHEMA); - } catch (SQLException e) { - logger.error("Error storing artifact in database : " +artifact.toString(),e); - throw new APPCException(e.getMessage(),e); - } - if(logger.isDebugEnabled()){ - logger.debug("Exiting storeSDCArtifact"); - } - } - - /** - * Stores Artifact received from SDC and its Reference into APP-C database if it does not exist - * @param artifact - SDC Artifact object - * @param reference - SDC reference object - * @throws APPCException - */ - public void storeSDCArtifactWithReference(SDCArtifact artifact , SDCReference reference) throws APPCException { - if(logger.isDebugEnabled()){ - logger.debug("Entering storeSDCArtifactWithReference with : " + artifact.toString()); - } - try { - initializeDBLibService(); - SDCArtifact existingArtifact = retrieveSDCArtifact(artifact.getResourceName(), artifact.getResourceVersion(),artifact.getArtifactType()); - if (existingArtifact ==null) { // new resource - logger.debug(String.format("Artifact not found for vnfType = %s, version = %s and artifactType = %s. Inserting data." , - artifact.getResourceName(),artifact.getResourceVersion() ,artifact.getArtifactType())); - ArrayList arguments = prepareArguments(artifact); - Integer version = getNextInternalVersion(artifact.getArtifactName()); - arguments.add(version.toString()); - dbLibService.writeData(INSERT_QUERY_WITH_INT_VER,arguments,SCHEMA); - } else { // duplicate - logger.debug(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", - artifact.getArtifactType() , artifact.getResourceName() , artifact.getResourceVersion())); - } - - SDCReference existingReference = retrieveSDCReference(reference.getVnfType(),reference.getFileCategory()); - if(existingReference == null){ - logger.debug("Inserting SDC Reference data: " +reference.toString()); - ArrayList arguments = prepareReferenceArguments(reference); - dbLibService.writeData(SDC_REF_INSERT_QUERY,arguments,SCHEMA); - }else{ - logger.debug("Artifact reference already exists for: " +reference.toString()); - } - } catch (SQLException e) { - logger.error("Error storing artifact to database: " + artifact.toString(),e); - throw new APPCException(e.getMessage(),e); - } - if(logger.isDebugEnabled()){ - logger.debug("Exiting storeSDCArtifactWithReference"); - } - } - - private Integer getNextInternalVersion(String artifactName) throws APPCException { - if (logger.isDebugEnabled()) { - logger.debug("Entering getNextInternalVersion with artifactName:" + artifactName); - } - Integer version = 1; - try { - initializeDBLibService(); - ArrayList arguments = new ArrayList<>(); - arguments.add(artifactName); - CachedRowSet rowSet = dbLibService.getData(SELECT_MAX_INT_VERSION, arguments, SCHEMA); - if (rowSet.first()) { - version = rowSet.getInt(Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION .toString()); - } - }catch (SQLException e) { - logger.error("Error getting internal version for artifact name " + artifactName , e); - throw new APPCException(e); - } - if (logger.isDebugEnabled()) { - logger.debug("Exiting getNextInternalVersion with retrieved version:" + version.toString()); - } - return version; - } - - private void initializeDBLibService() { - if(dbLibService == null){ - BundleContext context = FrameworkUtil.getBundle(DbLibService.class).getBundleContext(); - ServiceReference serviceReference = context.getServiceReference(DbLibService.class.getName()); - dbLibService = (DbLibService)context.getService(serviceReference); - } - } - - private ArrayList prepareReferenceArguments(SDCReference reference) { - ArrayList arguments = new ArrayList<>(); - arguments.add(reference.getVnfType()); - arguments.add(reference.getVnfcType()); - arguments.add(reference.getFileCategory()); - arguments.add(reference.getAction()); - arguments.add(reference.getArtifactType()); - arguments.add(reference.getArtifactName()); - return arguments; - } - - private ArrayList prepareArguments(SDCArtifact artifact) { - ArrayList arguments = new ArrayList<>(); - arguments.add(artifact.getServiceUUID()); - arguments.add(artifact.getDistributionId()); - arguments.add(artifact.getServiceName()); - arguments.add(truncateServiceDescription(artifact.getServiceDescription())); - arguments.add(artifact.getResourceUUID()); - arguments.add(artifact.getResourceInstanceName()); - arguments.add(artifact.getResourceName()); - arguments.add(artifact.getResourceVersion()); - arguments.add(artifact.getResourceType()); - arguments.add(artifact.getArtifactUUID()); - arguments.add(artifact.getArtifactType()); - arguments.add(artifact.getArtifactVersion()); - arguments.add(artifact.getArtifactDescription()); - arguments.add(artifact.getCreationDate()); - arguments.add(artifact.getArtifactName()); - arguments.add(artifact.getArtifactContent()); - return arguments; - } - - private String truncateServiceDescription(String serviceDescription){ - if (!StringUtils.isBlank(serviceDescription) && serviceDescription.length()>255){ - logger.info("Truncating the SERVICE_DESCRIPTION to 255 characters"); - serviceDescription=serviceDescription.substring(0,255); - } - return serviceDescription; - } - - /** - * Reads the SDC artifact from APP-C database - * @param resourceName - resource Name from SDC Artifact - * @param resourceVersion - resource version from SDC Artifact - * @param artifactType artifact type from SDC Artifact - * @return - SDC_ARTIFACT record if data exists - * @throws APPCException - */ - public SDCArtifact retrieveSDCArtifact(String resourceName, String resourceVersion, String artifactType) throws APPCException { - SDCArtifact artifact = null; - try { - initializeDBLibService(); - ArrayList arguments = new ArrayList<>(); - arguments.add(resourceName); - arguments.add(resourceVersion); - arguments.add(artifactType); - CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY, arguments, SCHEMA); - if (rowSet.first()) { - artifact = new SDCArtifact(); - artifact.setArtifactUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID.toString())); - artifact.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); - artifact.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); - artifact.setArtifactVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION.toString())); - artifact.setArtifactDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION.toString())); - artifact.setArtifactContent(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT.toString())); - - artifact.setResourceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID.toString())); - artifact.setResourceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME.toString())); - artifact.setResourceType(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE.toString())); - artifact.setResourceVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.toString())); - artifact.setResourceInstanceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME.toString())); - - artifact.setServiceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID.toString())); - artifact.setServiceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME.toString())); - artifact.setServiceDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION.toString())); - - artifact.setCreationDate(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE.toString())); - artifact.setDistributionId(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID.toString())); - } - - } catch (SQLException e) { - logger.error("Error query artifact for " + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + " = " + resourceName + - Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + " = " + resourceVersion + - Constants.ARTIFACT_TYPE + " = " + artifactType, e); - throw new APPCException(e); - } - return artifact; - } - - /** - * Reads the SDC reference from APP-C database - * @param vnfType - vnf Type from SDC reference - * @param fileCategory - file category from SDC reference - * @return - SDC_ARTIFACT record if data exists - * @throws APPCException - */ - public SDCReference retrieveSDCReference(String vnfType, String fileCategory) throws APPCException { - SDCReference reference = null; - try { - initializeDBLibService(); - ArrayList arguments = new ArrayList<>(); - arguments.add(vnfType); - arguments.add(fileCategory); - CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY_SDC_REFERENCE, arguments, SCHEMA); - if (rowSet.first()) { - reference = new SDCReference(); - reference.setVnfType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNF_TYPE.toString())); - reference.setVnfcType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE.toString())); - reference.setFileCategory(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY.toString())); - reference.setAction(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.ACTION.toString())); - reference.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); - reference.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); - } - } catch (SQLException e) { - logger.error("Error querying SDC_REFERENCE for " + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + " = " + vnfType + - Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + " = " + fileCategory , e); - throw new APPCException(e); - } - return reference; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java deleted file mode 100644 index eacfb5db6..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.helper; - -/** - * Constants required in SDC listener module - */ -public class Constants { - static final String SDC_ARTIFACTS = "ASDC_ARTIFACTS"; - static final String SDC_REFERENCE = "ASDC_REFERENCE"; - - static final String AND = " AND "; - - static final String ARTIFACT_TYPE = "ARTIFACT_TYPE"; - static final String ARTIFACT_NAME = "ARTIFACT_NAME"; - - static final String VF_LICENSE = "VF_LICENSE"; - - public enum SDC_ARTIFACTS_FIELDS { - SERVICE_UUID, - DISTRIBUTION_ID, - SERVICE_NAME, - SERVICE_DESCRIPTION, - RESOURCE_UUID, - RESOURCE_INSTANCE_NAME, - RESOURCE_NAME, - RESOURCE_VERSION, - RESOURCE_TYPE, - ARTIFACT_UUID, - ARTIFACT_VERSION, - ARTIFACT_DESCRIPTION, - INTERNAL_VERSION, - CREATION_DATE, - ARTIFACT_CONTENT - } - - public enum SDC_REFERENCE_FIELDS{ - SDC_REFERENCE_ID, - VNF_TYPE, - VNFC_TYPE, - FILE_CATEGORY, - ACTION - } - - static final String COMMA = " , "; - static final String QUERY_PLACEHOLDER = " = ? "; - static final String SELECT_FROM = "SELECT * FROM " ; - static final String WHERE = " WHERE "; - static final String INSERT = "INSERT INTO "; -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java deleted file mode 100644 index 295ee47c8..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.helper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.exceptions.APPCException; - -import java.util.ArrayList; -import java.util.List; - -/** - * Provides method for genrating Dependency JSON from Tosca model - */ -public class DependencyModelGenerator { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelGenerator.class); - - /** - * - * @param tosca - tosca string from SDC - * @param vnfType - Vnf Type from tosca - * @return - Dependency JSON in String format - * @throws APPCException is thrown if error occurs - */ - public String getDependencyModel(String tosca, String vnfType) throws APPCException { - logger.debug(String.format("Generating dependency model for vnfType : %s , TOSCA: %s ", vnfType ,tosca)); - String dependencyJson; - DependencyModelParser dependencyModelParser = new DependencyModelParser(); - VnfcDependencyModel vnfcDependencyModel = dependencyModelParser.generateDependencyModel(tosca, vnfType); - - if (vnfcDependencyModel != null && !vnfcDependencyModel.getDependencies().isEmpty()) { - logger.debug(String.format("Dependency Model generated : %s ", vnfcDependencyModel.toString())); - List vnfcs = new ArrayList<>(); - - for (Node node : vnfcDependencyModel.getDependencies()) { - org.onap.appc.sdc.artifacts.object.Vnfc vnfc = new org.onap.appc.sdc.artifacts.object.Vnfc(); - vnfc.setVnfcType(node.getChild().getVnfcType()); - vnfc.setMandatory(node.getChild().isMandatory()); - vnfc.setResilienceType(node.getChild().getResilienceType()); - if (node.getParents() != null && !node.getParents().isEmpty()) { - List parents = new ArrayList<>(); - for (Vnfc parentNode : node.getParents()) { - parents.add(parentNode.getVnfcType()); - } - vnfc.setParents(parents); - } - vnfcs.add(vnfc); - } - ObjectMapper objectMapper = new ObjectMapper(); - - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure - (MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true).writer().withRootName("vnfcs"); - try { - dependencyJson = writer.writeValueAsString(vnfcs); - } catch (JsonProcessingException e) { - logger.error("Error converting dependency model to JSON"); - throw new APPCException("Error converting dependency model to JSON",e); - } - } else { - logger.error("Error generating dependency model from tosca. Empty dependency model"); - throw new APPCException("Error generating dependency model from tosca. Empty dependency model"); - } - return dependencyJson; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java deleted file mode 100644 index 7438d3047..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.impl; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventHeader; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.adapter.message.event.EventStatus; -import org.onap.appc.sdc.listener.Util; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.sdc.artifacts.ArtifactProcessor; -import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * Provides abstrace implementation for SDC artifact processor - */ -public abstract class AbstractArtifactProcessor implements ArtifactProcessor { - - public static final String PAYLOAD_CHARSET = "UTF-8"; - private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss"; - - protected IDistributionClient client; - protected EventSender eventSender; - - protected INotificationData notification; - protected IResourceInstance resource; - protected IArtifactInfo artifact; - protected URI storeUri; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractArtifactProcessor.class); - - protected ArtifactStorageService artifactStorageService; - - private AbstractArtifactProcessor(){ - artifactStorageService = new ArtifactStorageService(); - } - - AbstractArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, - IArtifactInfo artifact, URI storeUri){ - - this(); - this.client = client; - this.eventSender = eventSender; - this.notification = notification; - this.resource = resource; - this.artifact = artifact; - this.storeUri = storeUri; - } - - @Override - public void run(){ - - try{ - logger.info(String.format("Attempting to download artifact %s", artifact)); - // Download artifact - IDistributionClientDownloadResult download = client.download(artifact); - - logger.info(String.format("Download of artifact %s completed with status %s", artifact.getArtifactUUID(), download)); - - // Notify of download status - if (download.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { - client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, - DistributionStatusEnum.DOWNLOAD_ERROR), download.getDistributionMessageResult()); - sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), "Download is failed."); - return; - } - - client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DOWNLOAD_OK)); - - processArtifact(download); - - client.sendDeploymentStatus( - Util.buildDistributionStatusMessage(client, notification, this.artifact, DistributionStatusEnum.DEPLOY_OK)); - } - catch (Exception e){ - logger.error("Error processing artifact " + this.artifact.toString() ,e); - - client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact, - DistributionStatusEnum.DEPLOY_ERROR), e.getMessage()); - sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), e.getMessage()); - } - } - - - @Override - public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { - String data = null; - if(logger.isDebugEnabled()){ - logger.debug("Entry processArtifact in AbstractArtifactProcessor"); - } - try { - if (download.getArtifactPayload() != null) { - data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET); - } - } catch (UnsupportedEncodingException e) { - logger.error("Error reading artifact with " + PAYLOAD_CHARSET + " encoding" + new String(download.getArtifactPayload()) ,e); - throw new APPCException(e); - } - - SDCArtifact sdcArtifact = getArtifactObject(data); - logger.debug("Constructed SDCArtifact = " + sdcArtifact); - processArtifact(sdcArtifact); - - if(logger.isDebugEnabled()){ - logger.debug("Exit processArtifact in AbstractArtifactProcessor"); - } - } - - protected abstract void processArtifact(SDCArtifact artifact) throws APPCException; - - protected SDCArtifact getArtifactObject(String data){ - - SDCArtifact sdcArtifact = new SDCArtifact(); - - sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); - sdcArtifact.setArtifactName(this.artifact.getArtifactName()); - sdcArtifact.setArtifactType(this.artifact.getArtifactType()); - sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); - sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); - sdcArtifact.setArtifactContent(data); - sdcArtifact.setCreationDate(getCurrentDateTime()); - - sdcArtifact.setDistributionId(this.notification.getDistributionID()); - sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); - sdcArtifact.setServiceName(this.notification.getServiceName()); - sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); - - sdcArtifact.setResourceName(this.resource.getResourceName()); - sdcArtifact.setResourceType(this.resource.getResourceType()); - sdcArtifact.setResourceVersion(this.resource.getResourceVersion()); - sdcArtifact.setResourceUUID(this.resource.getResourceUUID()); - sdcArtifact.setResourceInstanceName(this.resource.getResourceInstanceName()); - - return sdcArtifact; - } - - protected String getCurrentDateTime() { - DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); - Date date = new Date(); - return dateFormat.format(date); - } - - private void sendDCAEEvent(String distributionID, String serviceName, String serviceVersion, String errorMessage) { - if (null == eventSender){ - return; - } - String errorDescription = String.format("SDC distribution of service '%s', version '%s' is failed with reason: '%s'", - serviceName, serviceVersion, errorMessage); - - EventMessage eventMessage = new EventMessage( - new EventHeader((new Date()).toString(), serviceVersion, distributionID), - new EventStatus(401, errorDescription)); - - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java deleted file mode 100644 index 293974b79..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.sdc.artifacts.ArtifactProcessor; -import org.onap.appc.sdc.artifacts.object.ArtifactType; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; - -import java.net.URI; - -/** - * Factory class for creating instance of Artifact Processor - */ -public class ArtifactProcessorFactory { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactProcessorFactory.class); - - public ArtifactProcessorFactory (){ - - } - - /** - * Provides and instance of Artifact Processor - * @param client an instance of IDistributionClient - * @param eventSender an instance of EventSender - * @param notification an instance of INotificationData - * @param resource an instance of IResourceInstance - * @param artifact an instance of IArtifactInfo - * @param storeUri - * @return - */ - public ArtifactProcessor getArtifactProcessor(IDistributionClient client, EventSender eventSender, - INotificationData notification, IResourceInstance resource, - IArtifactInfo artifact, URI storeUri) { - - logger.debug("Creating artifact processor for artifact type = " + artifact.getArtifactType()); - ArtifactType artifactType = ArtifactType.getArtifactType(artifact.getArtifactType()); - if(artifactType == null){ - return null; - } - ArtifactProcessor artifactProcessor = null; - switch (artifactType){ - case APPC_CONFIG : - artifactProcessor = new ConfigArtifactProcessor(client, eventSender, notification, resource, - artifact, storeUri); - break; - case VF_LICENSE: - artifactProcessor = new LicenseArtifactProcessor(client,eventSender,notification,resource, - artifact,storeUri); - break; - default: - break; - } - return artifactProcessor; - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java deleted file mode 100644 index 41230ea30..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.impl; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.sdc.listener.ProviderOperations; -import org.onap.appc.sdc.listener.ProviderResponse; -import org.onap.appc.sdc.listener.Util; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; - -import java.net.MalformedURLException; -import java.net.URI; - -/** - * Artifact processor for config artifact type - */ -public class ConfigArtifactProcessor extends AbstractArtifactProcessor { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(ConfigArtifactProcessor.class); - - /** - * returns an instance of ConfigArtifactProcessor - * @param client an instance of IDistributionClient - * @param eventSender an instance of EventSender - * @param notification an instance of INotificationData - * @param resource an instance of IResourceInstance - * @param artifact an instance of IArtifactInfo - * @param storeUri an instance of URI - */ - public ConfigArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { - super(client,eventSender,notification,resource,artifact,storeUri); - } - - @Override - public void processArtifact(SDCArtifact artifact) throws APPCException { - String postData = Util.toSdcStoreDocumentInput(notification, resource, super.artifact, artifact.getArtifactContent()); - try { - ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null); - if (result.getStatus() == 200) { - Util.parseResponse(result.getBody()); - } - } catch (MalformedURLException | APPCException e) { - logger.error("Error processing artifact : " + this.artifact.toString(),e); - throw new APPCException(e.getMessage(),e); - } - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java deleted file mode 100644 index fe5099785..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.impl; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.licmgr.Constants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang.StringUtils; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; - -import java.net.URI; - -/** - * Artifact processor for VNF license artifact type - */ -public class LicenseArtifactProcessor extends AbstractArtifactProcessor { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(LicenseArtifactProcessor.class); - - /** - * returns an instance of ConfigArtifactProcessor - * @param client an instance of IDistributionClient - * @param eventSender an instance of EventSender - * @param notification an instance of INotificationData - * @param resource an instance of IResourceInstance - * @param artifact an instance of IArtifactInfo - * @param storeUri an instance of URI - */ - public LicenseArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { - super(client,eventSender,notification,resource,artifact,storeUri); - } - - @Override - public void processArtifact(SDCArtifact artifact) throws APPCException { - - String vnfType = artifact.getResourceName(); - String version = artifact.getResourceVersion(); - String packageArtifactID = artifact.getArtifactUUID(); - - if (StringUtils.isEmpty(vnfType) || - StringUtils.isEmpty(version) || - StringUtils.isEmpty(packageArtifactID)) { - String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); - logger.error(errStr); - throw new APPCException(errStr); - } - - try { - SDCArtifact existingArtifact = artifactStorageService.retrieveSDCArtifact(vnfType, version,artifact.getArtifactType()); - - if (existingArtifact ==null) { // new resource - logger.debug("Artifact not found from database for vnfType = " + vnfType + " , version = " + version + " , artifactType = " + artifact.getArtifactType()); - artifactStorageService.storeSDCArtifact(artifact); - } else { // duplicate - logger.debug("Artifact retrieved from database = " + existingArtifact); - logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version)); - } - - } catch (Exception e) { - logger.error("Error processing artifact : " + artifact.toString(),e); - throw new APPCException(e.getMessage(),e); - } - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java deleted file mode 100644 index e38188432..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java +++ /dev/null @@ -1,241 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.impl; - -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.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import org.apache.commons.lang.StringUtils; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.licmgr.Constants; -import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator; -import org.onap.appc.sdc.artifacts.object.Resource; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.onap.appc.sdc.artifacts.object.SDCReference; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; - -import javax.json.Json; -import java.io.*; -import java.net.URI; -import java.util.*; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -public class ToscaCsarArtifactProcessor extends AbstractArtifactProcessor{ - - private final EELFLogger logger = EELFManager.getInstance().getLogger(ToscaCsarArtifactProcessor.class); - - private DependencyModelGenerator dependencyModelGenerator; - - public ToscaCsarArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, - IArtifactInfo artifact, URI storeUri){ - super(client,eventSender,notification,resource,artifact,storeUri); - dependencyModelGenerator = new DependencyModelGenerator(); - } - - @Override - public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { - logger.debug("processing artifact " + super.artifact.getArtifactType()); - byte[] byteArray = download.getArtifactPayload(); - String serviceFileName = ""; - String serviceTemplateContent = ""; - List resources = null; - Map csarFiles = new HashMap<>(); - try (ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(byteArray))) { - ZipEntry entry = inputStream.getNextEntry(); - logger.debug("First Entry = " +entry); - while(entry!= null){ - String filename = entry.getName(); - logger.debug("Next Entry = "+ filename); - - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - String str = null; - StringBuilder sb = new StringBuilder(); - while((str = bufferedReader.readLine()) != null){ - sb.append(new String(str)).append(System.getProperty("line.separator")); - } - csarFiles.put(filename,sb.toString()); - entry = inputStream.getNextEntry(); - } - - } catch (IOException e) { - logger.error("Error Reading TOSCA.meta from CSAR",e); - throw new APPCException(e); - } - serviceFileName = readServiceFileName(csarFiles.get("TOSCA-Metadata/TOSCA.meta")); - logger.debug("Service File Name = " + serviceFileName); - serviceTemplateContent = csarFiles.get(serviceFileName); - - try { - resources = readResources (serviceTemplateContent); - } catch (Exception e) { - logger.error("Error reading resources from " + ", serviceFileName = " + serviceFileName - + ", TOSCA Metadata = " + csarFiles.get("TOSCA-Metadata/TOSCA.meta"),e); - throw new APPCException(e); - } - - for(Resource resource:resources){ - String resourceTemplate = csarFiles.get("Definitions/resource-" + resource.getFileNameTag() + "-template.yml"); - SDCArtifact artifact = this.getArtifactObject(resource,resourceTemplate); - processArtifact(artifact); - } - } - - private String readServiceFileName(String toscaMetadata) { - toscaMetadata = toscaMetadata.substring(toscaMetadata.indexOf("Entry-Definitions"), toscaMetadata.indexOf(System.getProperty("line.separator"),toscaMetadata.indexOf("Entry-Definitions"))); - toscaMetadata =toscaMetadata.split(":")[1].trim(); - return toscaMetadata; - } - - protected SDCArtifact getArtifactObject(Resource resource, String data){ - - SDCArtifact sdcArtifact = new SDCArtifact(); - - sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); - sdcArtifact.setArtifactName(this.artifact.getArtifactName()); - sdcArtifact.setArtifactType(this.artifact.getArtifactType()); - sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); - sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); - sdcArtifact.setArtifactContent(data); - sdcArtifact.setCreationDate(super.getCurrentDateTime()); - - sdcArtifact.setDistributionId(this.notification.getDistributionID()); - sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); - sdcArtifact.setServiceName(this.notification.getServiceName()); - sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); - - sdcArtifact.setResourceName(resource.getName()); - sdcArtifact.setResourceType(resource.getType()); - sdcArtifact.setResourceVersion(resource.getVersion()); - sdcArtifact.setResourceUUID(resource.getUuid()); - sdcArtifact.setResourceInstanceName(resource.getInstanceName()); - - return sdcArtifact; - } - - private List readResources(String serviceTemplateContent) throws IOException { - List resources = new LinkedList<>(); - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - JsonNode root = mapper.readTree(serviceTemplateContent); - JsonNode topologyTemplate = root.get("topology_template"); - JsonNode nodeTemplates = topologyTemplate.get("node_templates"); - Iterator> itr = nodeTemplates.fields(); - while(itr.hasNext()){ - Map.Entry entry = itr.next(); - String instanceName = entry.getKey(); - JsonNode nodeTemplate = entry.getValue(); - - String fileNameTag = nodeTemplate.get("type").asText(); - logger.debug("Resource type in Service Template = " + fileNameTag); - fileNameTag = fileNameTag.substring(fileNameTag.lastIndexOf(".")+1,fileNameTag.length()); - String version = nodeTemplate.get("metadata").get("version").asText(); - String uuid = nodeTemplate.get("metadata").get("UUID").asText(); - String name = nodeTemplate.get("metadata").get("name").asText(); - String type = nodeTemplate.get("metadata").get("type").asText(); - - if(!"VF".equalsIgnoreCase(type)){ - continue; - } - - Resource resource = new Resource(); - resource.setFileNameTag(fileNameTag); - resource.setVersion(version); - resource.setUuid(uuid); - resource.setInstanceName(instanceName); - resource.setName(name); - resource.setType(type); - - resources.add(resource); - } - return resources; - } - - - @Override - protected void processArtifact(SDCArtifact artifact) throws APPCException { - String vnfType = artifact.getResourceName(); - String version = artifact.getResourceVersion(); - String packageArtifactID = artifact.getArtifactUUID(); - - if (StringUtils.isEmpty(vnfType) || - StringUtils.isEmpty(version) || - StringUtils.isEmpty(packageArtifactID)) { - String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); - logger.error(errStr); - throw new APPCException(errStr); - } - try { - SDCReference reference = new SDCReference(); - reference.setVnfType(vnfType); - reference.setFileCategory("tosca_model"); - reference.setArtifactName(artifact.getArtifactName()); - logger.debug("Storing TOSCA to SDC Artifact"); - artifactStorageService.storeSDCArtifactWithReference(artifact,reference); - - SDCArtifact dependencyArtifact = getDependencyArtifact(artifact); - SDCReference dependencyReference = new SDCReference(); - dependencyReference.setVnfType(vnfType); - dependencyReference.setFileCategory("tosca_dependency_model"); - dependencyReference.setArtifactName(dependencyArtifact.getArtifactName()); - logger.debug("Storing Dependency to SDC Artifact"); - artifactStorageService.storeSDCArtifactWithReference(dependencyArtifact,dependencyReference); - } catch (Exception e) { - logger.error("Error processing artifact : " + artifact.toString() ); - throw new APPCException(e.getMessage(),e); - } - } - - private SDCArtifact getDependencyArtifact(SDCArtifact toscaArtifact) throws APPCException { - SDCArtifact artifact = new SDCArtifact(); - artifact.setArtifactName("dependency_"+toscaArtifact.getArtifactName()); - String dependencyModel = dependencyModelGenerator.getDependencyModel(toscaArtifact.getArtifactContent(),toscaArtifact.getResourceName()); - artifact.setArtifactContent(dependencyModel); - artifact.setArtifactType("DEPENDENCY_MODEL"); - - artifact.setArtifactUUID(toscaArtifact.getArtifactUUID()); - artifact.setArtifactVersion(toscaArtifact.getArtifactVersion()); - artifact.setArtifactDescription(toscaArtifact.getArtifactDescription()); - artifact.setCreationDate(super.getCurrentDateTime()); - artifact.setDistributionId(toscaArtifact.getDistributionId()); - artifact.setServiceUUID(toscaArtifact.getServiceUUID()); - artifact.setServiceName(toscaArtifact.getServiceName()); - artifact.setServiceDescription(toscaArtifact.getServiceDescription()); - artifact.setResourceName(toscaArtifact.getResourceName()); - artifact.setResourceType(toscaArtifact.getResourceType()); - artifact.setResourceVersion(toscaArtifact.getResourceVersion()); - artifact.setResourceUUID(toscaArtifact.getResourceUUID()); - artifact.setResourceInstanceName(toscaArtifact.getResourceInstanceName()); - return artifact; - } - - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java deleted file mode 100644 index 790ad2381..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.object; - -/** - * Enummration listing SDC artifact types - */ -public enum ArtifactType { - APPC_CONFIG,VF_LICENSE,TOSCA_CSAR; - - /** - * returns ArtifactType for the input string type - * @param artifactTypeStr - * @return - */ - public static ArtifactType getArtifactType(String artifactTypeStr){ - for(ArtifactType artifactType: ArtifactType.values()){ - if(artifactType.name().equals(artifactTypeStr)){ - return artifactType; - } - } - return null; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java deleted file mode 100644 index 6ae441c18..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.object; - -public class Resource { - private String name; - private String type; - private String version; - private String uuid; - private String instanceName; - private String fileNameTag; - - public Resource(){ - - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getInstanceName() { - return instanceName; - } - - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } - - - public String getFileNameTag() { - return fileNameTag; - } - - public void setFileNameTag(String fileNameTag) { - this.fileNameTag = fileNameTag; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java deleted file mode 100644 index d5376b570..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java +++ /dev/null @@ -1,215 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.object; - -/** - * POJO containing metadata about SDC artifact - */ -public class SDCArtifact { - - private String artifactUUID; - - private String artifactName; - - private String artifactType; - - private String artifactVersion; - - private String artifactContent; - - private String artifactDescription; - - private String creationDate; - - private String distributionId; - - - - private String resourceUUID; - - private String resourceName; - - private String resourceType; - - private String resourceVersion; - - private String resourceInstanceName; - - - private String serviceUUID; - - private String serviceName; - - private String serviceDescription; - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getArtifactContent() { - return artifactContent; - } - - public void setArtifactContent(String artifactContent) { - this.artifactContent = artifactContent; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactType() { - return artifactType; - } - - public void setArtifactType(String artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getCreationDate() { - return creationDate; - } - - public void setCreationDate(String creationDate) { - this.creationDate = creationDate; - } - - public String getDistributionId() { - return distributionId; - } - - public void setDistributionId(String distributionId) { - this.distributionId = distributionId; - } - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getServiceDescription() { - return serviceDescription; - } - - public void setServiceDescription(String serviceDescription) { - this.serviceDescription = serviceDescription; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getServiceUUID() { - return serviceUUID; - } - - public void setServiceUUID(String serviceUUID) { - this.serviceUUID = serviceUUID; - } - - - @Override - public String toString() { - return "artifactUUID = " + artifactUUID + - " , artifactName = " + artifactName + - " , artifactType = " + artifactType + - " , artifactVersion = " + artifactVersion + - " , artifactContent = " + artifactContent + - " , artifactDescription = " + artifactDescription + - " , creationDate = " + creationDate + - " , distributionId = " +distributionId + - " , resourceUUID = " + resourceUUID + - " , resourceName = " + resourceName + - " , resourceType = " + resourceType + - " , resourceVersion = " + resourceVersion + - " , resourceInstanceName = " + resourceInstanceName + - " , serviceUUID = " + serviceUUID + - " , serviceName = " + serviceName + - " , serviceDescription = " + serviceDescription; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java deleted file mode 100644 index 2ee6d7c85..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.object; - -public class SDCReference { - - private String vnfType; - private String vnfcType; - private String fileCategory; - private String action; - private String artifactType; - private String artifactName; - - public String getVnfType() { - return vnfType; - } - - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - - public String getVnfcType() { - return vnfcType; - } - - public void setVnfcType(String vnfcType) { - this.vnfcType = vnfcType; - } - - public String getFileCategory() { - return fileCategory; - } - - public void setFileCategory(String fileCategory) { - this.fileCategory = fileCategory; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getArtifactType() { - return artifactType; - } - - public void setArtifactType(String artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - @Override - public String toString() { - return "vnfType = " + vnfType+ - ", vnfType = " + vnfType+ - ", fileCategory = " + fileCategory+ - ", action = " + action+ - ", artifactType = " + artifactType+ - ", artifactName = " + artifactName+ - ", vnfType = " + vnfType; - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java deleted file mode 100644 index 3e0d3a749..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.artifacts.object; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.util.List; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonPropertyOrder({"vnfc-type","mandatory","resilience","parents"}) -public class Vnfc { - - @JsonProperty("vnfc-type") - private String vnfcType; - @JsonProperty("mandatory") - private boolean mandatory; - @JsonProperty("resilience") - private String resilienceType; - @JsonProperty("parents") - private List parents; - - public String getVnfcType() { - return vnfcType; - } - - public void setVnfcType(String vnfcType) { - this.vnfcType = vnfcType; - } - public boolean isMandatory() { - return mandatory; - } - - public void setMandatory(boolean mandatory) { - this.mandatory = mandatory; - } - - public String getResilienceType() { - return resilienceType; - } - - public void setResilienceType(String resilienceType) { - this.resilienceType = resilienceType; - } - - public List getParents() { - return parents; - } - - public void setParents(List parents) { - this.parents = parents; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java deleted file mode 100644 index fa8340ac7..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java +++ /dev/null @@ -1,211 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.Socket; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Map; -import java.util.Map.Entry; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ProviderOperations { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); - - private static String basic_auth; - - public static ProviderResponse post(URL url, String json, Map adtl_headers) throws APPCException { - if (json == null) { - throw new APPCException("Provided message was null"); - } - - HttpPost post = null; - try { - post = new HttpPost(url.toExternalForm()); - post.setHeader("Content-Type", "application/json"); - post.setHeader("Accept", "application/json"); - - // Set Auth - if (basic_auth != null) { - post.setHeader("Authorization", "Basic " + basic_auth); - } - - if (adtl_headers != null) { - for (Entry header : adtl_headers.entrySet()) { - post.setHeader(header.getKey(), header.getValue()); - } - } - - StringEntity entity = new StringEntity(json); - entity.setContentType("application/json"); - post.setEntity(new StringEntity(json)); - } catch (UnsupportedEncodingException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(url); - - int httpCode = 0; - String respBody = null; - try { - HttpResponse response = client.execute(post); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - return new ProviderResponse(httpCode, respBody); - } catch (IOException e) { - throw new APPCException(e); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user - * The user with optional domain name (for AAF) - * @param password - * The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basic_auth = null; - } - return basic_auth; - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient(URL url) throws APPCException { - HttpClient client; - if (url.getProtocol().equals("https")) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme("https", sf, 443)); - registry.register(new Scheme("https", sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - client = new DefaultHttpClient(); - } - } else if (url.getProtocol().equals("http")) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - public static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - - public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[] { - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java deleted file mode 100644 index bf91332c5..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -public class ProviderResponse { - - private int status; - private String body; - - public ProviderResponse(int status, String body) { - this.status = status; - this.body = body; - } - - public String getBody() { - return body; - } - - public int getStatus() { - return status; - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java deleted file mode 100644 index 8be458200..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.sdc.artifacts.ArtifactProcessor; -import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.openecomp.sdc.utils.DistributionStatusEnum; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.net.URI; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -public class SdcCallback implements INotificationCallback { - - private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCallback.class); - private ArtifactProcessorFactory artifactProcessorFactory=new ArtifactProcessorFactory(); - - private URI storeUri; - private IDistributionClient client; - - private EventSender eventSender = null; - - private ThreadPoolExecutor executor; - private int threadCount = 10; - - private AtomicBoolean isRunning = new AtomicBoolean(false); - - - public SdcCallback(URI storeUri, IDistributionClient client) { - this.storeUri = storeUri; - this.client = client; - - // Create the thread pool - executor = new ThreadPoolExecutor(threadCount, threadCount, 1, TimeUnit.SECONDS, - new ArrayBlockingQueue(threadCount * 2)); - - // Custom Named thread factory - BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build(); - executor.setThreadFactory(threadFactory); - - isRunning.set(true); - } - - @Override - public void activateCallback(INotificationData data) { - if (null == eventSender) { - try { - BundleContext bctx = FrameworkUtil.getBundle(EventSender.class).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(EventSender.class); - eventSender = (EventSender) bctx.getService(sref); - } catch (Exception e) { - logger.error("SdcCallback failed on initializing EventSender", e); - } - } - - if (isRunning.get()) { - - for(IArtifactInfo artifact:data.getServiceArtifacts()){ - ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(client, eventSender, data, null, artifact, storeUri); - if(artifactProcessor!=null){ - executor.submit(artifactProcessor); - } - } - - for (IResourceInstance resource : data.getResources()) { - for (IArtifactInfo artifact : resource.getArtifacts()) { - logger.info(Util.toSdcStoreDocumentInput(data, resource, artifact, "abc")); - if (executor.getQueue().size() >= threadCount) { - // log warning about job backlog - } - ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(client, eventSender, data, resource, artifact, storeUri); - if(artifactProcessor != null){ - executor.submit(artifactProcessor); - } - else{ - /* Before refactoring of the DownloadAndStoreOp class, the approach was to download all the - artifacts, send the download status, and then perform the processing of artifact if it is - required. Now that we are downloading the artifacts only when its processing is required, - we are sending the download status as positive just to have the same behaviour as before - refactoring. - */ - client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK)); - logger.error("Artifact type not supported : " + artifact.getArtifactType()); - } - } - } - } else { - // TODO - return a failed result so sdc knows we are shut down - } - } - - public void stop() { - stop(10); - } - - public void stop(int waitSec) { - isRunning.set(false); - logger.info(String.format("Stopping the SDC listener and waiting up to %ds for %d pending jobs", waitSec, - executor.getQueue().size())); - boolean cleanShutdown = false; - executor.shutdown(); - try { - cleanShutdown = executor.awaitTermination(waitSec, TimeUnit.SECONDS); - executor.shutdownNow(); // In case of timeout - } catch (InterruptedException e) { - logger.error("Error in SdcCallback for stop(int waitSec) method due to InterruptedException: reason= " + e.getMessage(), e); - } - logger.info(String.format("Attempting to shutdown cleanly: %s", cleanShutdown ? "SUCCESS" : "FAILURE")); - logger.info("Shutdown complete."); - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java deleted file mode 100644 index 86ba9e1f5..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.sdc.api.consumer.IConfiguration; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -public class SdcConfig implements IConfiguration { - - private String host; - private String consumer; - private String consumerId; - private String env; - private String keystorePath; - private String keystorePass; - /** Polling internal is time between listening sessions */ - private int pollingInterval; - /** Polling timeout is the time to listen for (dmaap timeout url param)/1000 */ - private int pollingTimeout; - private List types = new ArrayList<>(); - private String user; - private String pass; - - private URI storeOp; - - private Properties props; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcConfig.class); - - SdcConfig(Properties props) throws Exception { - this.props = props; - init(); - } - - private void init() throws Exception { - if (props == null) { - logger.error("SdcConfig init is skipped due to properties is null"); - return; - } - - // Keystore for ca cert - keystorePath = props.getProperty("appc.sdc.keystore.path"); - keystorePass = props.getProperty("appc.sdc.keystore.pass"); - - // ASDC host - host = props.getProperty("appc.sdc.host"); - env = props.getProperty("appc.sdc.env"); - user = props.getProperty("appc.sdc.user"); - pass = props.getProperty("appc.sdc.pass"); - - // DMaaP properties - consumer = props.getProperty("appc.sdc.consumer"); - consumerId = props.getProperty("appc.sdc.consumer.id"); - - pollingInterval = Integer.valueOf(props.getProperty("interval", "60")); - - // Client uses cambriaClient-0.2.4 which throws non relevant (wrong) - // exceptions with times > 30s - pollingTimeout = Integer.valueOf(props.getProperty("timeout", "25")); - - // Anything less than 60 and we risk 429 Too Many Requests - if (pollingInterval < 60) { - pollingInterval = 60; - } - - if (pollingInterval > pollingTimeout) { - logger.warn(String.format( - "Message acknowledgement may be delayed by %ds in the ADSC listener. [Listening Time: %s, Poll Period: %s]", - pollingInterval - pollingTimeout, pollingTimeout, pollingInterval)); - } - - logParams(); - - // Download type - /* - This types seems redundant, as it looks from the code that they are not being used anywhere - */ - types.add("APPC_CONFIG"); - types.add("VF_LICENSE"); - // types.add("TOSCA_CSAR"); commenting it out as we are not listening to TOSCA_CSAR - - storeOp = new URI(props.getProperty("appc.sdc.provider.url")); - } - - @Override - public boolean activateServerTLSAuth() { - return false; - } - - public boolean isFilterInEmptyResources() { - return false; - } - - @Override - public String getAsdcAddress() { - return host; - } - - @Override - public String getConsumerGroup() { - return consumer; - } - - @Override - public String getConsumerID() { - return consumerId; - } - - @Override - public String getEnvironmentName() { - return env; - } - - @Override - public String getKeyStorePassword() { - return keystorePass; - } - - @Override - public String getKeyStorePath() { - return keystorePath; - } - - @Override - public String getPassword() { - return pass; - } - - @Override - public int getPollingInterval() { - return pollingInterval; - } - - @Override - public int getPollingTimeout() { - return pollingTimeout; - } - - @Override - public List getRelevantArtifactTypes() { - return types; - } - - @Override - public String getUser() { - return user; - } - - @Override - public Boolean isUseHttpsWithDmaap(){ - return true; - } - - URI getStoreOpURI() { - return storeOp; - } - - /** - * Logs the relevant parameters - */ - private void logParams() { - Map params = new HashMap<>(); - params.put("SDC Host", getAsdcAddress()); - params.put("SDC Environment", getEnvironmentName()); - params.put("Consumer Name", getConsumerGroup()); - params.put("Consumer ID", getConsumerID()); - params.put("Poll Active Wait", String.valueOf(getPollingInterval())); - params.put("Poll Timeout", String.valueOf(getPollingTimeout())); - - logger.info(String.format("SDC Params: %s", params)); - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java deleted file mode 100644 index b204a54f7..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.results.IDistributionClientResult; -import org.openecomp.sdc.impl.DistributionClientFactory; -import org.openecomp.sdc.utils.DistributionActionResultEnum; - -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * SDC listener handles bundle start and stop through start and stop method.

- * Register connection with SDC server based on properties file configuration when start, - * and disconnect with SDC server when stop. - */ -public class SdcListener { - private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcListener.class); - - /** - * The bundle context - */ - private IDistributionClient client; - private SdcCallback callback; - private SdcConfig config; - private CountDownLatch latch; - - private Thread startThread = null; - - @SuppressWarnings("unused") - public void start() throws Exception { - // Add timestamp to the log to differentiate the jmeter run testing calls. - final long timeStamp = System.currentTimeMillis(); - logger.info(String.format("[%d] Starting SDC Listener", timeStamp)); - - Configuration configuration = ConfigurationFactory.getConfiguration(); - Properties props = configuration.getProperties(); - config = new SdcConfig(props); - logger.debug(String.format("[%d] created SDC config", timeStamp)); - - client = DistributionClientFactory.createDistributionClient(); - logger.debug(String.format("[%d] created SDC client", timeStamp)); - - callback = new SdcCallback(config.getStoreOpURI(), client); - logger.debug(String.format("[%d] created SDC callback", timeStamp)); - - latch = new CountDownLatch(1); - - startThread = new Thread(new StartRunnable(timeStamp)); - startThread.setName(String.format("[%d] sdcListener start", timeStamp)); - logger.debug(String.format("[%d] created SDC initialization thread", timeStamp)); - startThread.start(); - } - - @SuppressWarnings("unused") - public void stop() throws InterruptedException { - // Add timestamp to the log to differentiate the jmeter run testing calls. - final long timeStamp = System.currentTimeMillis(); - logger.info(String.format("[%d] Stopping SDC Listener", timeStamp)); - - stopStartThread(timeStamp); - - if (latch != null) { - logger.debug(String.format("[%d] waiting SDC latch count to 0 for 10 seconds", timeStamp)); - latch.await(10, TimeUnit.SECONDS); - latch = null; - } - - if (callback != null) { - logger.debug(String.format("[%d] stopping SDC callback", timeStamp)); - callback.stop(); - callback = null; - } - if (client != null) { - logger.debug(String.format("[%d] stopping SDC client", timeStamp)); - client.stop(); - client = null; - - } - logger.info(String.format("[%d] SDC Listener stopped successfully", timeStamp)); - } - - void stopStartThread(long timeStamp) throws InterruptedException { - if (startThread == null) { - return; - } - - if (startThread.getState() == Thread.State.TERMINATED) { - logger.debug(String.format("[%d] SDC thread(%s) is already terminated.", - timeStamp, startThread.getName())); - } else { - logger.debug(String.format("[%d] SDC thread(%s) is to be interrupted with state(%s)", - timeStamp, startThread.getName(), startThread.getState().toString())); - - startThread.interrupt(); - - logger.debug(String.format("[%d] SDC thread(%s) has been interrupted(%s) with state(%s)", - timeStamp, startThread.getName(), startThread.isInterrupted(), - startThread.getState().toString())); - } - startThread = null; - } - - /** - * Runnable implementation for actual initialization during SDC listener start - */ - class StartRunnable implements Runnable { - private final long timeStamp; - - StartRunnable(long theTimeStamp) { - timeStamp = theTimeStamp; - } - - /** - * This run method calls SDC client for init and start which are synchronized calls along with stop. - * To interrupt this thread at stop time, we added thread interrupted checking in each step - * for earlier interruption. - */ - @Override - public void run() { - if (!initialRegistration()) { - logger.warn(String.format("[%d] SDC thread initial registration failed.", timeStamp)); - } - - if (isThreadInterrupted("after initial registration")) { - return; - } - - IDistributionClientResult result = client.init(config, callback); - - if (isThreadInterrupted("after client init")) { - return; - } - - if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { - client.start(); - } else { - logger.error(String.format("[%d] Could not register SDC client. %s - %s", - timeStamp, result.getDistributionActionResult(), result.getDistributionMessageResult())); - } - - latch.countDown(); - } - - private boolean initialRegistration() { - try { - final String jsonTemplate = - "{\"consumerName\": \"%s\",\"consumerSalt\": \"%s\",\"consumerPassword\":\"%s\"}"; - String saltedPassStr = org.openecomp.tlv.sdc.security.Passwords.hashPassword(config.getPassword()); - if (saltedPassStr == null || !saltedPassStr.contains(":")) { - return false; - } - - String[] saltedPass = saltedPassStr.split(":"); - String json = String.format(jsonTemplate, config.getUser(), saltedPass[0], saltedPass[1]); - - Map headers = new HashMap<>(); - // TODO - Replace the header below to sdc's requirements. What should the new value be - headers.put("USER_ID", "test"); - - // TODO - How to format the url. Always same endpoint or ports? - String host = config.getAsdcAddress(); - URL url = new URL(String.format("http%s://%s/sdc2/rest/v1/consumers", - host.contains("443") ? "s" : "", host)); - - logger.info(String.format("Attempting to register user %s on %s with salted pass of %s", - config.getUser(), url, saltedPass[1])); - - ProviderOperations providerOperations = new ProviderOperations(); - ProviderResponse result = providerOperations.post(url, json, headers); - return result.getStatus() == 200; - } catch (Exception e) { - logger.error( - "Error performing initial registration with SDC server. User may not be able to connect", - e); - return false; - } - } - - private boolean isThreadInterrupted(String details) { - if (Thread.currentThread().isInterrupted()) { - logger.info(String.format("[%d] SDC thread interrupted %s.", timeStamp, details)); - return true; - } - return false; - } - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java deleted file mode 100644 index bc4b4a896..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -import org.json.JSONException; -import org.json.JSONObject; -import org.onap.appc.exceptions.APPCException; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.utils.DistributionStatusEnum; - -public class Util { - - // TODO - Use the yang builder instead - public static String toSdcStoreDocumentInput(INotificationData notification, IResourceInstance resource, - IArtifactInfo artifact, String data) { - JSONObject json = new JSONObject(); - - JSONObject requestInfo = new JSONObject(); - requestInfo.put("request-id", notification.getServiceUUID()); - requestInfo.put("request-action", "StoreSdcDocumentRequest"); - requestInfo.put("source", "SDC"); - - JSONObject docParams = new JSONObject(); - docParams.put("service-uuid", notification.getServiceUUID()); - docParams.put("distribution-id", notification.getDistributionID()); - docParams.put("service-name", notification.getServiceName()); - docParams.put("service-description", notification.getServiceDescription()); - docParams.put("service-artifacts", "[]"); - docParams.put("resource-uuid", resource.getResourceUUID()); - docParams.put("resource-instance-name", resource.getResourceInstanceName()); - docParams.put("resource-name", resource.getResourceName()); - docParams.put("resource-version", resource.getResourceVersion()); - docParams.put("resource-type", resource.getResourceType()); - docParams.put("artifact-uuid", artifact.getArtifactUUID()); - docParams.put("artifact-name", artifact.getArtifactName()); - docParams.put("artifact-type", artifact.getArtifactType()); - docParams.put("artifact-version", artifact.getArtifactVersion()); - docParams.put("artifact-description", artifact.getArtifactDescription()); - docParams.put("artifact-contents", data); - - json.put("request-information", requestInfo); - json.put("document-parameters", docParams); - - return String.format("{\"input\": %s}", json.toString()); - } - - public static boolean parseResponse(String input) throws APPCException { - JSONObject result, output, response; - try { - result = new JSONObject(input); - output = result.getJSONObject("output"); - response = output.getJSONObject("config-document-response"); - String id = response.getString("request-id"); - String status = response.getString("status"); - if (status.equals(DistributionStatusEnum.DEPLOY_OK.toString())) { - return true; - } else { - String error = response.optString("error-reason"); - String msg = error.isEmpty() ? "No Reason Provided" : error; - throw new APPCException(msg); - } - } catch (JSONException jse) { - throw new APPCException("Did not get valid json from provider.", jse); - } - } - - public static IDistributionStatusMessage buildDistributionStatusMessage(final IDistributionClient client, - final INotificationData data, final IArtifactInfo relevantArtifact, final DistributionStatusEnum status) { - IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { - - @Override - public long getTimestamp() { - long currentTimeMillis = System.currentTimeMillis(); - return currentTimeMillis; - } - - @Override - public DistributionStatusEnum getStatus() { - return status; - } - - @Override - public String getDistributionID() { - return data.getDistributionID(); - } - - @Override - public String getConsumerID() { - return client.getConfiguration().getConsumerID(); - } - - @Override - public String getArtifactURL() { - return relevantArtifact.getArtifactURL(); - } - }; - return statusMessage; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java deleted file mode 100644 index 30b275a51..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.tlv.sdc.security; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Random; - -/** - * A copy from the org.openecomp.sdc:security-utils artifact that works with java 7. - */ -public class Passwords { - - private static final Random RANDOM = new SecureRandom(); - private static final int SALT = 0; - private static final int HASH = 1; - private static final String HASH_ALGORITHM = "SHA-256"; - - /** - * static utility class - */ - private Passwords() { - } - - /** - * the method calculates a hash with a generated salt for the given password - * - * @param password - * @return a "salt:hash" value - */ - public static String hashPassword(String password) { - byte[] salt = getNextSalt(); - byte byteData[] = hash(salt, password.getBytes()); - if (byteData != null) { - return toHex(salt) + ":" + toHex(byteData); - } - return null; - - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param expectedHash - * @return - */ - public static boolean isExpectedPassword(String password, String expectedHash) { - String[] params = expectedHash.split(":"); - return isExpectedPassword(password, params[SALT], params[HASH]); - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param salt - * @param hash - * the hash generated using the salt - * @return true if the password matched the hash - */ - public static boolean isExpectedPassword(String password, String salt, String hash) { - byte[] saltBytes = fromHex(salt); - byte[] hashBytes = fromHex(hash); - - byte byteData[] = hash(saltBytes, password.getBytes()); - if (byteData != null) { - return Arrays.equals(byteData, hashBytes); - } - return false; - } - - public static void main(String[] args) { - if (args.length > 1 || args.length > 0) { - System.out.println("[" + hashPassword(args[0]) + "]"); - } else { - System.out.println("no passward passed."); - } - - } - - /** - * Returns a random salt to be used to hash a password. - * - * @return a 16 bytes random salt - */ - private static byte[] getNextSalt() { - byte[] salt = new byte[16]; - RANDOM.nextBytes(salt); - return salt; - } - - /** - * hase's the salt and value using the chosen algorithm - * - * @param salt - * @param password - * @return an array of bytes resulting from the hash - */ - private static byte[] hash(byte[] salt, byte[] password) { - MessageDigest md; - byte[] byteData = null; - try { - md = MessageDigest.getInstance(HASH_ALGORITHM); - md.update(salt); - md.update(password); - byteData = md.digest(); - } catch (NoSuchAlgorithmException e) { - System.out.println("in vlide algorithem name"); - } - return byteData; - } - - /** - * Converts a string of hexadecimal characters into a byte array. - * - * @param hex - * the hex string - * @return the hex string decoded into a byte array - */ - private static byte[] fromHex(String hex) { - byte[] binary = new byte[hex.length() / 2]; - for (int i = 0; i < binary.length; i++) { - binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); - } - return binary; - } - - /** - * Converts a byte array into a hexadecimal string. - * - * @param array - * the byte array to convert - * @return a length*2 character string encoding the byte array - */ - private static String toHex(byte[] array) { - BigInteger bi = new BigInteger(1, array); - String hex = bi.toString(16); - int paddingLength = (array.length * 2) - hex.length(); - if (paddingLength > 0) - return String.format("%0" + paddingLength + "d", 0) + hex; - else - return hex; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/onap/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..f8c5e8e2e --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,40 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +# These SDC properties were provided by the SDC Op-So team +appc.sdc.keystore.path=etc/sdc-client.jks +appc.sdc.keystore.pass=Aa123456 + +appc.sdc.host=192.168.1.2:8443 +appc.sdc.env=TEST +appc.sdc.user=appc +appc.sdc.pass=appc + +appc.sdc.consumer=TEST +appc.sdc.consumer.id=TEST +appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index f8c5e8e2e..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,40 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -# These SDC properties were provided by the SDC Op-So team -appc.sdc.keystore.path=etc/sdc-client.jks -appc.sdc.keystore.pass=Aa123456 - -appc.sdc.host=192.168.1.2:8443 -appc.sdc.env=TEST -appc.sdc.user=appc -appc.sdc.pass=appc - -appc.sdc.consumer=TEST -appc.sdc.consumer.id=TEST -appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request - diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestArtifactProcessor.java new file mode 100644 index 000000000..8253238e8 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestArtifactProcessor.java @@ -0,0 +1,128 @@ +package org.onap.appc.sdc.artifacts.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.powermock.api.mockito.PowerMockito; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class TestArtifactProcessor { + + AbstractArtifactProcessor abstractArtifactProcessor; + + @Before + public void setup() throws Exception{ + IDistributionClient client = PowerMockito.mock(IDistributionClient.class); + EventSender eventSender = PowerMockito.mock(EventSender.class); + abstractArtifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) + ,getServiceArtifacts().get(0),null)); + } + + @Test + public void testGetArtifactObject(){ + SDCArtifact artifact=abstractArtifactProcessor.getArtifactObject("test"); + Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID()); + Assert.assertEquals("VF_LICENSE",artifact.getArtifactType()); + Assert.assertEquals("Vnf",artifact.getResourceName()); + Assert.assertEquals("1.0",artifact.getResourceVersion()); + Assert.assertEquals("test",artifact.getArtifactContent()); + } + + @Test + public void testFactoryForLicense() throws Exception{ + IDistributionClient client = PowerMockito.mock(IDistributionClient.class); + EventSender eventSender = PowerMockito.mock(EventSender.class); + ArtifactProcessorFactory factory=new ArtifactProcessorFactory(); + Assert.assertTrue(factory.getArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) + ,getServiceArtifacts().get(0),null) instanceof LicenseArtifactProcessor); + } + + @Test + public void testFactoryForConfig() throws Exception{ + IDistributionClient client = PowerMockito.mock(IDistributionClient.class); + EventSender eventSender = PowerMockito.mock(EventSender.class); + ArtifactProcessorFactory factory=new ArtifactProcessorFactory(); + Assert.assertTrue(factory.getArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) + ,getServiceArtifactsForConfig().get(0),null) instanceof ConfigArtifactProcessor); + } + + private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, + InstantiationException, InvocationTargetException { + + INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + + List serviceArtifacts = getServiceArtifacts(); + + invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); + return notificationData; + } + + private List getResources() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List resources = new ArrayList<>(); + IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + + List serviceArtifacts = getServiceArtifacts(); + invokeMethod(resource,"setArtifacts",serviceArtifacts); + invokeMethod(resource,"setResourceName","Vnf"); + invokeMethod(resource,"setResourceVersion","1.0"); + + resources.add(resource); + return resources; + } + + private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + Method[] methods = object.getClass().getDeclaredMethods(); + for(Method method:methods){ + if(methodName.equalsIgnoreCase(method.getName())){ + method.setAccessible(true); + method.invoke(object,arguments); + } + } + } + + private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) + .stream() + .filter(constructor1 -> constructor1.getParameterCount()==0) + .collect(Collectors.toList()) + .get(0); + constructor.setAccessible(true); + return constructor.newInstance(); + } + + private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","VF_LICENSE"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } + + private List getServiceArtifactsForConfig() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","APPC_CONFIG"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java new file mode 100644 index 000000000..f4cbc6a74 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java @@ -0,0 +1,132 @@ +package org.onap.appc.sdc.artifacts.impl; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.verify; + +@RunWith(PowerMockRunner.class) +public class TestLicenseArtifactProcessor { + + private LicenseArtifactProcessor artifactProcessor; + private ArtifactStorageService storageService; + + @Before + public void setup() throws Exception{ + IDistributionClient client = PowerMockito.mock(IDistributionClient.class); + EventSender eventSender = PowerMockito.mock(EventSender.class); + storageService = PowerMockito.mock(ArtifactStorageService.class); + artifactProcessor = Mockito.spy(new LicenseArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) + ,getServiceArtifacts().get(0),null)); + Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); + PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact((SDCArtifact)Matchers.anyObject()); + PowerMockito.doNothing().when(storageService).storeSDCArtifact(Matchers.anyObject()); + } + + @Test(expected = org.onap.appc.exceptions.APPCException.class) + public void testProcessArtifactWithMissingData() throws APPCException { + SDCArtifact artifact=new SDCArtifact(); + artifact.setResourceVersion("RESOURCE VERSION"); + artifact.setArtifactUUID("123-456-789"); + artifactProcessor.processArtifact(artifact); + } + @Test + public void testProcessArtifact() throws APPCException { + PowerMockito.when(storageService.retrieveSDCArtifact(anyString(),anyString(),anyString())).thenReturn(null); + SDCArtifact artifact=new SDCArtifact(); + artifact.setResourceVersion("RESOURCE VERSION"); + artifact.setArtifactUUID("123-456-789"); + artifact.setResourceName("Resource Name"); + artifactProcessor.processArtifact(artifact); + verify(storageService,Mockito.times(1)).storeSDCArtifact(anyObject()); + } + @Test + public void testProcessArtifactWithDuplicateArtifact() throws APPCException { + SDCArtifact artifact=new SDCArtifact(); + artifact.setResourceVersion("RESOURCE VERSION"); + artifact.setArtifactUUID("123-456-789"); + artifact.setResourceName("Resource Name"); + PowerMockito.when(storageService.retrieveSDCArtifact(anyString(),anyString(),anyString())).thenReturn(artifact); + artifactProcessor.processArtifact(artifact); + verify(storageService,Mockito.times(0)).storeSDCArtifact(anyObject()); + } + + private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, + InstantiationException, InvocationTargetException { + + org.openecomp.sdc.api.notification.INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + + List serviceArtifacts = getServiceArtifacts(); + + invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); + return notificationData; + } + + private List getResources() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List resources = new ArrayList<>(); + IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + + List serviceArtifacts = getServiceArtifacts(); + invokeMethod(resource,"setArtifacts",serviceArtifacts); + invokeMethod(resource,"setResourceName","Vnf"); + invokeMethod(resource,"setResourceVersion","1.0"); + + resources.add(resource); + return resources; + } + + private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + Method[] methods = object.getClass().getDeclaredMethods(); + for(Method method:methods){ + if(methodName.equalsIgnoreCase(method.getName())){ + method.setAccessible(true); + method.invoke(object,arguments); + } + } + } + + private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) + .stream() + .filter(constructor1 -> constructor1.getParameterCount()==0) + .collect(Collectors.toList()) + .get(0); + constructor.setAccessible(true); + return constructor.newInstance(); + } + + private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcCallbackTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcCallbackTest.java new file mode 100644 index 000000000..1333ac022 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcCallbackTest.java @@ -0,0 +1,233 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; +import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator; +import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory; +import org.onap.appc.sdc.artifacts.impl.ToscaCsarArtifactProcessor; +import org.onap.appc.sdc.artifacts.object.SDCArtifact; +import org.onap.appc.sdc.artifacts.object.SDCReference; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.INotificationCallback; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.impl.DistributionClientDownloadResultImpl; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.mockito.Matchers.anyObject; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({IDistributionClient.class, + EventSender.class, + ArtifactStorageService.class, + ToscaCsarArtifactProcessor.class, + ArtifactProcessorFactory.class, + DependencyModelGenerator.class}) +public class SdcCallbackTest { + + private INotificationCallback sdcCallback; + private ArtifactStorageService storageService; + private ToscaCsarArtifactProcessor artifactProcessor; + private String resourceContent; + + + @Before + public void setup() throws Exception { + IDistributionClient client = PowerMockito.mock(IDistributionClient.class); + EventSender eventSender = PowerMockito.mock(EventSender.class); + sdcCallback = new SdcCallback(null, client); + resourceContent=readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(),""); + artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client, eventSender, getNotificationData(), getResources().get(0) + , getServiceArtifacts().get(0), null)); + storageService = PowerMockito.mock(ArtifactStorageService.class); + Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); + DependencyModelGenerator dependencyModelGeneratorMock=PowerMockito.mock(DependencyModelGenerator.class); + PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(Matchers.anyString(),Matchers.anyString())) + .thenReturn("Dependency_model"); + Whitebox.setInternalState(artifactProcessor,"dependencyModelGenerator",dependencyModelGeneratorMock); + + PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact(anyObject()); + PowerMockito.doCallRealMethod().when(artifactProcessor).run(); + + //PowerMockito.mockStatic(ArtifactProcessorFactory.class); + ArtifactProcessorFactory artifactProcessorFactory=PowerMockito.mock(ArtifactProcessorFactory.class); + PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(anyObject(), anyObject(), + anyObject(), anyObject(), + anyObject(), anyObject())).thenReturn(artifactProcessor); + + Whitebox.setInternalState(sdcCallback,"eventSender", eventSender); + PowerMockito.doReturn(readDownloadResult()).when(client).download(anyObject()); + PowerMockito.doReturn(null).when(client).sendDownloadStatus(anyObject()); + + PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(), + Matchers.anyString(),Matchers.anyString()); + + PowerMockito.doAnswer(invocationOnMock -> { + System.out.print(invocationOnMock.getArguments()[0].toString()); + return null; + }).when(storageService).storeSDCArtifact(anyObject()); + } + + private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException { + DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl + (DistributionActionResultEnum.SUCCESS,"Download success"); + File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI()); + + byte[] bFile = new byte[(int) file.length()]; + FileInputStream fileInputStream = new FileInputStream(file); + fileInputStream.read(bFile); + fileInputStream.close(); + + downloadResult.setArtifactPayload(bFile); + return downloadResult; + } + + + @Test + public void testSDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + INotificationData notificationData = getNotificationData(); + sdcCallback.activateCallback(notificationData); + pause(); + } + + @Test + public void testArtifacts() throws Exception { + PowerMockito.doAnswer(invocationOnMock -> { + SDCArtifact artifact =(SDCArtifact)invocationOnMock.getArguments()[0]; + SDCReference reference=(SDCReference)invocationOnMock.getArguments()[1]; + Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID()); + Assert.assertEquals("Resource-APPC",reference.getVnfType()); + Assert.assertEquals(resourceContent.trim(),artifact.getArtifactContent().replaceAll(System.lineSeparator(),"")); + return null; + }).doAnswer(invocation -> { + SDCArtifact artifact =(SDCArtifact)invocation.getArguments()[0]; + SDCReference reference=(SDCReference)invocation.getArguments()[1]; + Assert.assertEquals("Resource-APPC",reference.getVnfType()); + Assert.assertEquals("tosca_dependency_model",reference.getFileCategory()); + Assert.assertEquals("Dependency_model",artifact.getArtifactContent()); + Assert.assertEquals("Resource-APPC",artifact.getResourceName()); + return null; + }).when(storageService).storeSDCArtifactWithReference(anyObject(),anyObject()); + + artifactProcessor.processArtifact(readDownloadResult()); + } + + private void pause(){ + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + } + } + + private String readInput(String inputFile) throws URISyntaxException { + File file = new File(this.getClass().getResource(inputFile).toURI()); + byte[] bFile = new byte[(int) file.length()]; + try(FileInputStream fileInputStream = new FileInputStream(file)){ + fileInputStream.read(bFile); + } catch (Exception e){ + e.printStackTrace(); + } + return new String(bFile); + } + + private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { + + INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + + List serviceArtifacts = getServiceArtifacts(); + + invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); + return notificationData; + } + + private List getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + List resources = new ArrayList<>(); + IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + + List serviceArtifacts = getServiceArtifacts(); + invokeMethod(resource,"setArtifacts",serviceArtifacts); + invokeMethod(resource,"setResourceName","Vnf"); + invokeMethod(resource,"setResourceVersion","1.0"); + + resources.add(resource); + return resources; + } + + private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + Method[] methods = object.getClass().getDeclaredMethods(); + for(Method method:methods){ + if(methodName.equalsIgnoreCase(method.getName())){ + method.setAccessible(true); + method.invoke(object,arguments); + } + } + } + + private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) + .stream() + .filter(constructor1 -> constructor1.getParameterCount()==0) + .collect(Collectors.toList()) + .get(0); + constructor.setAccessible(true); + return constructor.newInstance(); + } + + private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcListenerTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcListenerTest.java new file mode 100644 index 000000000..7b60ce460 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcListenerTest.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.sdc.api.IDistributionClient; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(Thread.class) +public class SdcListenerTest { + private SdcListener sdcListener; + private EELFLogger mockLogger = mock(EELFLogger.class); + + @Before + public void setUp() throws Exception { + sdcListener = new SdcListener(); + + // to avoid operation on logger fail, mock up the logger + Whitebox.setInternalState(sdcListener, "logger", mockLogger); + } + + @Test + public void testStart() throws Exception { + sdcListener.start(); + Assert.assertTrue("Should created startThread", + Whitebox.getInternalState(sdcListener, "startThread") != null); + } + + @Test + public void testStop() throws Exception { + // test interrupt thread and other null case + MockThread mockThread = spy(new MockThread()); + mockThread.setNewState(Thread.State.TIMED_WAITING); + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + + sdcListener.stop(); + Mockito.verify(mockThread, times(1)).interrupt(); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + + // test other non-null case and thread null case + IDistributionClient mockClient = mock(IDistributionClient.class); + Whitebox.setInternalState(sdcListener, "client", mockClient); + SdcCallback mockCallback = mock(SdcCallback.class); + Whitebox.setInternalState(sdcListener, "callback", mockCallback); + CountDownLatch mockLatch = mock(CountDownLatch.class); + Whitebox.setInternalState(sdcListener, "latch", mockLatch); + + sdcListener.stop(); + + Mockito.verify(mockLatch, times(1)).await(10, TimeUnit.SECONDS); + Mockito.verify(mockCallback, times(1)).stop(); + Mockito.verify(mockClient, times(1)).stop(); + Assert.assertTrue("Should reset latch", + Whitebox.getInternalState(sdcListener, "latch") == null); + Assert.assertTrue("Should reset callback", + Whitebox.getInternalState(sdcListener, "callback") == null); + Assert.assertTrue("Should reset client", + Whitebox.getInternalState(sdcListener, "client") == null); + } + + @Test + public void testStopStartThread() throws Exception { + // null case + sdcListener.stopStartThread(123); + //Mockito.verify(mockLogger, times(0)).debug(String.valueOf(any())); + + MockThread mockThread = spy(new MockThread()); + + // thread terminated case + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + mockThread.setNewState(Thread.State.TERMINATED); + sdcListener.stopStartThread(123); + Mockito.verify(mockThread, times(0)).interrupt(); + //Mockito.verify(mockLogger, times(1)).debug(String.valueOf(any())); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + + // thread not termianted case + int timesCallThread = 0; + int timesCallLogger = 1; + for(Thread.State state : Thread.State.values()) { + if (state == Thread.State.TERMINATED) { + continue; + } + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + mockThread.setNewState(state); + sdcListener.stopStartThread(123); + Mockito.verify(mockThread, times(++ timesCallThread)).interrupt(); + //Mockito.verify(mockLogger, times(timesCallLogger += 2)).debug(String.valueOf(any())); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + } + } + + /* + * I have used the following PowerMockito (due to Thread.getName() is a final method) + * try to mock up the thread behavior. But the mock Thread.getName() always returns null + * which works in intelliJ Junit test, but not Jenkins build: + * Thread mockThread = PowerMockito.mock(Thread.class); + * PowerMockito.doReturn(Thread.State.TERMINATED).when(mockThread).getState(); + * PowerMockito.doReturn("testing").when(mockThread).getName(); + * Hence, here goes the MockThread class to override Thread to my expected behavior. + */ + class MockThread extends Thread { + private State state; + + private MockThread() { + super.setName("testing"); + } + + void setNewState(State newState) { + state = newState; + } + + @Override + public State getState() { + return state; + } + } +} \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestObjects.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestObjects.java new file mode 100644 index 000000000..49c93d0a9 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestObjects.java @@ -0,0 +1,21 @@ +package org.onap.appc.sdc.listener; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.sdc.artifacts.object.Vnfc; + +public class SdcTestObjects { + + @Test + public void testVnfcInstance(){ + Vnfc vnfc=new Vnfc(); + vnfc.setVnfcType("Firewall"); + vnfc.setMandatory(true); + vnfc.setResilienceType("Active"); + Assert.assertEquals("Firewall",vnfc.getVnfcType()); + Assert.assertEquals(true,vnfc.isMandatory()); + Assert.assertEquals("Active",vnfc.getResilienceType()); + } + + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestUtils.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestUtils.java new file mode 100644 index 000000000..7f2a01a7a --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/SdcTestUtils.java @@ -0,0 +1,108 @@ +package org.onap.appc.sdc.listener; + +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.io.File; +import java.io.FileInputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class SdcTestUtils { + + @Test + public void testToSdcStoreDocumentInput() throws Exception{ + Assert.assertEquals(readInput("/output/TestUtilResponse.json"), Util.toSdcStoreDocumentInput + (getNotificationData(),getResources(),getServiceArtifact(),"Mock data")); + } + + @Test + public void testProviderResponse(){ + ProviderResponse response=new ProviderResponse(200,"Success"); + Assert.assertEquals(200,response.getStatus()); + Assert.assertEquals("Success",response.getBody()); + } + + private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, + InstantiationException, InvocationTargetException { + + INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + + List serviceArtifacts = getServiceArtifacts(); + + invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); + invokeMethod(notificationData,"setServiceUUID","4564-4567-7897"); + invokeMethod(notificationData,"setDistributionID","Distribution ID Mock"); + invokeMethod(notificationData,"setServiceDescription","Service Description Mock"); + invokeMethod(notificationData,"setServiceName","Service Name Mock"); + + return notificationData; + } + + private IResourceInstance getResources() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + + List serviceArtifacts = getServiceArtifacts(); + invokeMethod(resource,"setArtifacts",serviceArtifacts); + invokeMethod(resource,"setResourceName","Vnf"); + invokeMethod(resource,"setResourceVersion","1.0"); + invokeMethod(resource,"setResourceUUID","Resource UUID"); + + return resource; + } + + private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + Method[] methods = object.getClass().getDeclaredMethods(); + for(Method method:methods){ + if(methodName.equalsIgnoreCase(method.getName())){ + method.setAccessible(true); + method.invoke(object,arguments); + } + } + } + private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) + .stream() + .filter(constructor1 -> constructor1.getParameterCount()==0) + .collect(Collectors.toList()) + .get(0); + constructor.setAccessible(true); + return constructor.newInstance(); + } + private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } + private IArtifactInfo getServiceArtifact() throws ClassNotFoundException, InvocationTargetException, + InstantiationException, IllegalAccessException { + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + return artifactInfo; + } + private String readInput(String inputFile) throws URISyntaxException { + File file = new File(this.getClass().getResource(inputFile).toURI()); + byte[] bFile = new byte[(int) file.length()]; + try(FileInputStream fileInputStream = new FileInputStream(file)){ + fileInputStream.read(bFile); + } catch (Exception e){ + e.printStackTrace(); + } + return new String(bFile); + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/TestRun.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/TestRun.java new file mode 100644 index 000000000..4b673318c --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/onap/appc/sdc/listener/TestRun.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.sdc.listener; + +import org.junit.Test; + +public class TestRun { + + @Test + public void testRunning() throws Exception { + /* + AppcSdcListenerActivator a = new AppcSdcListenerActivator(); + a.start(null); + Thread.sleep(10000); + a.stop(null); + */ + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestArtifactProcessor.java deleted file mode 100644 index 8253238e8..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestArtifactProcessor.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.onap.appc.sdc.artifacts.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.powermock.api.mockito.PowerMockito; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -public class TestArtifactProcessor { - - AbstractArtifactProcessor abstractArtifactProcessor; - - @Before - public void setup() throws Exception{ - IDistributionClient client = PowerMockito.mock(IDistributionClient.class); - EventSender eventSender = PowerMockito.mock(EventSender.class); - abstractArtifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) - ,getServiceArtifacts().get(0),null)); - } - - @Test - public void testGetArtifactObject(){ - SDCArtifact artifact=abstractArtifactProcessor.getArtifactObject("test"); - Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID()); - Assert.assertEquals("VF_LICENSE",artifact.getArtifactType()); - Assert.assertEquals("Vnf",artifact.getResourceName()); - Assert.assertEquals("1.0",artifact.getResourceVersion()); - Assert.assertEquals("test",artifact.getArtifactContent()); - } - - @Test - public void testFactoryForLicense() throws Exception{ - IDistributionClient client = PowerMockito.mock(IDistributionClient.class); - EventSender eventSender = PowerMockito.mock(EventSender.class); - ArtifactProcessorFactory factory=new ArtifactProcessorFactory(); - Assert.assertTrue(factory.getArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) - ,getServiceArtifacts().get(0),null) instanceof LicenseArtifactProcessor); - } - - @Test - public void testFactoryForConfig() throws Exception{ - IDistributionClient client = PowerMockito.mock(IDistributionClient.class); - EventSender eventSender = PowerMockito.mock(EventSender.class); - ArtifactProcessorFactory factory=new ArtifactProcessorFactory(); - Assert.assertTrue(factory.getArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) - ,getServiceArtifactsForConfig().get(0),null) instanceof ConfigArtifactProcessor); - } - - private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, - InstantiationException, InvocationTargetException { - - INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); - - List serviceArtifacts = getServiceArtifacts(); - - invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); - return notificationData; - } - - private List getResources() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List resources = new ArrayList<>(); - IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); - - List serviceArtifacts = getServiceArtifacts(); - invokeMethod(resource,"setArtifacts",serviceArtifacts); - invokeMethod(resource,"setResourceName","Vnf"); - invokeMethod(resource,"setResourceVersion","1.0"); - - resources.add(resource); - return resources; - } - - private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { - Method[] methods = object.getClass().getDeclaredMethods(); - for(Method method:methods){ - if(methodName.equalsIgnoreCase(method.getName())){ - method.setAccessible(true); - method.invoke(object,arguments); - } - } - } - - private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) - .stream() - .filter(constructor1 -> constructor1.getParameterCount()==0) - .collect(Collectors.toList()) - .get(0); - constructor.setAccessible(true); - return constructor.newInstance(); - } - - private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List serviceArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","VF_LICENSE"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - serviceArtifacts.add(artifactInfo); - return serviceArtifacts; - } - - private List getServiceArtifactsForConfig() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List serviceArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","APPC_CONFIG"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - serviceArtifacts.add(artifactInfo); - return serviceArtifacts; - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java deleted file mode 100644 index f4cbc6a74..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/artifacts/impl/TestLicenseArtifactProcessor.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.onap.appc.sdc.artifacts.impl; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.verify; - -@RunWith(PowerMockRunner.class) -public class TestLicenseArtifactProcessor { - - private LicenseArtifactProcessor artifactProcessor; - private ArtifactStorageService storageService; - - @Before - public void setup() throws Exception{ - IDistributionClient client = PowerMockito.mock(IDistributionClient.class); - EventSender eventSender = PowerMockito.mock(EventSender.class); - storageService = PowerMockito.mock(ArtifactStorageService.class); - artifactProcessor = Mockito.spy(new LicenseArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) - ,getServiceArtifacts().get(0),null)); - Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); - PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact((SDCArtifact)Matchers.anyObject()); - PowerMockito.doNothing().when(storageService).storeSDCArtifact(Matchers.anyObject()); - } - - @Test(expected = org.onap.appc.exceptions.APPCException.class) - public void testProcessArtifactWithMissingData() throws APPCException { - SDCArtifact artifact=new SDCArtifact(); - artifact.setResourceVersion("RESOURCE VERSION"); - artifact.setArtifactUUID("123-456-789"); - artifactProcessor.processArtifact(artifact); - } - @Test - public void testProcessArtifact() throws APPCException { - PowerMockito.when(storageService.retrieveSDCArtifact(anyString(),anyString(),anyString())).thenReturn(null); - SDCArtifact artifact=new SDCArtifact(); - artifact.setResourceVersion("RESOURCE VERSION"); - artifact.setArtifactUUID("123-456-789"); - artifact.setResourceName("Resource Name"); - artifactProcessor.processArtifact(artifact); - verify(storageService,Mockito.times(1)).storeSDCArtifact(anyObject()); - } - @Test - public void testProcessArtifactWithDuplicateArtifact() throws APPCException { - SDCArtifact artifact=new SDCArtifact(); - artifact.setResourceVersion("RESOURCE VERSION"); - artifact.setArtifactUUID("123-456-789"); - artifact.setResourceName("Resource Name"); - PowerMockito.when(storageService.retrieveSDCArtifact(anyString(),anyString(),anyString())).thenReturn(artifact); - artifactProcessor.processArtifact(artifact); - verify(storageService,Mockito.times(0)).storeSDCArtifact(anyObject()); - } - - private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, - InstantiationException, InvocationTargetException { - - org.openecomp.sdc.api.notification.INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); - - List serviceArtifacts = getServiceArtifacts(); - - invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); - return notificationData; - } - - private List getResources() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List resources = new ArrayList<>(); - IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); - - List serviceArtifacts = getServiceArtifacts(); - invokeMethod(resource,"setArtifacts",serviceArtifacts); - invokeMethod(resource,"setResourceName","Vnf"); - invokeMethod(resource,"setResourceVersion","1.0"); - - resources.add(resource); - return resources; - } - - private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { - Method[] methods = object.getClass().getDeclaredMethods(); - for(Method method:methods){ - if(methodName.equalsIgnoreCase(method.getName())){ - method.setAccessible(true); - method.invoke(object,arguments); - } - } - } - - private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) - .stream() - .filter(constructor1 -> constructor1.getParameterCount()==0) - .collect(Collectors.toList()) - .get(0); - constructor.setAccessible(true); - return constructor.newInstance(); - } - - private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List serviceArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - serviceArtifacts.add(artifactInfo); - return serviceArtifacts; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java deleted file mode 100644 index 1333ac022..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService; -import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator; -import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory; -import org.onap.appc.sdc.artifacts.impl.ToscaCsarArtifactProcessor; -import org.onap.appc.sdc.artifacts.object.SDCArtifact; -import org.onap.appc.sdc.artifacts.object.SDCReference; -import org.openecomp.sdc.api.IDistributionClient; -import org.openecomp.sdc.api.consumer.INotificationCallback; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.impl.DistributionClientDownloadResultImpl; -import org.openecomp.sdc.utils.DistributionActionResultEnum; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.mockito.Matchers.anyObject; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({IDistributionClient.class, - EventSender.class, - ArtifactStorageService.class, - ToscaCsarArtifactProcessor.class, - ArtifactProcessorFactory.class, - DependencyModelGenerator.class}) -public class SdcCallbackTest { - - private INotificationCallback sdcCallback; - private ArtifactStorageService storageService; - private ToscaCsarArtifactProcessor artifactProcessor; - private String resourceContent; - - - @Before - public void setup() throws Exception { - IDistributionClient client = PowerMockito.mock(IDistributionClient.class); - EventSender eventSender = PowerMockito.mock(EventSender.class); - sdcCallback = new SdcCallback(null, client); - resourceContent=readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(),""); - artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client, eventSender, getNotificationData(), getResources().get(0) - , getServiceArtifacts().get(0), null)); - storageService = PowerMockito.mock(ArtifactStorageService.class); - Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); - DependencyModelGenerator dependencyModelGeneratorMock=PowerMockito.mock(DependencyModelGenerator.class); - PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(Matchers.anyString(),Matchers.anyString())) - .thenReturn("Dependency_model"); - Whitebox.setInternalState(artifactProcessor,"dependencyModelGenerator",dependencyModelGeneratorMock); - - PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact(anyObject()); - PowerMockito.doCallRealMethod().when(artifactProcessor).run(); - - //PowerMockito.mockStatic(ArtifactProcessorFactory.class); - ArtifactProcessorFactory artifactProcessorFactory=PowerMockito.mock(ArtifactProcessorFactory.class); - PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(anyObject(), anyObject(), - anyObject(), anyObject(), - anyObject(), anyObject())).thenReturn(artifactProcessor); - - Whitebox.setInternalState(sdcCallback,"eventSender", eventSender); - PowerMockito.doReturn(readDownloadResult()).when(client).download(anyObject()); - PowerMockito.doReturn(null).when(client).sendDownloadStatus(anyObject()); - - PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(), - Matchers.anyString(),Matchers.anyString()); - - PowerMockito.doAnswer(invocationOnMock -> { - System.out.print(invocationOnMock.getArguments()[0].toString()); - return null; - }).when(storageService).storeSDCArtifact(anyObject()); - } - - private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException { - DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl - (DistributionActionResultEnum.SUCCESS,"Download success"); - File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI()); - - byte[] bFile = new byte[(int) file.length()]; - FileInputStream fileInputStream = new FileInputStream(file); - fileInputStream.read(bFile); - fileInputStream.close(); - - downloadResult.setArtifactPayload(bFile); - return downloadResult; - } - - - @Test - public void testSDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - INotificationData notificationData = getNotificationData(); - sdcCallback.activateCallback(notificationData); - pause(); - } - - @Test - public void testArtifacts() throws Exception { - PowerMockito.doAnswer(invocationOnMock -> { - SDCArtifact artifact =(SDCArtifact)invocationOnMock.getArguments()[0]; - SDCReference reference=(SDCReference)invocationOnMock.getArguments()[1]; - Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID()); - Assert.assertEquals("Resource-APPC",reference.getVnfType()); - Assert.assertEquals(resourceContent.trim(),artifact.getArtifactContent().replaceAll(System.lineSeparator(),"")); - return null; - }).doAnswer(invocation -> { - SDCArtifact artifact =(SDCArtifact)invocation.getArguments()[0]; - SDCReference reference=(SDCReference)invocation.getArguments()[1]; - Assert.assertEquals("Resource-APPC",reference.getVnfType()); - Assert.assertEquals("tosca_dependency_model",reference.getFileCategory()); - Assert.assertEquals("Dependency_model",artifact.getArtifactContent()); - Assert.assertEquals("Resource-APPC",artifact.getResourceName()); - return null; - }).when(storageService).storeSDCArtifactWithReference(anyObject(),anyObject()); - - artifactProcessor.processArtifact(readDownloadResult()); - } - - private void pause(){ - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } - } - - private String readInput(String inputFile) throws URISyntaxException { - File file = new File(this.getClass().getResource(inputFile).toURI()); - byte[] bFile = new byte[(int) file.length()]; - try(FileInputStream fileInputStream = new FileInputStream(file)){ - fileInputStream.read(bFile); - } catch (Exception e){ - e.printStackTrace(); - } - return new String(bFile); - } - - private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { - - INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); - - List serviceArtifacts = getServiceArtifacts(); - - invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); - return notificationData; - } - - private List getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { - List resources = new ArrayList<>(); - IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); - - List serviceArtifacts = getServiceArtifacts(); - invokeMethod(resource,"setArtifacts",serviceArtifacts); - invokeMethod(resource,"setResourceName","Vnf"); - invokeMethod(resource,"setResourceVersion","1.0"); - - resources.add(resource); - return resources; - } - - private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { - Method[] methods = object.getClass().getDeclaredMethods(); - for(Method method:methods){ - if(methodName.equalsIgnoreCase(method.getName())){ - method.setAccessible(true); - method.invoke(object,arguments); - } - } - } - - private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) - .stream() - .filter(constructor1 -> constructor1.getParameterCount()==0) - .collect(Collectors.toList()) - .get(0); - constructor.setAccessible(true); - return constructor.newInstance(); - } - - private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { - List serviceArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - serviceArtifacts.add(artifactInfo); - return serviceArtifacts; - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java deleted file mode 100644 index 7b60ce460..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.sdc.listener; - -import com.att.eelf.configuration.EELFLogger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.openecomp.sdc.api.IDistributionClient; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(Thread.class) -public class SdcListenerTest { - private SdcListener sdcListener; - private EELFLogger mockLogger = mock(EELFLogger.class); - - @Before - public void setUp() throws Exception { - sdcListener = new SdcListener(); - - // to avoid operation on logger fail, mock up the logger - Whitebox.setInternalState(sdcListener, "logger", mockLogger); - } - - @Test - public void testStart() throws Exception { - sdcListener.start(); - Assert.assertTrue("Should created startThread", - Whitebox.getInternalState(sdcListener, "startThread") != null); - } - - @Test - public void testStop() throws Exception { - // test interrupt thread and other null case - MockThread mockThread = spy(new MockThread()); - mockThread.setNewState(Thread.State.TIMED_WAITING); - Whitebox.setInternalState(sdcListener, "startThread", mockThread); - - sdcListener.stop(); - Mockito.verify(mockThread, times(1)).interrupt(); - Assert.assertTrue("Should reset startThread", - Whitebox.getInternalState(sdcListener, "startThread") == null); - - // test other non-null case and thread null case - IDistributionClient mockClient = mock(IDistributionClient.class); - Whitebox.setInternalState(sdcListener, "client", mockClient); - SdcCallback mockCallback = mock(SdcCallback.class); - Whitebox.setInternalState(sdcListener, "callback", mockCallback); - CountDownLatch mockLatch = mock(CountDownLatch.class); - Whitebox.setInternalState(sdcListener, "latch", mockLatch); - - sdcListener.stop(); - - Mockito.verify(mockLatch, times(1)).await(10, TimeUnit.SECONDS); - Mockito.verify(mockCallback, times(1)).stop(); - Mockito.verify(mockClient, times(1)).stop(); - Assert.assertTrue("Should reset latch", - Whitebox.getInternalState(sdcListener, "latch") == null); - Assert.assertTrue("Should reset callback", - Whitebox.getInternalState(sdcListener, "callback") == null); - Assert.assertTrue("Should reset client", - Whitebox.getInternalState(sdcListener, "client") == null); - } - - @Test - public void testStopStartThread() throws Exception { - // null case - sdcListener.stopStartThread(123); - //Mockito.verify(mockLogger, times(0)).debug(String.valueOf(any())); - - MockThread mockThread = spy(new MockThread()); - - // thread terminated case - Whitebox.setInternalState(sdcListener, "startThread", mockThread); - mockThread.setNewState(Thread.State.TERMINATED); - sdcListener.stopStartThread(123); - Mockito.verify(mockThread, times(0)).interrupt(); - //Mockito.verify(mockLogger, times(1)).debug(String.valueOf(any())); - Assert.assertTrue("Should reset startThread", - Whitebox.getInternalState(sdcListener, "startThread") == null); - - // thread not termianted case - int timesCallThread = 0; - int timesCallLogger = 1; - for(Thread.State state : Thread.State.values()) { - if (state == Thread.State.TERMINATED) { - continue; - } - Whitebox.setInternalState(sdcListener, "startThread", mockThread); - mockThread.setNewState(state); - sdcListener.stopStartThread(123); - Mockito.verify(mockThread, times(++ timesCallThread)).interrupt(); - //Mockito.verify(mockLogger, times(timesCallLogger += 2)).debug(String.valueOf(any())); - Assert.assertTrue("Should reset startThread", - Whitebox.getInternalState(sdcListener, "startThread") == null); - } - } - - /* - * I have used the following PowerMockito (due to Thread.getName() is a final method) - * try to mock up the thread behavior. But the mock Thread.getName() always returns null - * which works in intelliJ Junit test, but not Jenkins build: - * Thread mockThread = PowerMockito.mock(Thread.class); - * PowerMockito.doReturn(Thread.State.TERMINATED).when(mockThread).getState(); - * PowerMockito.doReturn("testing").when(mockThread).getName(); - * Hence, here goes the MockThread class to override Thread to my expected behavior. - */ - class MockThread extends Thread { - private State state; - - private MockThread() { - super.setName("testing"); - } - - void setNewState(State newState) { - state = newState; - } - - @Override - public State getState() { - return state; - } - } -} \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestObjects.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestObjects.java deleted file mode 100644 index 49c93d0a9..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestObjects.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.onap.appc.sdc.listener; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.sdc.artifacts.object.Vnfc; - -public class SdcTestObjects { - - @Test - public void testVnfcInstance(){ - Vnfc vnfc=new Vnfc(); - vnfc.setVnfcType("Firewall"); - vnfc.setMandatory(true); - vnfc.setResilienceType("Active"); - Assert.assertEquals("Firewall",vnfc.getVnfcType()); - Assert.assertEquals(true,vnfc.isMandatory()); - Assert.assertEquals("Active",vnfc.getResilienceType()); - } - - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestUtils.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestUtils.java deleted file mode 100644 index 7f2a01a7a..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcTestUtils.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.onap.appc.sdc.listener; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; - -import java.io.File; -import java.io.FileInputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -public class SdcTestUtils { - - @Test - public void testToSdcStoreDocumentInput() throws Exception{ - Assert.assertEquals(readInput("/output/TestUtilResponse.json"), Util.toSdcStoreDocumentInput - (getNotificationData(),getResources(),getServiceArtifact(),"Mock data")); - } - - @Test - public void testProviderResponse(){ - ProviderResponse response=new ProviderResponse(200,"Success"); - Assert.assertEquals(200,response.getStatus()); - Assert.assertEquals("Success",response.getBody()); - } - - private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, - InstantiationException, InvocationTargetException { - - INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); - - List serviceArtifacts = getServiceArtifacts(); - - invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); - invokeMethod(notificationData,"setServiceUUID","4564-4567-7897"); - invokeMethod(notificationData,"setDistributionID","Distribution ID Mock"); - invokeMethod(notificationData,"setServiceDescription","Service Description Mock"); - invokeMethod(notificationData,"setServiceName","Service Name Mock"); - - return notificationData; - } - - private IResourceInstance getResources() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); - - List serviceArtifacts = getServiceArtifacts(); - invokeMethod(resource,"setArtifacts",serviceArtifacts); - invokeMethod(resource,"setResourceName","Vnf"); - invokeMethod(resource,"setResourceVersion","1.0"); - invokeMethod(resource,"setResourceUUID","Resource UUID"); - - return resource; - } - - private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { - Method[] methods = object.getClass().getDeclaredMethods(); - for(Method method:methods){ - if(methodName.equalsIgnoreCase(method.getName())){ - method.setAccessible(true); - method.invoke(object,arguments); - } - } - } - private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors()) - .stream() - .filter(constructor1 -> constructor1.getParameterCount()==0) - .collect(Collectors.toList()) - .get(0); - constructor.setAccessible(true); - return constructor.newInstance(); - } - private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - List serviceArtifacts = new ArrayList<>(); - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - serviceArtifacts.add(artifactInfo); - return serviceArtifacts; - } - private IArtifactInfo getServiceArtifact() throws ClassNotFoundException, InvocationTargetException, - InstantiationException, IllegalAccessException { - IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); - invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); - invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); - return artifactInfo; - } - private String readInput(String inputFile) throws URISyntaxException { - File file = new File(this.getClass().getResource(inputFile).toURI()); - byte[] bFile = new byte[(int) file.length()]; - try(FileInputStream fileInputStream = new FileInputStream(file)){ - fileInputStream.read(bFile); - } catch (Exception e){ - e.printStackTrace(); - } - return new String(bFile); - } -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java deleted file mode 100644 index 4b673318c..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.sdc.listener; - -import org.junit.Test; - -public class TestRun { - - @Test - public void testRunning() throws Exception { - /* - AppcSdcListenerActivator a = new AppcSdcListenerActivator(); - a.start(null); - Thread.sleep(10000); - a.stop(null); - */ - } - -} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/onap/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..522e0ed72 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,36 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# These ASDC properties were provided by the ASDC Op-So team +appc.sdc.keystore.path=etc/sdc-client.jks +appc.sdc.keystore.pass=Aa123456 + +appc.sdc.host=192.168.1.2:8443 +appc.sdc.env=TEST +appc.sdc.user=appc +appc.sdc.pass=appc + +appc.sdc.consumer=TEST +appc.sdc.consumer.id=TEST +appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 522e0ed72..000000000 --- a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,36 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# These ASDC properties were provided by the ASDC Op-So team -appc.sdc.keystore.path=etc/sdc-client.jks -appc.sdc.keystore.pass=Aa123456 - -appc.sdc.host=192.168.1.2:8443 -appc.sdc.env=TEST -appc.sdc.user=appc -appc.sdc.pass=appc - -appc.sdc.consumer=TEST -appc.sdc.consumer.id=TEST -appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/YANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/YANGGenerator.java new file mode 100644 index 000000000..e0ad22a54 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/YANGGenerator.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang; + +import org.onap.appc.yang.exception.YANGGenerationException; + +import java.io.OutputStream; + +/** + * The Interface YANGGenerator - provides method to generate YANG file from TOSCA. + */ +public interface YANGGenerator { + + /** + * Generate YANG from TOSCA. + * if any exceptional Type is coming in the input tosca as a part of configuration parameter property, YANGGenerationException will be thrown. + * This API is not supporting below mentioned built-in Types: + * bits, decimal64, enumeration, identityref, leafref, union + * + * @param uniqueID - Set as module name in the yang, mandatory, cannot be null or empty + * @param tosca - TOSCA String from which the YANG is to be generated, mandatory, cannot be null or empty + * @param stream - The outputStream to which the generated yang is written, mandatory, cannot be null + * @throws YANGGenerationException - Thrown when any error occurred during method execution, the origin can be found from ex.getCause() or ex.getMessage() + */ + + void generateYANG(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException; +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/exception/YANGGenerationException.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/exception/YANGGenerationException.java new file mode 100644 index 000000000..690a2fda6 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/exception/YANGGenerationException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang.exception; + +/** + * The Class YANGGenerationException. + */ +public class YANGGenerationException extends Exception { + + + /** + * Instantiates a new YANG generation exception. + * + * @param message - the appropriate message + * @param cause -the appropriate cause + */ + public YANGGenerationException(String message,Throwable cause){ + super(message,cause); + } + + + /** + * Instantiates new YANG generation exception + * @param message + */ + public YANGGenerationException(String message){ + super(message); + } +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorFactory.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorFactory.java new file mode 100644 index 000000000..fe278d412 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorFactory.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang.impl; + +import org.onap.appc.yang.YANGGenerator; + +/** + * A factory for creating YANGGenerator objects. + */ +public class YANGGeneratorFactory { + + private YANGGeneratorFactory(){} + + private static class InstanceHolder + { + private static YANGGeneratorImpl instance = new YANGGeneratorImpl(); + private InstanceHolder(){} + } + + /** + * Gets the YANG generator. + * + * @return the YANG generator + */ + public static YANGGenerator getYANGGenerator() + { + return InstanceHolder.instance; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorImpl.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorImpl.java new file mode 100644 index 000000000..55ff41cbd --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/impl/YANGGeneratorImpl.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; +import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl; +import org.onap.appc.yang.YANGGenerator; +import org.onap.appc.yang.exception.YANGGenerationException; +import org.onap.appc.yang.objects.Leaf; +import org.onap.appc.yang.type.YangTypes; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.YamlUtil; + +import java.io.*; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@SuppressWarnings("CheckStyle") +public class YANGGeneratorImpl implements YANGGenerator { + + private static final EELFLogger Log = EELFManager.getInstance().getLogger(YANGGeneratorImpl.class); + private static final String MODULE_TYPE = "moduleType"; + private static final String LEAVES = "leaves"; + + + /* (non-Javadoc) + * @see org.onap.appc.yang.YANGGenerator#generateYANG(java.lang.String, java.lang.String, java.io.OutputStream) + */ + @Override + public void generateYANG(String uniqueID, String tosca, OutputStream stream) + throws YANGGenerationException { + Log.info("Entered into generateYANG."); + Log.debug("Received Tosca:\n" + tosca +"\n Received uniqueID: "+uniqueID); + + validateInput(uniqueID, tosca, stream); + Map parsedToscaMap = parseTosca(tosca); + String moduleType =parsedToscaMap.get(MODULE_TYPE).toString(); + List leaves = (List) parsedToscaMap.get(LEAVES); + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); + ve.init(); + Template template; + + try { + template = ve.getTemplate("templates/YangTemplate.vm"); + } catch ( ResourceNotFoundException | ParseErrorException ex) { + Log.error("Error while retrieving YANG Template", ex); + throw new YANGGenerationException("Error while retrieving YANG Template",ex); + } + + VelocityContext vc = new VelocityContext(); + + vc.put("moduleName", uniqueID); + vc.put(MODULE_TYPE, moduleType); + vc.put(LEAVES, leaves); + + StringWriter sw = new StringWriter(); + template.merge(vc,sw); + Log.debug("generated YANG \n "+sw.toString()); + try { + String yang = sw.toString(); + validateYang(yang); + stream.write(yang.getBytes()); + stream.flush(); + } catch (IOException e) { + Log.error("Error while writing to outputstream", e); + throw new YANGGenerationException("Error writing to outputstream",e); + } finally { + try { + stream.close(); + } catch (IOException e) { + Log.error("Error while closing outputstream", e); + } + } + Log.info("exiting generateYANG method."); + } + + private void validateYang(String yang) throws YANGGenerationException { + + try(InputStream inputYangStream = new ByteArrayInputStream(yang.getBytes())){ + YangStatementSourceImpl statementSource = new YangStatementSourceImpl(inputYangStream); + if(statementSource.getYangAST()==null){ + throw new YANGGenerationException("Syntax Error in Generated YANG = " + yang); + } + } + catch(IOException e){ + Log.error("Error validating yang file "+ yang,e); + throw new YANGGenerationException("Invalid YANG generated",e); + } + } + + private Map parseTosca(String tosca) throws YANGGenerationException { + Log.info("Entered into parseTosca."); + ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(tosca, ServiceTemplate.class); + Map nodeTypeMap = serviceTemplate.getNode_types(); + String kind = nodeTypeMap.keySet().toArray(new String[0])[0]; + NodeType nodeType = nodeTypeMap.get(kind); + Map returnMap= new HashMap<>(); + Map propertyDefinitionFromTOSCA = nodeType.getProperties(); + returnMap.put(MODULE_TYPE, kind); + List leaves = new LinkedList<>(); + + for(Map.Entry entry: propertyDefinitionFromTOSCA.entrySet()){ + Leaf leaf = new Leaf(); + leaf.setName(entry.getKey()); + PropertyDefinition pd = entry.getValue(); + Map typeMap=YangTypes.getYangTypeMap(); + if (typeMap.containsKey(pd.getType())) { + String paramType = typeMap.get(pd.getType()); + leaf.setType(paramType); + leaf.setDescription(!StringUtils.isEmpty(pd.getDescription()) ? pd.getDescription() : ""); + leaf.setMandatory((pd.getRequired() != null) ? Boolean.toString(pd.getRequired()) : Boolean.toString(false)); + leaf.setDefaultValue((pd.get_default() != null) ? pd.get_default().toString(): ""); + leaves.add(leaf); + } else { + YANGGenerationException yangGenerationException = new YANGGenerationException(pd.getType() + " Type is not supported ", null); + Log.error(pd.getType() + " Type is not supported ", yangGenerationException); + throw yangGenerationException; + } + } + returnMap.put(LEAVES, leaves); + Log.info("exiting parseTosca method with return MAP "+returnMap); + return returnMap; + } + + private void validateInput(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException { + Log.info("Entered into validateInput."); + if(StringUtils.isEmpty(uniqueID)) { + throw new YANGGenerationException("uniqueID is mandatory, cannot be null or empty.",null); + } + if(StringUtils.isEmpty(tosca)) { + throw new YANGGenerationException("tosca is mandatory, cannot be null or empty.",null); + } + if(stream == null){ + throw new YANGGenerationException("stream is mandatory, cannot be null.",null); + } + Log.info("exiting validateInput method."); + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/objects/Leaf.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/objects/Leaf.java new file mode 100644 index 000000000..2ec66b680 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/objects/Leaf.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang.objects; + +public class Leaf { + private String name; + private String type; + private String description; + private String mandatory; + private String defaultValue; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getMandatory() { + return mandatory; + } + public void setMandatory(String mandatory) { + this.mandatory = mandatory; + } + public String getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + @Override + public String toString() { + return "Leaf [name=" + name + ", type=" + type + ", description=" + description + ", mandatory=" + mandatory + + ", defaultValue=" + defaultValue + "]"; + } + + + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/type/YangTypes.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/type/YangTypes.java new file mode 100644 index 000000000..97fb9973d --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/onap/appc/yang/type/YangTypes.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.yang.type; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class YangTypes { + + private static final Map yangTypeMap; + private YangTypes(){} + static { + Map typeMap = new HashMap<>(); + + /* standard Types */ + /* typeMap.put("bits","bits"); + typeMap.put("leafref","leafref"); + typeMap.put("decimal64","decimal64"); + typeMap.put("enumeration","enumeration"); + typeMap.put("identityref","identityref"); + typeMap.put("union","union");*/ + typeMap.put("binary","binary"); + typeMap.put("boolean","boolean"); + typeMap.put("empty","empty"); + typeMap.put("instance-identifier","instance-identifier"); + typeMap.put("int8","int8"); + typeMap.put("int16","int16"); + typeMap.put("int32","int32"); + typeMap.put("int64","int64"); + typeMap.put("string","string"); + typeMap.put("uint8","uint8"); + typeMap.put("uint16","uint16"); + typeMap.put("uint32","uint32"); + typeMap.put("uint64","uint64"); + + + /* ietf-yang-types */ + + typeMap.put("counter32","yang:counter32"); + typeMap.put("zero-based-counter32","yang:zero-based-counter32"); + typeMap.put("counter64","yang:counter64"); + typeMap.put("zero-based-counter64","yang:zero-based-counter64"); + typeMap.put("gauge32","yang:gauge32"); + typeMap.put("gauge64","yang:gauge64"); + typeMap.put("object-identifier","yang:object-identifier"); + typeMap.put("object-identifier-128","yang:object-identifier-128"); + typeMap.put("yang-identifier","yang:yang-identifier"); + typeMap.put("date-and-time","yang:date-and-time"); + typeMap.put("timeticks","yang:timeticks"); + typeMap.put("timestamp","yang:timestamp"); + typeMap.put("phys-address","yang:phys-address"); + typeMap.put("mac-address","yang:mac-address"); + typeMap.put("xpath1.0","yang:xpath1.0"); + typeMap.put("hex-string","yang:hex-string"); + typeMap.put("uuid","yang:uuid"); + typeMap.put("dotted-quad","yang:dotted-quad"); + + /* ietf-inet-types */ + + typeMap.put("ip-version","inet:ip-version"); + typeMap.put("dscp","inet:dscp"); + typeMap.put("ipv6-flow-label","inet:ipv6-flow-label"); + typeMap.put("port-number","inet:port-number"); + typeMap.put("as-number","inet:as-number"); + typeMap.put("ip-address","inet:ip-address"); + typeMap.put("ipv4-address","inet:ipv4-address"); + typeMap.put("ipv6-address","inet:ipv6-address"); + typeMap.put("ip-address-no-zone","inet:ip-address-no-zone"); + typeMap.put("ipv4-address-no-zone","inet:ipv4-address-no-zone"); + typeMap.put("ipv6-address-no-zone","inet:ipv6-address-no-zone"); + typeMap.put("ip-prefix","inet:ip-prefix"); + typeMap.put("ipv4-prefix","inet:ipv4-prefix"); + typeMap.put("ipv6-prefix","inet:ipv6-prefix"); + typeMap.put("domain-name","inet:domain-name"); + typeMap.put("host","inet:host"); + typeMap.put("uri","inet:uri"); + + yangTypeMap = Collections.unmodifiableMap(typeMap); + } + + public static Map getYangTypeMap(){ + return yangTypeMap; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java deleted file mode 100644 index e0ad22a54..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang; - -import org.onap.appc.yang.exception.YANGGenerationException; - -import java.io.OutputStream; - -/** - * The Interface YANGGenerator - provides method to generate YANG file from TOSCA. - */ -public interface YANGGenerator { - - /** - * Generate YANG from TOSCA. - * if any exceptional Type is coming in the input tosca as a part of configuration parameter property, YANGGenerationException will be thrown. - * This API is not supporting below mentioned built-in Types: - * bits, decimal64, enumeration, identityref, leafref, union - * - * @param uniqueID - Set as module name in the yang, mandatory, cannot be null or empty - * @param tosca - TOSCA String from which the YANG is to be generated, mandatory, cannot be null or empty - * @param stream - The outputStream to which the generated yang is written, mandatory, cannot be null - * @throws YANGGenerationException - Thrown when any error occurred during method execution, the origin can be found from ex.getCause() or ex.getMessage() - */ - - void generateYANG(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException; -} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java deleted file mode 100644 index 690a2fda6..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang.exception; - -/** - * The Class YANGGenerationException. - */ -public class YANGGenerationException extends Exception { - - - /** - * Instantiates a new YANG generation exception. - * - * @param message - the appropriate message - * @param cause -the appropriate cause - */ - public YANGGenerationException(String message,Throwable cause){ - super(message,cause); - } - - - /** - * Instantiates new YANG generation exception - * @param message - */ - public YANGGenerationException(String message){ - super(message); - } -} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java deleted file mode 100644 index fe278d412..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang.impl; - -import org.onap.appc.yang.YANGGenerator; - -/** - * A factory for creating YANGGenerator objects. - */ -public class YANGGeneratorFactory { - - private YANGGeneratorFactory(){} - - private static class InstanceHolder - { - private static YANGGeneratorImpl instance = new YANGGeneratorImpl(); - private InstanceHolder(){} - } - - /** - * Gets the YANG generator. - * - * @return the YANG generator - */ - public static YANGGenerator getYANGGenerator() - { - return InstanceHolder.instance; - } - -} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java deleted file mode 100644 index 55ff41cbd..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang.StringUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.RuntimeConstants; -import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; -import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl; -import org.onap.appc.yang.YANGGenerator; -import org.onap.appc.yang.exception.YANGGenerationException; -import org.onap.appc.yang.objects.Leaf; -import org.onap.appc.yang.type.YangTypes; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.YamlUtil; - -import java.io.*; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -@SuppressWarnings("CheckStyle") -public class YANGGeneratorImpl implements YANGGenerator { - - private static final EELFLogger Log = EELFManager.getInstance().getLogger(YANGGeneratorImpl.class); - private static final String MODULE_TYPE = "moduleType"; - private static final String LEAVES = "leaves"; - - - /* (non-Javadoc) - * @see org.onap.appc.yang.YANGGenerator#generateYANG(java.lang.String, java.lang.String, java.io.OutputStream) - */ - @Override - public void generateYANG(String uniqueID, String tosca, OutputStream stream) - throws YANGGenerationException { - Log.info("Entered into generateYANG."); - Log.debug("Received Tosca:\n" + tosca +"\n Received uniqueID: "+uniqueID); - - validateInput(uniqueID, tosca, stream); - Map parsedToscaMap = parseTosca(tosca); - String moduleType =parsedToscaMap.get(MODULE_TYPE).toString(); - List leaves = (List) parsedToscaMap.get(LEAVES); - VelocityEngine ve = new VelocityEngine(); - ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); - ve.init(); - Template template; - - try { - template = ve.getTemplate("templates/YangTemplate.vm"); - } catch ( ResourceNotFoundException | ParseErrorException ex) { - Log.error("Error while retrieving YANG Template", ex); - throw new YANGGenerationException("Error while retrieving YANG Template",ex); - } - - VelocityContext vc = new VelocityContext(); - - vc.put("moduleName", uniqueID); - vc.put(MODULE_TYPE, moduleType); - vc.put(LEAVES, leaves); - - StringWriter sw = new StringWriter(); - template.merge(vc,sw); - Log.debug("generated YANG \n "+sw.toString()); - try { - String yang = sw.toString(); - validateYang(yang); - stream.write(yang.getBytes()); - stream.flush(); - } catch (IOException e) { - Log.error("Error while writing to outputstream", e); - throw new YANGGenerationException("Error writing to outputstream",e); - } finally { - try { - stream.close(); - } catch (IOException e) { - Log.error("Error while closing outputstream", e); - } - } - Log.info("exiting generateYANG method."); - } - - private void validateYang(String yang) throws YANGGenerationException { - - try(InputStream inputYangStream = new ByteArrayInputStream(yang.getBytes())){ - YangStatementSourceImpl statementSource = new YangStatementSourceImpl(inputYangStream); - if(statementSource.getYangAST()==null){ - throw new YANGGenerationException("Syntax Error in Generated YANG = " + yang); - } - } - catch(IOException e){ - Log.error("Error validating yang file "+ yang,e); - throw new YANGGenerationException("Invalid YANG generated",e); - } - } - - private Map parseTosca(String tosca) throws YANGGenerationException { - Log.info("Entered into parseTosca."); - ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(tosca, ServiceTemplate.class); - Map nodeTypeMap = serviceTemplate.getNode_types(); - String kind = nodeTypeMap.keySet().toArray(new String[0])[0]; - NodeType nodeType = nodeTypeMap.get(kind); - Map returnMap= new HashMap<>(); - Map propertyDefinitionFromTOSCA = nodeType.getProperties(); - returnMap.put(MODULE_TYPE, kind); - List leaves = new LinkedList<>(); - - for(Map.Entry entry: propertyDefinitionFromTOSCA.entrySet()){ - Leaf leaf = new Leaf(); - leaf.setName(entry.getKey()); - PropertyDefinition pd = entry.getValue(); - Map typeMap=YangTypes.getYangTypeMap(); - if (typeMap.containsKey(pd.getType())) { - String paramType = typeMap.get(pd.getType()); - leaf.setType(paramType); - leaf.setDescription(!StringUtils.isEmpty(pd.getDescription()) ? pd.getDescription() : ""); - leaf.setMandatory((pd.getRequired() != null) ? Boolean.toString(pd.getRequired()) : Boolean.toString(false)); - leaf.setDefaultValue((pd.get_default() != null) ? pd.get_default().toString(): ""); - leaves.add(leaf); - } else { - YANGGenerationException yangGenerationException = new YANGGenerationException(pd.getType() + " Type is not supported ", null); - Log.error(pd.getType() + " Type is not supported ", yangGenerationException); - throw yangGenerationException; - } - } - returnMap.put(LEAVES, leaves); - Log.info("exiting parseTosca method with return MAP "+returnMap); - return returnMap; - } - - private void validateInput(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException { - Log.info("Entered into validateInput."); - if(StringUtils.isEmpty(uniqueID)) { - throw new YANGGenerationException("uniqueID is mandatory, cannot be null or empty.",null); - } - if(StringUtils.isEmpty(tosca)) { - throw new YANGGenerationException("tosca is mandatory, cannot be null or empty.",null); - } - if(stream == null){ - throw new YANGGenerationException("stream is mandatory, cannot be null.",null); - } - Log.info("exiting validateInput method."); - } - -} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java deleted file mode 100644 index 2ec66b680..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang.objects; - -public class Leaf { - private String name; - private String type; - private String description; - private String mandatory; - private String defaultValue; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getMandatory() { - return mandatory; - } - public void setMandatory(String mandatory) { - this.mandatory = mandatory; - } - public String getDefaultValue() { - return defaultValue; - } - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - @Override - public String toString() { - return "Leaf [name=" + name + ", type=" + type + ", description=" + description + ", mandatory=" + mandatory - + ", defaultValue=" + defaultValue + "]"; - } - - - -} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java deleted file mode 100644 index 97fb9973d..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.yang.type; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -public class YangTypes { - - private static final Map yangTypeMap; - private YangTypes(){} - static { - Map typeMap = new HashMap<>(); - - /* standard Types */ - /* typeMap.put("bits","bits"); - typeMap.put("leafref","leafref"); - typeMap.put("decimal64","decimal64"); - typeMap.put("enumeration","enumeration"); - typeMap.put("identityref","identityref"); - typeMap.put("union","union");*/ - typeMap.put("binary","binary"); - typeMap.put("boolean","boolean"); - typeMap.put("empty","empty"); - typeMap.put("instance-identifier","instance-identifier"); - typeMap.put("int8","int8"); - typeMap.put("int16","int16"); - typeMap.put("int32","int32"); - typeMap.put("int64","int64"); - typeMap.put("string","string"); - typeMap.put("uint8","uint8"); - typeMap.put("uint16","uint16"); - typeMap.put("uint32","uint32"); - typeMap.put("uint64","uint64"); - - - /* ietf-yang-types */ - - typeMap.put("counter32","yang:counter32"); - typeMap.put("zero-based-counter32","yang:zero-based-counter32"); - typeMap.put("counter64","yang:counter64"); - typeMap.put("zero-based-counter64","yang:zero-based-counter64"); - typeMap.put("gauge32","yang:gauge32"); - typeMap.put("gauge64","yang:gauge64"); - typeMap.put("object-identifier","yang:object-identifier"); - typeMap.put("object-identifier-128","yang:object-identifier-128"); - typeMap.put("yang-identifier","yang:yang-identifier"); - typeMap.put("date-and-time","yang:date-and-time"); - typeMap.put("timeticks","yang:timeticks"); - typeMap.put("timestamp","yang:timestamp"); - typeMap.put("phys-address","yang:phys-address"); - typeMap.put("mac-address","yang:mac-address"); - typeMap.put("xpath1.0","yang:xpath1.0"); - typeMap.put("hex-string","yang:hex-string"); - typeMap.put("uuid","yang:uuid"); - typeMap.put("dotted-quad","yang:dotted-quad"); - - /* ietf-inet-types */ - - typeMap.put("ip-version","inet:ip-version"); - typeMap.put("dscp","inet:dscp"); - typeMap.put("ipv6-flow-label","inet:ipv6-flow-label"); - typeMap.put("port-number","inet:port-number"); - typeMap.put("as-number","inet:as-number"); - typeMap.put("ip-address","inet:ip-address"); - typeMap.put("ipv4-address","inet:ipv4-address"); - typeMap.put("ipv6-address","inet:ipv6-address"); - typeMap.put("ip-address-no-zone","inet:ip-address-no-zone"); - typeMap.put("ipv4-address-no-zone","inet:ipv4-address-no-zone"); - typeMap.put("ipv6-address-no-zone","inet:ipv6-address-no-zone"); - typeMap.put("ip-prefix","inet:ip-prefix"); - typeMap.put("ipv4-prefix","inet:ipv4-prefix"); - typeMap.put("ipv6-prefix","inet:ipv6-prefix"); - typeMap.put("domain-name","inet:domain-name"); - typeMap.put("host","inet:host"); - typeMap.put("uri","inet:uri"); - - yangTypeMap = Collections.unmodifiableMap(typeMap); - } - - public static Map getYangTypeMap(){ - return yangTypeMap; - } - -} diff --git a/appc-sdc-listener/appc-yang-generator/src/test/java/org/onap/appc/TestYANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/test/java/org/onap/appc/TestYANGGenerator.java new file mode 100644 index 000000000..21130ee25 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/java/org/onap/appc/TestYANGGenerator.java @@ -0,0 +1,197 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import org.junit.*; +import org.junit.rules.TemporaryFolder; +import org.onap.appc.yang.YANGGenerator; +import org.onap.appc.yang.exception.YANGGenerationException; +import org.onap.appc.yang.impl.YANGGeneratorFactory; + +import java.io.*; + +/** + * The Class TestYANGGenerator - Junit Test Class for all related test cases. + */ +@Ignore +public class TestYANGGenerator { + + private YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator(); + private static String tosca; + private static String toscaWithSyntaxError; + private static String expectedYang; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + /** + * Run before test method. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Before + public void runBeforeTestMethod() throws IOException { + tosca= getFileContent("tosca/toscaFile.yml"); + toscaWithSyntaxError = getFileContent("tosca/toscaFileWithSyntaxError.yml"); + expectedYang = getFileContent("yang/expectedYang.yang"); + } + + /** + * Test YANG generator for success. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws YANGGenerationException the YANG generation exception + */ + @Test + public void TestYANGGeneratorForSuccess() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + Assert.assertNotNull(tosca); + Assert.assertFalse("tosca file is emply or blank", tosca.equals("")); + yangGenerator.generateYANG("ATD456", tosca, out); + out.flush(); + out.close(); + String generatedYang = getFileContent(tempFile); + Assert.assertEquals(expectedYang,generatedYang); + } + + @Test(expected = YANGGenerationException.class) + public void testYangGenerationForSyntaxError() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("ATD456",toscaWithSyntaxError,out); + } + + + /** + * Test for Yang Generator which generates YANG that is not matching with expected YANG. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws YANGGenerationException - the YANG generation exception + */ + @Test + public void unmatchedYangGenerationTest() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("112476", tosca, out); + out.flush(); + out.close(); + String generatedYang = getFileContent(tempFile); + Assert.assertNotSame(expectedYang, generatedYang); + + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForEmptyUniqueIDInput() throws IOException, YANGGenerationException { +// OutputStream out = new FileOutputStream(classLoader.getResource("yang/generatedYang.yang").getFile()); + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("", tosca, out); + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForUnSupportedType() throws IOException, YANGGenerationException { + tosca= getFileContent("tosca/toscaFileWithUnsupportedTypes.yml"); + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("", tosca, out); + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForEmptyToscaInput() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("1111", "", out); + } + + /** + * YANG generation test with invalid method arguments. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YANGGenerationTestWithInvalidMethodArguments() throws YANGGenerationException { + yangGenerator.generateYANG("112476", "ToscaSAMPLE", null); + } + + @Test(expected = YANGGenerationException.class) + public void YANGGenerationTestWithIOException() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + out.flush(); + out.close(); + yangGenerator.generateYANG("1111", tosca, out); + } + + + private String getFileContent(String fileName) throws IOException + { + ClassLoader classLoader = new TestYANGGenerator().getClass().getClassLoader(); + InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + + private String getFileContent(File file) throws IOException + { + InputStream is = new FileInputStream(file); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java deleted file mode 100644 index 21130ee25..000000000 --- a/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java +++ /dev/null @@ -1,197 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc; - -import org.junit.*; -import org.junit.rules.TemporaryFolder; -import org.onap.appc.yang.YANGGenerator; -import org.onap.appc.yang.exception.YANGGenerationException; -import org.onap.appc.yang.impl.YANGGeneratorFactory; - -import java.io.*; - -/** - * The Class TestYANGGenerator - Junit Test Class for all related test cases. - */ -@Ignore -public class TestYANGGenerator { - - private YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator(); - private static String tosca; - private static String toscaWithSyntaxError; - private static String expectedYang; - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - /** - * Run before test method. - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @Before - public void runBeforeTestMethod() throws IOException { - tosca= getFileContent("tosca/toscaFile.yml"); - toscaWithSyntaxError = getFileContent("tosca/toscaFileWithSyntaxError.yml"); - expectedYang = getFileContent("yang/expectedYang.yang"); - } - - /** - * Test YANG generator for success. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws YANGGenerationException the YANG generation exception - */ - @Test - public void TestYANGGeneratorForSuccess() throws IOException, YANGGenerationException { - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - Assert.assertNotNull(tosca); - Assert.assertFalse("tosca file is emply or blank", tosca.equals("")); - yangGenerator.generateYANG("ATD456", tosca, out); - out.flush(); - out.close(); - String generatedYang = getFileContent(tempFile); - Assert.assertEquals(expectedYang,generatedYang); - } - - @Test(expected = YANGGenerationException.class) - public void testYangGenerationForSyntaxError() throws IOException, YANGGenerationException { - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - yangGenerator.generateYANG("ATD456",toscaWithSyntaxError,out); - } - - - /** - * Test for Yang Generator which generates YANG that is not matching with expected YANG. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws YANGGenerationException - the YANG generation exception - */ - @Test - public void unmatchedYangGenerationTest() throws IOException, YANGGenerationException { - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - yangGenerator.generateYANG("112476", tosca, out); - out.flush(); - out.close(); - String generatedYang = getFileContent(tempFile); - Assert.assertNotSame(expectedYang, generatedYang); - - } - - /** - * Yang generation test for empty tosca input. - * - * @throws YANGGenerationException the YANG generation exception - */ - @Test(expected = YANGGenerationException.class) - public void YangGenerationTestForEmptyUniqueIDInput() throws IOException, YANGGenerationException { -// OutputStream out = new FileOutputStream(classLoader.getResource("yang/generatedYang.yang").getFile()); - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - yangGenerator.generateYANG("", tosca, out); - } - - /** - * Yang generation test for empty tosca input. - * - * @throws YANGGenerationException the YANG generation exception - */ - @Test(expected = YANGGenerationException.class) - public void YangGenerationTestForUnSupportedType() throws IOException, YANGGenerationException { - tosca= getFileContent("tosca/toscaFileWithUnsupportedTypes.yml"); - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - yangGenerator.generateYANG("", tosca, out); - } - - /** - * Yang generation test for empty tosca input. - * - * @throws YANGGenerationException the YANG generation exception - */ - @Test(expected = YANGGenerationException.class) - public void YangGenerationTestForEmptyToscaInput() throws IOException, YANGGenerationException { - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - yangGenerator.generateYANG("1111", "", out); - } - - /** - * YANG generation test with invalid method arguments. - * - * @throws YANGGenerationException the YANG generation exception - */ - @Test(expected = YANGGenerationException.class) - public void YANGGenerationTestWithInvalidMethodArguments() throws YANGGenerationException { - yangGenerator.generateYANG("112476", "ToscaSAMPLE", null); - } - - @Test(expected = YANGGenerationException.class) - public void YANGGenerationTestWithIOException() throws IOException, YANGGenerationException { - File tempFile = temporaryFolder.newFile("generatedYang.yang"); - OutputStream out = new FileOutputStream(tempFile); - out.flush(); - out.close(); - yangGenerator.generateYANG("1111", tosca, out); - } - - - private String getFileContent(String fileName) throws IOException - { - ClassLoader classLoader = new TestYANGGenerator().getClass().getClassLoader(); - InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } - - private String getFileContent(File file) throws IOException - { - InputStream is = new FileInputStream(file); - BufferedReader buf = new BufferedReader(new InputStreamReader(is)); - String line = buf.readLine(); - StringBuilder sb = new StringBuilder(); - - while (line != null) { - sb.append(line).append("\n"); - line = buf.readLine(); - } - String fileString = sb.toString(); - is.close(); - return fileString; - } - -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/SequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/SequenceGenerator.java new file mode 100644 index 000000000..709e4e31b --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/SequenceGenerator.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen; + + +import org.onap.appc.dg.objects.VnfcFlowModel; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.objects.SequenceGeneratorInput; +import org.onap.appc.seqgen.objects.Transaction; + +import java.util.List; +import java.util.Map; + +/** + * Sequence Generator API generates runtime sequence for LCM operations execution + */ +public interface SequenceGenerator { + /** + * + * @param input Sequence Generator Input containing request info, vnf capabilites and tunable parameters + * @return returns runtime sequence for LCM operation execution + * @throws APPCException + */ + List generateSequence(SequenceGeneratorInput input) throws APPCException; +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java new file mode 100644 index 000000000..26260d22f --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.dgplugin; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +public interface SequenceGeneratorPlugin extends SvcLogicJavaPlugin{ + + void generateSequence(Map params, SvcLogicContext context); +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java new file mode 100644 index 000000000..c0ea4134c --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java @@ -0,0 +1,243 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.dgplugin.impl; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.SequenceGenerator; +import org.onap.appc.seqgen.dgplugin.SequenceGeneratorPlugin; +import org.onap.appc.seqgen.impl.SequenceGeneratorFactory; +import org.onap.appc.seqgen.objects.Constants; +import org.onap.appc.seqgen.objects.SequenceGeneratorInput; +import org.onap.appc.seqgen.objects.Transaction; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.io.IOException; +import java.util.*; + +public class SequenceGeneratorPluginImpl implements SequenceGeneratorPlugin { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(SequenceGeneratorPluginImpl.class); + + @Override + public void generateSequence(Map params, SvcLogicContext context) { + ObjectMapper objectMapper = new ObjectMapper(); + String inputJSON = context.getAttribute("inputJSON"); + logger.debug("Input to Sequence Generator " + inputJSON); + try { + SequenceGeneratorInput sequenceGeneratorInput = buildSequenceGeneratorInput(inputJSON); + List sequence = generateSequence(sequenceGeneratorInput); + String output = objectMapper.writeValueAsString(sequence); + logger.debug("Sequence Generator Output " + output); + + context.setAttribute("output", output); + } catch (Exception e) { + logger.error("Error generating sequence", e); + context.setAttribute("error-code", "401"); + context.setAttribute("error-message", "Error generating sequence " + e.getMessage()); + } + } + + private SequenceGeneratorInput buildSequenceGeneratorInput(String inputJson) throws IOException, APPCException { + ObjectMapper objectMapper = new ObjectMapper(); + SequenceGeneratorInput sequenceGeneratorInput ; + objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); + sequenceGeneratorInput = objectMapper.readValue(inputJson, SequenceGeneratorInput.class); + + InventoryModel inventoryModel = buildInventoryModel(inputJson); + sequenceGeneratorInput.setInventoryModel(inventoryModel); + + VnfcDependencyModel dependencyModel = buildDependencyModel(inputJson); + sequenceGeneratorInput.setDependencyModel(dependencyModel); + + return sequenceGeneratorInput; + } + private List generateSequence(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { + if (sequenceGeneratorInput.getRequestInfo() == null) { + throw new APPCException("Request info is not provided in the input"); + } + String action = sequenceGeneratorInput.getRequestInfo().getAction(); + VNFOperation operation = VNFOperation.findByString(action); + if (operation == null) { + throw new APPCException("Invalid Action " + action); + } + SequenceGenerator sequenceGenerator = SequenceGeneratorFactory.getInstance().createSequenceGenerator(operation); + return sequenceGenerator.generateSequence(sequenceGeneratorInput); + } + + // Dependency model is an optional attribute and may contain null values + private VnfcDependencyModel buildDependencyModel(String inputJson) throws IOException, APPCException { + Set> dependency = new HashSet<>(); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); + JsonNode rootNode = objectMapper.readTree(inputJson); + JsonNode vnfcs = getVnfcsNode(rootNode); + if (vnfcs != null) { + for (JsonNode vnfcNode : vnfcs) { + String vnfcType = readVnfcType(vnfcNode); + String mandatory = readMandatory(vnfcNode); + String resilience = readResilience(vnfcNode); + Vnfc vnfc = new Vnfc(vnfcType, resilience, null, Boolean.parseBoolean(mandatory)); + Node currentNode = getNode(dependency, vnfcType); + if (currentNode == null) { + currentNode = new Node<>(vnfc); + dependency.add(currentNode); + } else { + currentNode.getChild().setMandatory(Boolean.valueOf(mandatory)); + currentNode.getChild().setResilienceType(resilience); + } + JsonNode parents = vnfcNode.get("parents"); + for (JsonNode parent : parents) { + String parentVnfcType = parent.asText(); + Node parentNode = getNode(dependency, parentVnfcType); + if (parentNode != null) { + currentNode.addParent(parentNode.getChild()); + } else { + Vnfc parentVnfc = new Vnfc(parentVnfcType, null, null, false); + parentNode = new Node<>(parentVnfc); + currentNode.addParent(parentVnfc); + dependency.add(parentNode); + } + } + + } + return new VnfcDependencyModel(dependency); + } + return null; + } + + private String readResilience(JsonNode vnfcNode) { + String resilience = null; + if (vnfcNode.get("resilience") != null) { + resilience = vnfcNode.get("resilience").asText(); + } + return resilience; + } + + private String readMandatory(JsonNode vnfcNode) { + String mandatory ; + JsonNode mandatoryNode = vnfcNode.get("mandatory"); + if (mandatoryNode == null) { + mandatory = "false"; + } else { + mandatory = mandatoryNode.asText(); + } + return mandatory; + } + + private String readVnfcType(JsonNode vnfcNode) throws APPCException { + JsonNode vnfcTypeNode = vnfcNode.get(Constants.VNFC_TYPE); + if (vnfcTypeNode == null) { + throw new APPCException("vnfc-type is not available in dependency info"); + } + return vnfcTypeNode.asText(); + } + + private JsonNode getVnfcsNode(JsonNode rootNode) { + JsonNode dependencyInfo = rootNode.get("dependency-info"); + JsonNode vnfcs = null; + if (dependencyInfo != null) { + vnfcs = dependencyInfo.get("vnfcs"); + } + return vnfcs; + } + + private Node getNode(Set> dependency, String vnfcType) { + for (Node node : dependency) { + if (node.getChild().getVnfcType().equals(vnfcType)) { + return node; + } + } + return null; + } + + private InventoryModel buildInventoryModel(String inputJson) throws IOException, APPCException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); + JsonNode jsonNode = objectMapper.readTree(inputJson); + JsonNode inventoryInfo = jsonNode.get("inventory-info"); + if (inventoryInfo == null) { + throw new APPCException("inventory-info is not provided in the input"); + } + JsonNode vnfInfo = inventoryInfo.get("vnf-info"); + if (vnfInfo == null) { + throw new APPCException("vnf-info is not provided in the input"); + } + + String vnfId = vnfInfo.get("vnf-id").asText(); + String vnfType = vnfInfo.get("vnf-type").asText(); + String vnfVersion = vnfInfo.get("vnf-version").asText(); + + Vnf vnf = new Vnf(vnfId, vnfType, vnfVersion); + + JsonNode vms = vnfInfo.get("vm"); + + Map> vfcs = new HashMap<>(); + for (JsonNode vm : vms) { + if(vm.get("vserver-id")== null){ + throw new APPCException("vserver-id not found "); + } + String vserverId = vm.get("vserver-id").asText(); + Vserver vserver = new Vserver(null, null, vserverId, null, null); + JsonNode vnfc = vm.get("vnfc"); + if (vnfc.get("vnfc-name") == null) { + throw new APPCException("vnfc-name not found for vserver " + vserverId); + } + String vnfcName = vnfc.get("vnfc-name").asText(); + if (vnfc.get("vnfc-type") == null) { + throw new APPCException("vnfc-type not found for vserver " + vserverId); + } + String vnfcType = vnfc.get("vnfc-type").asText(); + if (StringUtils.isEmpty(vnfcType)) { + throw new APPCException("vserver " + vserverId + " is not associated with any vnfc"); + } + Vnfc vfc = new Vnfc(vnfcType, null, vnfcName); + List vServers = vfcs.get(vfc); + if (vServers == null) { + vServers = new LinkedList<>(); + vfcs.put(vfc, vServers); + } + vServers.add(vserver); + } + + for (Map.Entry> entry : vfcs.entrySet()) { + Vnfc vnfc = entry.getKey(); + List vServers = vfcs.get(vnfc); + vnfc.addVms(vServers); + vnf.addVnfc(vnfc); + } + + return new InventoryModel(vnf); + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/SequenceGeneratorFactory.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/SequenceGeneratorFactory.java new file mode 100644 index 000000000..3c6a11962 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/SequenceGeneratorFactory.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; + +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.SequenceGenerator; + +public class SequenceGeneratorFactory { + + private static class ReferenceHolder { + private static SequenceGeneratorFactory instance = new SequenceGeneratorFactory(); + private ReferenceHolder(){ + + } + } + + private SequenceGeneratorFactory(){ + + } + + public static SequenceGeneratorFactory getInstance(){ + return ReferenceHolder.instance; + } + + public SequenceGenerator createSequenceGenerator(VNFOperation operation) throws APPCException { + switch (operation){ + case Start: + return new StartSequenceGenerator(); + case Stop: + return new StopSequenceGenerator(); + default: + throw new APPCException("Sequence Generator does not support operation " + operation.name()); + } + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StartSequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StartSequenceGenerator.java new file mode 100644 index 000000000..dcffaafd8 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StartSequenceGenerator.java @@ -0,0 +1,275 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.FlowStrategies; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.SequenceGenerator; +import org.onap.appc.seqgen.objects.*; + +import java.util.*; + +import static org.onap.appc.seqgen.objects.Constants.*; + +public class StartSequenceGenerator implements SequenceGenerator { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class); + + private List generateSequenceWithOutDependency(SequenceGeneratorInput input) throws APPCException { + + List transactionList = new LinkedList<>(); + Integer transactionId = 1; + List invVnfcList = input.getInventoryModel().getVnf().getVnfcs(); + boolean singleTransaction=checkSingleTransaction(invVnfcList); + for (Vnfc vnfc : invVnfcList) { + List vms = vnfc.getVserverList(); + List transactionIds = new LinkedList<>(); + for (Vserver vm : vms) { + Transaction transaction = new Transaction(); + transaction.setTransactionId(transactionId); + transactionIds.add(transactionId++); + transaction.setAction(Action.START.getActionType()); + transaction.setActionLevel(ActionLevel.VM.getAction()); + ActionIdentifier actionIdentifier = new ActionIdentifier(); + actionIdentifier.setvServerId(vm.getId()); + transaction.setActionIdentifier(actionIdentifier); + transaction.setPayload(input.getRequestInfo().getPayload()); + if(!singleTransaction){ + updateResponse(transaction); + } + + transactionList.add(transaction); + } + } + return transactionList; + } + + private boolean checkSingleTransaction(List invVnfcList) { + int vServerCount=0; + for(Vnfc vnfc : invVnfcList) { + List vms = vnfc.getVserverList(); + vServerCount=vServerCount+vms.size(); + } + return vServerCount <= 1; + } + + private void updateResponse(Transaction transaction) { + Response ignoreResponse = new Response(); + ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); + Map ignoreAction = new HashMap<>(); + ignoreAction.put(ResponseAction.IGNORE.getAction(), Boolean.TRUE.toString()); + ignoreResponse.setResponseAction(ignoreAction); + transaction.addResponse(ignoreResponse); + } + + private List generateSequenceWithDependencyModel(VnfcFlowModel flowModel, SequenceGeneratorInput input) throws APPCException { + Integer waitTime = readWaitTime(input); + Integer retryCount = readRetryCount(input); + List transactionList = new LinkedList<>(); + Integer transactionId = 1; + Iterator> itr = flowModel.getModelIterator(); + while (itr.hasNext()) { + List vnfcs = itr.next(); + for (Vnfc vnfc : vnfcs) { + List vms = vnfc.getVserverList(); + List transactionIds = new LinkedList<>(); + if(!vms.isEmpty()) { + for (Vserver vm : vms) { + Transaction transaction = new Transaction(); + transaction.setTransactionId(transactionId); + transactionIds.add(transactionId++); + transaction.setAction(Action.START.getActionType()); + transaction.setActionLevel(ActionLevel.VM.getAction()); + ActionIdentifier actionIdentifier = new ActionIdentifier(); + actionIdentifier.setvServerId(vm.getId()); + transaction.setActionIdentifier(actionIdentifier); + transaction.setPayload(input.getRequestInfo().getPayload()); + updateResponse(transaction); + transactionList.add(transaction); + } + boolean startApplicationSupported = readApplicationStartCapability(input); + if (startApplicationSupported) { + Transaction startAppTransaction = new Transaction(); + startAppTransaction.setTransactionId(transactionId++); + startAppTransaction.setAction(Action.START_APPLICATION.getActionType()); + startAppTransaction.setActionLevel(ActionLevel.VNFC.getAction()); + ActionIdentifier startActionIdentifier = new ActionIdentifier(); + startActionIdentifier.setVnfcName(vnfc.getVnfcName()); + startAppTransaction.setActionIdentifier(startActionIdentifier); + startAppTransaction.setPayload(input.getRequestInfo().getPayload()); + + List preCheckOptions = new LinkedList<>(); + for (Integer vmTransactionId : transactionIds) { + setPreCheckOptions(preCheckOptions, vmTransactionId); + } + startAppTransaction.setPreCheckOperator(PreCheckOperator.ANY.getOperator()); + startAppTransaction.setPrecheckOptions(preCheckOptions); + transactionList.add(startAppTransaction); + } + boolean healthCheckSupported = readHealthCheckCapabilites(input.getCapability()); + if (healthCheckSupported) { + Transaction healthCheckTransaction = new Transaction(); + healthCheckTransaction.setTransactionId(transactionId++); + healthCheckTransaction.setAction(Action.HEALTH_CHECK.getActionType()); + healthCheckTransaction.setActionLevel(ActionLevel.VNFC.getAction()); + ActionIdentifier healthCheckActionIdentifier = new ActionIdentifier(); + healthCheckActionIdentifier.setVnfcName(vnfc.getVnfcName()); + healthCheckTransaction.setActionIdentifier(healthCheckActionIdentifier); + healthCheckTransaction.setPayload(input.getRequestInfo().getPayload()); + + Response retryResponse = new Response(); + retryResponse.setResponseMessage(ResponseMessage.UNHEALTHY.getResponse()); + Map retryAction = new HashMap<>(); + retryAction.put(ResponseAction.RETRY.getAction(), retryCount.toString()); + retryAction.put(ResponseAction.WAIT.getAction(), waitTime.toString()); + retryResponse.setResponseAction(retryAction); + healthCheckTransaction.addResponse(retryResponse); + + Response healthyResponse = new Response(); + healthyResponse.setResponseMessage(ResponseMessage.HEALTHY.getResponse()); + Map healthyAction = new HashMap<>(); + healthyAction.put(ResponseAction.CONTINUE.getAction().toLowerCase(), Boolean.TRUE.toString()); + healthyResponse.setResponseAction(healthyAction); + healthCheckTransaction.addResponse(healthyResponse); + + Response failureResponse = new Response(); + failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); + Map failureResonseAction = new HashMap<>(); + failureResonseAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString()); + failureResponse.setResponseAction(failureResonseAction); + healthCheckTransaction.addResponse(failureResponse); + transactionList.add(healthCheckTransaction); + } + } + } + } + return transactionList; + } + + private void setPreCheckOptions(List preCheckOptions, Integer vmTransactionId) { + PreCheckOption option = new PreCheckOption(); + option.setPreTransactionId(vmTransactionId); + option.setParamName("status"); + option.setParamValue("success"); + preCheckOptions.add(option); + } + + @Override + public List generateSequence(SequenceGeneratorInput input) throws APPCException { + if(input.getRequestInfo().getActionLevel().equals(ActionLevel.VM.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VNFC.getAction())|| + input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VF_MODULE.getAction())) { + if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) { + FlowStrategies flowStrategy = readStartFlowStrategy(input); + VnfcFlowModel flowModel = buildFlowModel(input.getInventoryModel() + , input.getDependencyModel(), flowStrategy); + logger.debug("Flow Model " + flowModel); + return generateSequenceWithDependencyModel(flowModel, input); + } else { + logger.info("Generating sequence without dependency model"); + return generateSequenceWithOutDependency(input); + } + }throw new APPCException("Invalid action level "+input.getRequestInfo().getActionLevel()); + } + + private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException { + FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy); + if (flowBuilder == null) { + throw new APPCException("Flow Strategy not supported " + flowStrategy); + } + return flowBuilder.buildFlowModel(dependencyModel, inventoryModel); + } + + private FlowStrategies readStartFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { + Map tunableParams = sequenceGeneratorInput.getTunableParams(); + FlowStrategies strategy; + String strategyStr = null; + if (tunableParams != null) { + strategyStr = tunableParams.get(Constants.STRATEGY); + if (StringUtils.isBlank(strategyStr)) { + return FlowStrategies.FORWARD; + } + + strategy = FlowStrategies.findByString(strategyStr); + if (strategy != null) { + return strategy; + } + } + throw new APPCException("Invalid Strategy " + strategyStr); + } + + private boolean readHealthCheckCapabilites(Map> capabilities) { + if (capabilities != null) { + List vnfcCapabilities = capabilities.get(CapabilityLevel.VNFC.getLevel()); + if (vnfcCapabilities != null) + return vnfcCapabilities.stream() + .anyMatch(p -> Capabilties.HEALTH_CHECK.getCapability().equalsIgnoreCase(p)); + } + return false; + } + + private boolean readApplicationStartCapability(SequenceGeneratorInput input) { + Map> capability = input.getCapability(); + if (capability != null) { + List vnfcCapabilities = capability.get(CapabilityLevel.VNFC.getLevel()); + if (vnfcCapabilities != null) + return vnfcCapabilities.stream().anyMatch(p -> Capabilties.START_APPLICATION.getCapability().equalsIgnoreCase(p)); + } + return false; + } + + private Integer readRetryCount(SequenceGeneratorInput input) throws APPCException { + String paramValStr = input.getTunableParams().get(RETRY_COUNT); + if (StringUtils.isEmpty(paramValStr)) { + return RETRY_COUNT_VALUE; + } + try { + return Integer.parseInt(paramValStr); + } catch (NumberFormatException e) { + String message = "Invalid Number for Retry Count " + paramValStr; + logger.error(message, e); + throw new APPCException(message); + } + } + + private Integer readWaitTime(SequenceGeneratorInput input) throws APPCException { + String paramValStr = input.getTunableParams().get(WAIT_TIME); + if (StringUtils.isEmpty(paramValStr)) { + return WAIT_TIME_VALUE; + } + try { + return Integer.parseInt(paramValStr); + } catch (NumberFormatException e) { + String message = "Invalid Number for Wait Time " + paramValStr; + logger.error(message, e); + throw new APPCException(message); + } + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StopSequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StopSequenceGenerator.java new file mode 100644 index 000000000..77bee6b83 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StopSequenceGenerator.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.FlowStrategies; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.SequenceGenerator; +import org.onap.appc.seqgen.objects.*; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.*; + +import static org.onap.appc.seqgen.objects.Constants.*; + +public class StopSequenceGenerator implements SequenceGenerator { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class); + + @Override + public List generateSequence(SequenceGeneratorInput input) throws APPCException { + if(input.getRequestInfo().getActionLevel().equals(ActionLevel.VM.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VNFC.getAction())|| + input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VF_MODULE.getAction())) { + if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) { + FlowStrategies flowStrategy = readStopFlowStrategy(input); + VnfcFlowModel flowModel = buildFlowModel(input.getInventoryModel() + , input.getDependencyModel(), flowStrategy); + logger.debug("Flow Model " + flowModel); + return generateSequenceWithDependencyModel(flowModel, input); + } else { + logger.info("Generating sequence without dependency model"); + return generateSequenceWithOutDependency(input); + } + }throw new APPCException("Invalid action level "+input.getRequestInfo().getActionLevel()); + + } + private List generateSequenceWithOutDependency(SequenceGeneratorInput input){ + List transactionList = new LinkedList<>(); + Integer transactionId = 1; + List transactionIds = new LinkedList<>(); + List invVnfcList = input.getInventoryModel().getVnf().getVnfcs(); + boolean singleTransaction=checkSingleTransaction(invVnfcList); + for (Vnfc vnfc : invVnfcList) { + List vms = vnfc.getVserverList(); + for(Vserver vm:vms){ + Transaction transaction = new Transaction(); + transaction.setTransactionId(transactionId); + transactionIds.add(transactionId++); + transaction.setAction(Action.STOP.getActionType()); + transaction.setActionLevel(ActionLevel.VM.getAction()); + ActionIdentifier actionIdentifier = new ActionIdentifier(); + actionIdentifier.setvServerId(vm.getId()); + transaction.setActionIdentifier(actionIdentifier); + transaction.setPayload(input.getRequestInfo().getPayload()); + if(!singleTransaction){ + updateStopResponse(transaction); + } + transactionList.add(transaction); + } + } + return transactionList; + } + + private void updateStopResponse(Transaction transaction) { + Response failureResponse = new Response(); + failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); + Map failureAction = new HashMap<>(); + failureAction.put(ResponseAction.IGNORE.getAction(),Boolean.TRUE.toString()); + failureResponse.setResponseAction(failureAction); + transaction.addResponse(failureResponse); + } + private boolean checkSingleTransaction(List invVnfcList) { + int vServerCount=0; + for(Vnfc vnfc : invVnfcList) { + List vms = vnfc.getVserverList(); + vServerCount=vServerCount+vms.size(); + } + return vServerCount <= 1; + } + + private List generateSequenceWithDependencyModel(VnfcFlowModel flowModel,SequenceGeneratorInput input){ + List transactionList = new LinkedList<>(); + Integer transactionId = 1; + List transactionIds = new LinkedList<>(); + Iterator> itr = flowModel.getModelIterator(); + while (itr.hasNext()){ + List vnfcs = itr.next(); + for(Vnfc vnfc:vnfcs){ + boolean stopApplicationSupported = readApplicationStopCapability(input); + if(stopApplicationSupported && !vnfc.getVserverList().isEmpty()){ + Transaction stopAppTransaction = new Transaction(); + stopAppTransaction.setTransactionId(transactionId++); + stopAppTransaction.setAction(Action.STOP_APPLICATION.getActionType()); + stopAppTransaction.setActionLevel(ActionLevel.VNFC.getAction()); + ActionIdentifier stopActionIdentifier = new ActionIdentifier(); + stopActionIdentifier .setVnfcName(vnfc.getVnfcName()); + stopAppTransaction.setActionIdentifier(stopActionIdentifier ); + stopAppTransaction.setPayload(input.getRequestInfo().getPayload()); + updateStopResponse(stopAppTransaction); + transactionList.add(stopAppTransaction); + } + List vms = vnfc.getVserverList(); + for(Vserver vm:vms){ + Transaction transaction = new Transaction(); + transaction.setTransactionId(transactionId); + transactionIds.add(transactionId++); + transaction.setAction(Action.STOP.getActionType()); + transaction.setActionLevel(ActionLevel.VM.getAction()); + ActionIdentifier actionIdentifier = new ActionIdentifier(); + actionIdentifier.setvServerId(vm.getId()); + transaction.setActionIdentifier(actionIdentifier); + transaction.setPayload(input.getRequestInfo().getPayload()); + + updateStopResponse(transaction); + transactionList.add(transaction); + } + } + } + return transactionList; + } + + private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException { + FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy); + if (flowBuilder == null) { + throw new APPCException("Flow Strategy not supported " + flowStrategy); + } + return flowBuilder.buildFlowModel(dependencyModel, inventoryModel); + } + + private FlowStrategies readStopFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { + Map tunableParams = sequenceGeneratorInput.getTunableParams(); + FlowStrategies strategy; + String strategyStr = null; + if (tunableParams != null) { + strategyStr = tunableParams.get(Constants.STRATEGY); + if (StringUtils.isBlank(strategyStr)) { + return FlowStrategies.REVERSE; + } + strategy = FlowStrategies.findByString(strategyStr); + if (strategy != null) { + return strategy; + } + } + throw new APPCException("Invalid Strategy " + strategyStr); + } + private boolean readApplicationStopCapability(SequenceGeneratorInput input) { + Map> capability = input.getCapability(); + if(capability!= null){ + List vnfcCapabilities = capability.get(Constants.CapabilityLevel.VNFC.getLevel()); + if(vnfcCapabilities!=null) + return vnfcCapabilities.stream().anyMatch(p -> Capabilties.STOP_APPLICATION.getCapability().equalsIgnoreCase(p)); + } + return false; + } + + +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/ActionIdentifier.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/ActionIdentifier.java new file mode 100644 index 000000000..0703edf42 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/ActionIdentifier.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class ActionIdentifier { + + @JsonProperty("vnf-id") + private String vnfId; + + @JsonProperty("vnfc-name") + private String vnfcName; + + @JsonProperty("vserver-id") + private String vServerId; + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfcName() { + return vnfcName; + } + + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + public String getvServerId() { + return vServerId; + } + + public void setvServerId(String vServerId) { + this.vServerId = vServerId; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Constants.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Constants.java new file mode 100644 index 000000000..476c5b718 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Constants.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +public class Constants { + public static final String RETRY_COUNT = "retry-count"; + public static final String WAIT_TIME = "wait-time"; + public static final Integer WAIT_TIME_VALUE = 60; + public static final Integer RETRY_COUNT_VALUE = 4; + public static final String STRATEGY = "strategy"; + public static final String VNFC_TYPE = "vnfc-type"; + + public enum CapabilityLevel{ + VNF("vnf"),VNFC("vnfc"),VM("vm"); + private String level; + CapabilityLevel(String level) { + this.level=level; + } + + public String getLevel() { + return level; + } + } + + public enum Capabilties{ + START_APPLICATION("StartApplication"),HEALTH_CHECK("HealthCheck"),STOP_APPLICATION("StopApplication"); + private String capability; + + Capabilties(String capability) { + this.capability=capability; + } + public String getCapability(){ + return capability; + } + } + + public enum ResponseMessage{ + HEALTHY("healthy"),UNHEALTHY("unhealthy"),SUCCESS("success"),FAILURE("failure"); + + public String getResponse() { + return response; + } + + private String response; + ResponseMessage(String response){ + this.response=response; + } + + } + + public enum ResponseAction{ + STOP("stop"),RETRY("retry"),IGNORE("ignore"),WAIT("wait"),CONTINUE("Continue"); + + ResponseAction(String action) { + this.action=action; + } + + private String action; + + public String getAction() { + return action; + } + + } + + public enum Action{ + START("Start"),START_APPLICATION("StartApplication"),HEALTH_CHECK("HealthCheck"),STOP_APPLICATION("StopApplication"),STOP("Stop"); + + Action(String actionType) { + this.actionType=actionType; + } + + public String getActionType() { + return actionType; + } + + private String actionType; + + } + public enum ActionLevel{ + VM("vm"),VNFC("vnfc"),VNF("vnf"),VF_MODULE("vf-module"); + private String action; + ActionLevel(String action){ + this.action=action; + } + public String getAction() { + return action; + } + } + + public enum PreCheckOperator{ + ANY("any"),ALL("all"); + + PreCheckOperator(String operator){ + this.operator=operator; + } + + public String getOperator() { + return operator; + } + + private String operator; + + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/PreCheckOption.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/PreCheckOption.java new file mode 100644 index 000000000..00d079b00 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/PreCheckOption.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class PreCheckOption { + + @JsonProperty("pre-transactionID") + private Integer preTransactionId; + + @JsonProperty("param-name") + private String paramName; + + @JsonProperty("param-value") + private String paramValue; + + private String rule; + + + public Integer getPreTransactionId() { + return preTransactionId; + } + + public void setPreTransactionId(Integer preTransactionId) { + this.preTransactionId = preTransactionId; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public String getParamValue() { + return paramValue; + } + + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } + + public String getRule() { + return rule; + } + + public void setRule(String rule) { + this.rule = rule; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfo.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfo.java new file mode 100644 index 000000000..1704d274f --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfo.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class RequestInfo { + + private String action; + + @JsonProperty("action-level") + private String actionLevel; + + @JsonProperty("action-identifier") + private ActionIdentifier actionIdentifier; + + private String payload; + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getActionLevel() { + return actionLevel; + } + + public void setActionLevel(String actionLevel) { + this.actionLevel = actionLevel; + } + + public ActionIdentifier getActionIdentifier() { + return actionIdentifier; + } + + public void setActionIdentifier(ActionIdentifier actionIdentifier) { + this.actionIdentifier = actionIdentifier; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfoBuilder.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfoBuilder.java new file mode 100644 index 000000000..4fad00013 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/RequestInfoBuilder.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +public class RequestInfoBuilder { + + private String action; + + private String actionLevel; + + private ActionIdentifier actionIdentifier; + + private String payload; + + public RequestInfoBuilder actionIdentifier(){ + this.actionIdentifier = new ActionIdentifier(); + return this; + } + + public RequestInfoBuilder vnfId(String vnfId){ + this.actionIdentifier.setVnfId(vnfId); + return this; + } + + public RequestInfoBuilder vnfcName(String vnfcName){ + this.actionIdentifier.setVnfcName(vnfcName); + return this; + } + + public RequestInfoBuilder vServerId(String vServerId){ + this.actionIdentifier.setvServerId(vServerId); + return this; + } + + public RequestInfoBuilder action(String action){ + this.action = action; + return this; + } + + public RequestInfoBuilder actionLevel(String actionLevel){ + this.actionLevel = actionLevel; + return this; + } + + public RequestInfoBuilder payload(String payload){ + this.payload = payload; + return this; + } + + public RequestInfo build(){ + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setAction(this.action); + requestInfo.setActionIdentifier(this.actionIdentifier); + requestInfo.setActionLevel(this.actionLevel); + requestInfo.setPayload(this.payload); + return requestInfo; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Response.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Response.java new file mode 100644 index 000000000..ba3ccd400 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Response.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.Map; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class Response { + + @JsonProperty("response-code") + private String responseCode; + + @JsonProperty("response-message") + private String responseMessage; + + @JsonProperty("response-action") + private Map responseAction; + + public String getResponseCode() { + return responseCode; + } + + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + public Map getResponseAction() { + return responseAction; + } + + public void setResponseAction(Map responseAction) { + this.responseAction = responseAction; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInput.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInput.java new file mode 100644 index 000000000..d3f6a6d14 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInput.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Map; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class SequenceGeneratorInput { + + @NotNull + @JsonProperty("request-info") + private RequestInfo requestInfo; + + @JsonIgnore + private InventoryModel inventoryModel; + + @JsonIgnore + private VnfcDependencyModel dependencyModel; + + @JsonProperty("tunable-parameters") + private Map tunableParams; + + @JsonProperty("capabilities") + private Map> capability; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public InventoryModel getInventoryModel() { + return inventoryModel; + } + + public void setInventoryModel(InventoryModel inventoryModel) { + this.inventoryModel = inventoryModel; + } + + public VnfcDependencyModel getDependencyModel() { + return dependencyModel; + } + + public void setDependencyModel(VnfcDependencyModel dependencyModel) { + this.dependencyModel = dependencyModel; + } + + public Map getTunableParams() { + return tunableParams; + } + + public void setTunableParams(Map tunableParams) { + this.tunableParams = tunableParams; + } + + public Map> getCapability() { + return capability; + } + + public void setCapability(Map> capability) { + this.capability = capability; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInputBuilder.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInputBuilder.java new file mode 100644 index 000000000..66cb111b5 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/SequenceGeneratorInputBuilder.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SequenceGeneratorInputBuilder { + + private RequestInfo requestInfo; + + private InventoryModel inventoryModel; + + private VnfcDependencyModel dependencyModel; + + private Map tunableParams; + + private Map> capability; + + public SequenceGeneratorInputBuilder requestInfo(RequestInfo requestInfo){ + this.requestInfo = requestInfo; + return this; + } + + public SequenceGeneratorInputBuilder capability(String level,List capabilities){ + if(this.capability ==null){ + this.capability = new HashMap<>(); + } + this.capability.put(level,capabilities); + return this; + } + + public SequenceGeneratorInputBuilder tunableParameter(String key,String value){ + if(this.tunableParams ==null){ + this.tunableParams = new HashMap<>(); + } + this.tunableParams.put(key,value); + return this; + } + + public SequenceGeneratorInputBuilder inventoryModel(InventoryModel model){ + this.inventoryModel = model; + return this; + } + + public SequenceGeneratorInputBuilder dependendcyModel(VnfcDependencyModel model){ + this.dependencyModel = model; + return this; + } + + public SequenceGeneratorInput build(){ + SequenceGeneratorInput input = new SequenceGeneratorInput(); + input.setRequestInfo(this.requestInfo); + input.setCapability(this.capability); + input.setInventoryModel(this.inventoryModel); + input.setDependencyModel(this.dependencyModel); + input.setTunableParams(this.tunableParams); + return input; + } + + + +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Transaction.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Transaction.java new file mode 100644 index 000000000..ce45ec9e5 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/objects/Transaction.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class Transaction { + + @JsonProperty("transactionId") + private Integer transactionId; + + @JsonProperty("action") + private String action; + + @JsonProperty("action-level") + private String actionLevel; + + @JsonProperty("action-identifier") + private ActionIdentifier actionIdentifier; + + @JsonProperty("payload") + private String payload; + + @JsonProperty("parameters") + private Map parameters; + + @JsonProperty("precheck-operator") + private String preCheckOperator; + + + @JsonProperty("precheck-options") + private List precheckOptions; + + @JsonProperty("responses") + private List responses; + + public Transaction(){ + responses = new LinkedList<>(); + } + + public Integer getTransactionId() { + return transactionId; + } + + public void setTransactionId(Integer transactionId) { + this.transactionId = transactionId; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getActionLevel() { + return actionLevel; + } + + public void setActionLevel(String actionLevel) { + this.actionLevel = actionLevel; + } + + public ActionIdentifier getActionIdentifier() { + return actionIdentifier; + } + + public void setActionIdentifier(ActionIdentifier actionIdentifier) { + this.actionIdentifier = actionIdentifier; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + public List getResponses() { + return responses; + } + + public void setResponses(List responses) { + this.responses = responses; + } + + public void addResponse(Response response){ + this.responses.add(response); + } + + public String getPreCheckOperator() { + return preCheckOperator; + } + + public void setPreCheckOperator(String preCheckOperator) { + this.preCheckOperator = preCheckOperator; + } + + public List getPrecheckOptions() { + return precheckOptions; + } + + public void setPrecheckOptions(List precheckOptions) { + this.precheckOptions = precheckOptions; + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/provider/SequenceGeneratorProvider.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/provider/SequenceGeneratorProvider.java new file mode 100644 index 000000000..ad9a68705 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/provider/SequenceGeneratorProvider.java @@ -0,0 +1,352 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.provider; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.util.concurrent.Futures; +import org.apache.commons.lang.StringUtils; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.NotificationProviderService; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.SequenceGeneratorService; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.dependency.info.dependency.info.Vnfcs; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.inventory.info.inventory.info.vnf.info.Vm; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.StatusBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.Transactions; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.TransactionsBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.ActionIdentifier; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.*; +import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.responses.ResponseActionBuilder; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.seqgen.SequenceGenerator; +import org.onap.appc.seqgen.impl.SequenceGeneratorFactory; +import org.onap.appc.seqgen.objects.*; + +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + + +public class SequenceGeneratorProvider implements AutoCloseable,SequenceGeneratorService{ + protected DataBroker dataBroker; + protected RpcProviderRegistry rpcRegistry; + protected NotificationProviderService notificationService; + protected BindingAwareBroker.RpcRegistration rpcRegistration; + private final EELFLogger log = EELFManager.getInstance().getLogger(SequenceGeneratorProvider.class); + private final ExecutorService executor; + private final static String APP_NAME = "SequenceGeneratorProvider"; + + public SequenceGeneratorProvider(DataBroker dataBroker2, NotificationProviderService notificationProviderService + , RpcProviderRegistry rpcRegistry2) { + log.info("Creating provider for " + APP_NAME); + executor = Executors.newFixedThreadPool(1); + this.dataBroker = dataBroker2; + this.notificationService = notificationProviderService; + + this.rpcRegistry = rpcRegistry2; + + if (this.rpcRegistry != null) { + rpcRegistration = rpcRegistry.addRpcImplementation(SequenceGeneratorService.class, this); + } + log.info("Initialization complete for " + APP_NAME); + } + + @Override + public void close() throws Exception { + log.info("Closing provider for " + APP_NAME); + if(this.executor != null){ + executor.shutdown(); + } + if(this.rpcRegistration != null){ + rpcRegistration.close(); + } + log.info("Successfully closed provider for " + APP_NAME); + } + + @Override + public Future> generateSequence(GenerateSequenceInput input) { + RpcResult rpcResult=null; + log.debug("Received input = " + input ); + try { + SequenceGenerator seqGenerator = SequenceGeneratorFactory.getInstance() + .createSequenceGenerator(VNFOperation.findByString(input.getRequestInfo().getAction().name())); + SequenceGeneratorInput seqGenInput = buildSeqGenInput(input); + List transactions = seqGenerator.generateSequence(seqGenInput); + rpcResult = buildSuccessResponse(transactions); + } catch (APPCException e) { + log.error("Error Generating Sequence",e); + rpcResult = buildFailureResponse(e.getMessage()); + } + return Futures.immediateFuture(rpcResult); + } + + private RpcResult buildSuccessResponse(List transactions) { + + List transactionList = new LinkedList<>(); + for(Transaction transaction:transactions){ + ActionIdentifier actionIdentifier = null; + if(transaction.getActionIdentifier() != null){ + actionIdentifier = new ActionIdentifierBuilder() + .setVnfId(transaction.getActionIdentifier().getVnfId()) + .setVnfcName(transaction.getActionIdentifier().getVnfcName()) + .setVserverId(transaction.getActionIdentifier().getvServerId()) + .build(); + } + + List precheckOptions = new LinkedList<>(); + if(transaction.getPrecheckOptions()!=null){ + for(PreCheckOption option:transaction.getPrecheckOptions()){ + PrecheckOptions precheckOption = new PrecheckOptionsBuilder() + .setParamName(option.getParamName()) + .setParamValue(option.getParamValue()) + .setPreTransactionId(option.getPreTransactionId()) + .setRule(option.getRule()) + .build(); + precheckOptions.add(precheckOption); + } + } + + List responseList = getResponses(transaction); + + Transactions transactionObj + = new TransactionsBuilder() + .setActionIdentifier(actionIdentifier) + .setAction(transaction.getAction()) + .setActionLevel(transaction.getActionLevel()) + .setPrecheckOperator(transaction.getPreCheckOperator()) + .setPayload(transaction.getPayload()) + .setTransactionId(transaction.getTransactionId()) + .setPrecheckOptions(precheckOptions) + .setResponses(responseList) + .build(); + transactionList.add(transactionObj); + } + + GenerateSequenceOutputBuilder builder = new GenerateSequenceOutputBuilder() + .setTransactions(transactionList); + + return RpcResultBuilder + . status(true) + .withResult(builder.build()).build(); + } + + private List getResponses(Transaction transaction) { + List responseList = new LinkedList<>(); + for(Response resp : transaction.getResponses()){ + Map responseActions = resp.getResponseAction(); + ResponseActionBuilder responseActionBuilder = new ResponseActionBuilder(); + if(responseActions.get(Constants.ResponseAction.WAIT.getAction())!=null){ + responseActionBuilder = responseActionBuilder.setWait(Integer.parseInt(responseActions.get(Constants.ResponseAction.WAIT.getAction()))); + } + if(responseActions.get(Constants.ResponseAction.RETRY.getAction())!=null){ + responseActionBuilder = responseActionBuilder.setRetry(Integer.parseInt(responseActions.get(Constants.ResponseAction.RETRY.getAction()))); + } + if(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase())!=null){ + responseActionBuilder = responseActionBuilder + .setContinue(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase()))); + } + if(responseActions.get(Constants.ResponseAction.IGNORE.getAction()) !=null){ + responseActionBuilder = responseActionBuilder.setIgnore(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.IGNORE.getAction()))); + } + if(responseActions.get(Constants.ResponseAction.STOP.getAction()) !=null){ + responseActionBuilder = responseActionBuilder.setStop(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.STOP.getAction()))); + } + Responses response = new ResponsesBuilder() + .setResponseMessage(resp.getResponseMessage()) + .setResponseAction(responseActionBuilder.build()) + .build(); + responseList.add(response); + } + return responseList; + } + + private SequenceGeneratorInput buildSeqGenInput(GenerateSequenceInput input) throws APPCException { + + validateMandatory(input); + + RequestInfoBuilder requestInfobuilder = new RequestInfoBuilder() + .action(input.getRequestInfo().getAction().name()) + .actionLevel(input.getRequestInfo().getActionLevel().getName().toLowerCase()) + .payload(input.getRequestInfo().getPayload()); + + if(input.getRequestInfo().getActionIdentifier() !=null){ + requestInfobuilder = requestInfobuilder + .actionIdentifier() + .vnfId(input.getRequestInfo().getActionIdentifier().getVnfId()) + .vnfcName(input.getRequestInfo().getActionIdentifier().getVnfcName()) + .vServerId(input.getRequestInfo().getActionIdentifier().getVserverId()); + } + + RequestInfo requestInfo = requestInfobuilder.build(); + + InventoryModel inventoryModel = readInventoryModel(input); + + VnfcDependencyModel dependencyModel = readDependencyModel(input); + + SequenceGeneratorInputBuilder builder = new SequenceGeneratorInputBuilder() + .requestInfo(requestInfo) + .inventoryModel(inventoryModel) + .dependendcyModel(dependencyModel); + + if(input.getCapabilities() !=null){ + if(input.getCapabilities().getVnf()!=null){ + builder = builder.capability("vnf",input.getCapabilities().getVnf()); + } + if(input.getCapabilities().getVnfc()!=null){ + builder = builder.capability("vnfc",input.getCapabilities().getVnfc()); + } + if(input.getCapabilities().getVm()!=null){ + builder = builder.capability("vm",input.getCapabilities().getVm()); + } + if(input.getCapabilities().getVfModule()!=null){ + builder = builder.capability("vf-module",input.getCapabilities().getVfModule()); + } + } + + if(input.getTunableParameters() != null){ + builder = builder.tunableParameter(Constants.RETRY_COUNT,String.valueOf(input.getTunableParameters().getRetryCount())) + .tunableParameter(Constants.WAIT_TIME,String.valueOf(input.getTunableParameters().getWaitTime())); + if(input.getTunableParameters().getStrategy() !=null){ + builder = builder.tunableParameter(Constants.STRATEGY,input.getTunableParameters().getStrategy().name()); + } + } + return builder.build(); + } + + + private void validateMandatory(GenerateSequenceInput input) throws APPCException { + if(input.getRequestInfo() ==null){ + throw new APPCException("Request Info is not present in the request"); + } + if(input.getRequestInfo().getAction() ==null){ + throw new APPCException("Action is not present in the request"); + } + if(input.getInventoryInfo() ==null){ + throw new APPCException("inventoryInfo is not provided in the input"); + } + } + + private VnfcDependencyModel readDependencyModel(GenerateSequenceInput input) { + if(input.getDependencyInfo() == null || input.getDependencyInfo().getVnfcs() ==null || input.getDependencyInfo().getVnfcs().isEmpty()){ + return null; + } + List vnfcs = input.getDependencyInfo().getVnfcs(); + Set> dependencies = new HashSet<>(); + for(Vnfcs vnfcObj:vnfcs){ + org.onap.appc.domainmodel.Vnfc vnfc; + Node currentNode = readNode(vnfcObj.getVnfcType(),dependencies); + if(currentNode == null){ + vnfc = new org.onap.appc.domainmodel.Vnfc(vnfcObj.getVnfcType(),vnfcObj.getResilience()); + currentNode = new Node<>(vnfc); + dependencies.add(currentNode); + } + else{ + currentNode.getChild().setResilienceType(vnfcObj.getResilience()); + currentNode.getChild().setMandatory(vnfcObj.isMandatory()); + } + for(String parentVnfcType:vnfcObj.getParents()){ + Node parentNode = readNode(parentVnfcType,dependencies); + if(parentNode == null){ + org.onap.appc.domainmodel.Vnfc parentVnfc = new org.onap.appc.domainmodel.Vnfc(parentVnfcType,null); + parentNode = new Node<>(parentVnfc); + currentNode.addParent(parentVnfc); + dependencies.add(parentNode); + } + else{ + currentNode.addParent(parentNode.getChild()); + } + } + } + return new VnfcDependencyModel(dependencies); + } + + private Node readNode(String vnfcType, Set> dependencies) { + for(Node node : dependencies){ + if(node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)){ + return node; + } + } + return null; + } + + private InventoryModel readInventoryModel(GenerateSequenceInput input) throws APPCException { + if (input.getInventoryInfo().getVnfInfo()== null) { + throw new APPCException("vnfInfo is not provided in the input"); + } + + Vnf vnf = new Vnf(input.getInventoryInfo().getVnfInfo().getVnfId(), + input.getInventoryInfo().getVnfInfo().getVnfType(),null); + + Map> map = new HashMap<>(); + for(Vm vm:input.getInventoryInfo().getVnfInfo().getVm()){ + if(StringUtils.isBlank(vm.getVserverId())){ + throw new APPCException("vserver-id not found "); + } + if(StringUtils.isBlank(vm.getVnfc().getVnfcType())){ + throw new APPCException("vnfc-type not found for vserver " + vm.getVserverId()); + } + if(StringUtils.isBlank(vm.getVnfc().getVnfcName())){ + throw new APPCException("vnfc-name not found for vserver " + vm.getVserverId()); + } + + org.onap.appc.domainmodel.Vnfc vnfc = new org.onap.appc.domainmodel.Vnfc(vm.getVnfc().getVnfcType(),null,vm.getVnfc().getVnfcName()); + List vms = map.get(vnfc); + if(vms ==null){ + vms = new LinkedList<>(); + map.put(vnfc,vms); + } + vms.add(new Vserver(null,null,vm.getVserverId(),null,null)); + } + for(Map.Entry> entry:map.entrySet()){ + org.onap.appc.domainmodel.Vnfc vnfc = entry.getKey(); + List vmList = entry.getValue(); + vnfc.addVms(vmList); + vnf.addVnfc(vnfc); + } + return new InventoryModel(vnf); + } + + private RpcResult buildFailureResponse(String errorMessage){ + GenerateSequenceOutputBuilder sequenceGeneratorOutputBuilder=new GenerateSequenceOutputBuilder(); + StatusBuilder statusBuilder =new StatusBuilder(); + statusBuilder.setCode(401); + statusBuilder.setMessage(errorMessage); + sequenceGeneratorOutputBuilder.setStatus(statusBuilder.build()); + return RpcResultBuilder + . status(true) + .withResult(sequenceGeneratorOutputBuilder.build()) + .build(); + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java new file mode 100644 index 000000000..9de0289ea --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706; + +import org.onap.appc.seqgen.provider.SequenceGeneratorProvider; + +public class SequenceGeneratorModule extends org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.AbstractSequenceGeneratorModule { + public SequenceGeneratorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + super(identifier, dependencyResolver); + } + + public SequenceGeneratorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.SequenceGeneratorModule oldModule, java.lang.AutoCloseable oldInstance) { + super(identifier, dependencyResolver, oldModule, oldInstance); + } + + @Override + public void customValidation() { + // add custom validation form module attributes here. + } + + @Override + public java.lang.AutoCloseable createInstance() { + final SequenceGeneratorProvider provider = new SequenceGeneratorProvider(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); + return new AutoCloseable() { + + @Override + public void close() throws Exception { + provider.close(); + } + }; + } + +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java new file mode 100644 index 000000000..3ebd11b05 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/onap/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/* +* Generated file +* +* Generated from: yang module name: sequence-generator-impl yang module local name: sequence-generator-impl +* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator +* Generated at: Thu Aug 10 15:48:17 IST 2017 +* +* Do not modify this file unless it is present under src/main directory +*/ +package org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706; +public class SequenceGeneratorModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.AbstractSequenceGeneratorModuleFactory { + +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java deleted file mode 100644 index 9de0289ea..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModule.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706; - -import org.onap.appc.seqgen.provider.SequenceGeneratorProvider; - -public class SequenceGeneratorModule extends org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.AbstractSequenceGeneratorModule { - public SequenceGeneratorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public SequenceGeneratorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.SequenceGeneratorModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - final SequenceGeneratorProvider provider = new SequenceGeneratorProvider(getDataBrokerDependency(), getNotificationServiceDependency(), getRpcRegistryDependency()); - return new AutoCloseable() { - - @Override - public void close() throws Exception { - provider.close(); - } - }; - } - -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java deleted file mode 100644 index 3ebd11b05..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/opendaylight/yang/gen/v1/org/openecomp/appc/sequencegenerator/impl/rev170706/SequenceGeneratorModuleFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/* -* Generated file -* -* Generated from: yang module name: sequence-generator-impl yang module local name: sequence-generator-impl -* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator -* Generated at: Thu Aug 10 15:48:17 IST 2017 -* -* Do not modify this file unless it is present under src/main directory -*/ -package org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706; -public class SequenceGeneratorModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.impl.rev170706.AbstractSequenceGeneratorModuleFactory { - -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/SequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/SequenceGenerator.java deleted file mode 100644 index 709e4e31b..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/SequenceGenerator.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen; - - -import org.onap.appc.dg.objects.VnfcFlowModel; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.objects.SequenceGeneratorInput; -import org.onap.appc.seqgen.objects.Transaction; - -import java.util.List; -import java.util.Map; - -/** - * Sequence Generator API generates runtime sequence for LCM operations execution - */ -public interface SequenceGenerator { - /** - * - * @param input Sequence Generator Input containing request info, vnf capabilites and tunable parameters - * @return returns runtime sequence for LCM operation execution - * @throws APPCException - */ - List generateSequence(SequenceGeneratorInput input) throws APPCException; -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java deleted file mode 100644 index 26260d22f..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/SequenceGeneratorPlugin.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.dgplugin; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -public interface SequenceGeneratorPlugin extends SvcLogicJavaPlugin{ - - void generateSequence(Map params, SvcLogicContext context); -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java deleted file mode 100644 index c0ea4134c..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/dgplugin/impl/SequenceGeneratorPluginImpl.java +++ /dev/null @@ -1,243 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.dgplugin.impl; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.SequenceGenerator; -import org.onap.appc.seqgen.dgplugin.SequenceGeneratorPlugin; -import org.onap.appc.seqgen.impl.SequenceGeneratorFactory; -import org.onap.appc.seqgen.objects.Constants; -import org.onap.appc.seqgen.objects.SequenceGeneratorInput; -import org.onap.appc.seqgen.objects.Transaction; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.io.IOException; -import java.util.*; - -public class SequenceGeneratorPluginImpl implements SequenceGeneratorPlugin { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(SequenceGeneratorPluginImpl.class); - - @Override - public void generateSequence(Map params, SvcLogicContext context) { - ObjectMapper objectMapper = new ObjectMapper(); - String inputJSON = context.getAttribute("inputJSON"); - logger.debug("Input to Sequence Generator " + inputJSON); - try { - SequenceGeneratorInput sequenceGeneratorInput = buildSequenceGeneratorInput(inputJSON); - List sequence = generateSequence(sequenceGeneratorInput); - String output = objectMapper.writeValueAsString(sequence); - logger.debug("Sequence Generator Output " + output); - - context.setAttribute("output", output); - } catch (Exception e) { - logger.error("Error generating sequence", e); - context.setAttribute("error-code", "401"); - context.setAttribute("error-message", "Error generating sequence " + e.getMessage()); - } - } - - private SequenceGeneratorInput buildSequenceGeneratorInput(String inputJson) throws IOException, APPCException { - ObjectMapper objectMapper = new ObjectMapper(); - SequenceGeneratorInput sequenceGeneratorInput ; - objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - sequenceGeneratorInput = objectMapper.readValue(inputJson, SequenceGeneratorInput.class); - - InventoryModel inventoryModel = buildInventoryModel(inputJson); - sequenceGeneratorInput.setInventoryModel(inventoryModel); - - VnfcDependencyModel dependencyModel = buildDependencyModel(inputJson); - sequenceGeneratorInput.setDependencyModel(dependencyModel); - - return sequenceGeneratorInput; - } - private List generateSequence(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { - if (sequenceGeneratorInput.getRequestInfo() == null) { - throw new APPCException("Request info is not provided in the input"); - } - String action = sequenceGeneratorInput.getRequestInfo().getAction(); - VNFOperation operation = VNFOperation.findByString(action); - if (operation == null) { - throw new APPCException("Invalid Action " + action); - } - SequenceGenerator sequenceGenerator = SequenceGeneratorFactory.getInstance().createSequenceGenerator(operation); - return sequenceGenerator.generateSequence(sequenceGeneratorInput); - } - - // Dependency model is an optional attribute and may contain null values - private VnfcDependencyModel buildDependencyModel(String inputJson) throws IOException, APPCException { - Set> dependency = new HashSet<>(); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - JsonNode rootNode = objectMapper.readTree(inputJson); - JsonNode vnfcs = getVnfcsNode(rootNode); - if (vnfcs != null) { - for (JsonNode vnfcNode : vnfcs) { - String vnfcType = readVnfcType(vnfcNode); - String mandatory = readMandatory(vnfcNode); - String resilience = readResilience(vnfcNode); - Vnfc vnfc = new Vnfc(vnfcType, resilience, null, Boolean.parseBoolean(mandatory)); - Node currentNode = getNode(dependency, vnfcType); - if (currentNode == null) { - currentNode = new Node<>(vnfc); - dependency.add(currentNode); - } else { - currentNode.getChild().setMandatory(Boolean.valueOf(mandatory)); - currentNode.getChild().setResilienceType(resilience); - } - JsonNode parents = vnfcNode.get("parents"); - for (JsonNode parent : parents) { - String parentVnfcType = parent.asText(); - Node parentNode = getNode(dependency, parentVnfcType); - if (parentNode != null) { - currentNode.addParent(parentNode.getChild()); - } else { - Vnfc parentVnfc = new Vnfc(parentVnfcType, null, null, false); - parentNode = new Node<>(parentVnfc); - currentNode.addParent(parentVnfc); - dependency.add(parentNode); - } - } - - } - return new VnfcDependencyModel(dependency); - } - return null; - } - - private String readResilience(JsonNode vnfcNode) { - String resilience = null; - if (vnfcNode.get("resilience") != null) { - resilience = vnfcNode.get("resilience").asText(); - } - return resilience; - } - - private String readMandatory(JsonNode vnfcNode) { - String mandatory ; - JsonNode mandatoryNode = vnfcNode.get("mandatory"); - if (mandatoryNode == null) { - mandatory = "false"; - } else { - mandatory = mandatoryNode.asText(); - } - return mandatory; - } - - private String readVnfcType(JsonNode vnfcNode) throws APPCException { - JsonNode vnfcTypeNode = vnfcNode.get(Constants.VNFC_TYPE); - if (vnfcTypeNode == null) { - throw new APPCException("vnfc-type is not available in dependency info"); - } - return vnfcTypeNode.asText(); - } - - private JsonNode getVnfcsNode(JsonNode rootNode) { - JsonNode dependencyInfo = rootNode.get("dependency-info"); - JsonNode vnfcs = null; - if (dependencyInfo != null) { - vnfcs = dependencyInfo.get("vnfcs"); - } - return vnfcs; - } - - private Node getNode(Set> dependency, String vnfcType) { - for (Node node : dependency) { - if (node.getChild().getVnfcType().equals(vnfcType)) { - return node; - } - } - return null; - } - - private InventoryModel buildInventoryModel(String inputJson) throws IOException, APPCException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - JsonNode jsonNode = objectMapper.readTree(inputJson); - JsonNode inventoryInfo = jsonNode.get("inventory-info"); - if (inventoryInfo == null) { - throw new APPCException("inventory-info is not provided in the input"); - } - JsonNode vnfInfo = inventoryInfo.get("vnf-info"); - if (vnfInfo == null) { - throw new APPCException("vnf-info is not provided in the input"); - } - - String vnfId = vnfInfo.get("vnf-id").asText(); - String vnfType = vnfInfo.get("vnf-type").asText(); - String vnfVersion = vnfInfo.get("vnf-version").asText(); - - Vnf vnf = new Vnf(vnfId, vnfType, vnfVersion); - - JsonNode vms = vnfInfo.get("vm"); - - Map> vfcs = new HashMap<>(); - for (JsonNode vm : vms) { - if(vm.get("vserver-id")== null){ - throw new APPCException("vserver-id not found "); - } - String vserverId = vm.get("vserver-id").asText(); - Vserver vserver = new Vserver(null, null, vserverId, null, null); - JsonNode vnfc = vm.get("vnfc"); - if (vnfc.get("vnfc-name") == null) { - throw new APPCException("vnfc-name not found for vserver " + vserverId); - } - String vnfcName = vnfc.get("vnfc-name").asText(); - if (vnfc.get("vnfc-type") == null) { - throw new APPCException("vnfc-type not found for vserver " + vserverId); - } - String vnfcType = vnfc.get("vnfc-type").asText(); - if (StringUtils.isEmpty(vnfcType)) { - throw new APPCException("vserver " + vserverId + " is not associated with any vnfc"); - } - Vnfc vfc = new Vnfc(vnfcType, null, vnfcName); - List vServers = vfcs.get(vfc); - if (vServers == null) { - vServers = new LinkedList<>(); - vfcs.put(vfc, vServers); - } - vServers.add(vserver); - } - - for (Map.Entry> entry : vfcs.entrySet()) { - Vnfc vnfc = entry.getKey(); - List vServers = vfcs.get(vnfc); - vnfc.addVms(vServers); - vnf.addVnfc(vnfc); - } - - return new InventoryModel(vnf); - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/SequenceGeneratorFactory.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/SequenceGeneratorFactory.java deleted file mode 100644 index 3c6a11962..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/SequenceGeneratorFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; - -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.SequenceGenerator; - -public class SequenceGeneratorFactory { - - private static class ReferenceHolder { - private static SequenceGeneratorFactory instance = new SequenceGeneratorFactory(); - private ReferenceHolder(){ - - } - } - - private SequenceGeneratorFactory(){ - - } - - public static SequenceGeneratorFactory getInstance(){ - return ReferenceHolder.instance; - } - - public SequenceGenerator createSequenceGenerator(VNFOperation operation) throws APPCException { - switch (operation){ - case Start: - return new StartSequenceGenerator(); - case Stop: - return new StopSequenceGenerator(); - default: - throw new APPCException("Sequence Generator does not support operation " + operation.name()); - } - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StartSequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StartSequenceGenerator.java deleted file mode 100644 index dcffaafd8..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StartSequenceGenerator.java +++ /dev/null @@ -1,275 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.FlowStrategies; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.SequenceGenerator; -import org.onap.appc.seqgen.objects.*; - -import java.util.*; - -import static org.onap.appc.seqgen.objects.Constants.*; - -public class StartSequenceGenerator implements SequenceGenerator { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class); - - private List generateSequenceWithOutDependency(SequenceGeneratorInput input) throws APPCException { - - List transactionList = new LinkedList<>(); - Integer transactionId = 1; - List invVnfcList = input.getInventoryModel().getVnf().getVnfcs(); - boolean singleTransaction=checkSingleTransaction(invVnfcList); - for (Vnfc vnfc : invVnfcList) { - List vms = vnfc.getVserverList(); - List transactionIds = new LinkedList<>(); - for (Vserver vm : vms) { - Transaction transaction = new Transaction(); - transaction.setTransactionId(transactionId); - transactionIds.add(transactionId++); - transaction.setAction(Action.START.getActionType()); - transaction.setActionLevel(ActionLevel.VM.getAction()); - ActionIdentifier actionIdentifier = new ActionIdentifier(); - actionIdentifier.setvServerId(vm.getId()); - transaction.setActionIdentifier(actionIdentifier); - transaction.setPayload(input.getRequestInfo().getPayload()); - if(!singleTransaction){ - updateResponse(transaction); - } - - transactionList.add(transaction); - } - } - return transactionList; - } - - private boolean checkSingleTransaction(List invVnfcList) { - int vServerCount=0; - for(Vnfc vnfc : invVnfcList) { - List vms = vnfc.getVserverList(); - vServerCount=vServerCount+vms.size(); - } - return vServerCount <= 1; - } - - private void updateResponse(Transaction transaction) { - Response ignoreResponse = new Response(); - ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); - Map ignoreAction = new HashMap<>(); - ignoreAction.put(ResponseAction.IGNORE.getAction(), Boolean.TRUE.toString()); - ignoreResponse.setResponseAction(ignoreAction); - transaction.addResponse(ignoreResponse); - } - - private List generateSequenceWithDependencyModel(VnfcFlowModel flowModel, SequenceGeneratorInput input) throws APPCException { - Integer waitTime = readWaitTime(input); - Integer retryCount = readRetryCount(input); - List transactionList = new LinkedList<>(); - Integer transactionId = 1; - Iterator> itr = flowModel.getModelIterator(); - while (itr.hasNext()) { - List vnfcs = itr.next(); - for (Vnfc vnfc : vnfcs) { - List vms = vnfc.getVserverList(); - List transactionIds = new LinkedList<>(); - if(!vms.isEmpty()) { - for (Vserver vm : vms) { - Transaction transaction = new Transaction(); - transaction.setTransactionId(transactionId); - transactionIds.add(transactionId++); - transaction.setAction(Action.START.getActionType()); - transaction.setActionLevel(ActionLevel.VM.getAction()); - ActionIdentifier actionIdentifier = new ActionIdentifier(); - actionIdentifier.setvServerId(vm.getId()); - transaction.setActionIdentifier(actionIdentifier); - transaction.setPayload(input.getRequestInfo().getPayload()); - updateResponse(transaction); - transactionList.add(transaction); - } - boolean startApplicationSupported = readApplicationStartCapability(input); - if (startApplicationSupported) { - Transaction startAppTransaction = new Transaction(); - startAppTransaction.setTransactionId(transactionId++); - startAppTransaction.setAction(Action.START_APPLICATION.getActionType()); - startAppTransaction.setActionLevel(ActionLevel.VNFC.getAction()); - ActionIdentifier startActionIdentifier = new ActionIdentifier(); - startActionIdentifier.setVnfcName(vnfc.getVnfcName()); - startAppTransaction.setActionIdentifier(startActionIdentifier); - startAppTransaction.setPayload(input.getRequestInfo().getPayload()); - - List preCheckOptions = new LinkedList<>(); - for (Integer vmTransactionId : transactionIds) { - setPreCheckOptions(preCheckOptions, vmTransactionId); - } - startAppTransaction.setPreCheckOperator(PreCheckOperator.ANY.getOperator()); - startAppTransaction.setPrecheckOptions(preCheckOptions); - transactionList.add(startAppTransaction); - } - boolean healthCheckSupported = readHealthCheckCapabilites(input.getCapability()); - if (healthCheckSupported) { - Transaction healthCheckTransaction = new Transaction(); - healthCheckTransaction.setTransactionId(transactionId++); - healthCheckTransaction.setAction(Action.HEALTH_CHECK.getActionType()); - healthCheckTransaction.setActionLevel(ActionLevel.VNFC.getAction()); - ActionIdentifier healthCheckActionIdentifier = new ActionIdentifier(); - healthCheckActionIdentifier.setVnfcName(vnfc.getVnfcName()); - healthCheckTransaction.setActionIdentifier(healthCheckActionIdentifier); - healthCheckTransaction.setPayload(input.getRequestInfo().getPayload()); - - Response retryResponse = new Response(); - retryResponse.setResponseMessage(ResponseMessage.UNHEALTHY.getResponse()); - Map retryAction = new HashMap<>(); - retryAction.put(ResponseAction.RETRY.getAction(), retryCount.toString()); - retryAction.put(ResponseAction.WAIT.getAction(), waitTime.toString()); - retryResponse.setResponseAction(retryAction); - healthCheckTransaction.addResponse(retryResponse); - - Response healthyResponse = new Response(); - healthyResponse.setResponseMessage(ResponseMessage.HEALTHY.getResponse()); - Map healthyAction = new HashMap<>(); - healthyAction.put(ResponseAction.CONTINUE.getAction().toLowerCase(), Boolean.TRUE.toString()); - healthyResponse.setResponseAction(healthyAction); - healthCheckTransaction.addResponse(healthyResponse); - - Response failureResponse = new Response(); - failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); - Map failureResonseAction = new HashMap<>(); - failureResonseAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString()); - failureResponse.setResponseAction(failureResonseAction); - healthCheckTransaction.addResponse(failureResponse); - transactionList.add(healthCheckTransaction); - } - } - } - } - return transactionList; - } - - private void setPreCheckOptions(List preCheckOptions, Integer vmTransactionId) { - PreCheckOption option = new PreCheckOption(); - option.setPreTransactionId(vmTransactionId); - option.setParamName("status"); - option.setParamValue("success"); - preCheckOptions.add(option); - } - - @Override - public List generateSequence(SequenceGeneratorInput input) throws APPCException { - if(input.getRequestInfo().getActionLevel().equals(ActionLevel.VM.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VNFC.getAction())|| - input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VF_MODULE.getAction())) { - if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) { - FlowStrategies flowStrategy = readStartFlowStrategy(input); - VnfcFlowModel flowModel = buildFlowModel(input.getInventoryModel() - , input.getDependencyModel(), flowStrategy); - logger.debug("Flow Model " + flowModel); - return generateSequenceWithDependencyModel(flowModel, input); - } else { - logger.info("Generating sequence without dependency model"); - return generateSequenceWithOutDependency(input); - } - }throw new APPCException("Invalid action level "+input.getRequestInfo().getActionLevel()); - } - - private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException { - FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy); - if (flowBuilder == null) { - throw new APPCException("Flow Strategy not supported " + flowStrategy); - } - return flowBuilder.buildFlowModel(dependencyModel, inventoryModel); - } - - private FlowStrategies readStartFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { - Map tunableParams = sequenceGeneratorInput.getTunableParams(); - FlowStrategies strategy; - String strategyStr = null; - if (tunableParams != null) { - strategyStr = tunableParams.get(Constants.STRATEGY); - if (StringUtils.isBlank(strategyStr)) { - return FlowStrategies.FORWARD; - } - - strategy = FlowStrategies.findByString(strategyStr); - if (strategy != null) { - return strategy; - } - } - throw new APPCException("Invalid Strategy " + strategyStr); - } - - private boolean readHealthCheckCapabilites(Map> capabilities) { - if (capabilities != null) { - List vnfcCapabilities = capabilities.get(CapabilityLevel.VNFC.getLevel()); - if (vnfcCapabilities != null) - return vnfcCapabilities.stream() - .anyMatch(p -> Capabilties.HEALTH_CHECK.getCapability().equalsIgnoreCase(p)); - } - return false; - } - - private boolean readApplicationStartCapability(SequenceGeneratorInput input) { - Map> capability = input.getCapability(); - if (capability != null) { - List vnfcCapabilities = capability.get(CapabilityLevel.VNFC.getLevel()); - if (vnfcCapabilities != null) - return vnfcCapabilities.stream().anyMatch(p -> Capabilties.START_APPLICATION.getCapability().equalsIgnoreCase(p)); - } - return false; - } - - private Integer readRetryCount(SequenceGeneratorInput input) throws APPCException { - String paramValStr = input.getTunableParams().get(RETRY_COUNT); - if (StringUtils.isEmpty(paramValStr)) { - return RETRY_COUNT_VALUE; - } - try { - return Integer.parseInt(paramValStr); - } catch (NumberFormatException e) { - String message = "Invalid Number for Retry Count " + paramValStr; - logger.error(message, e); - throw new APPCException(message); - } - } - - private Integer readWaitTime(SequenceGeneratorInput input) throws APPCException { - String paramValStr = input.getTunableParams().get(WAIT_TIME); - if (StringUtils.isEmpty(paramValStr)) { - return WAIT_TIME_VALUE; - } - try { - return Integer.parseInt(paramValStr); - } catch (NumberFormatException e) { - String message = "Invalid Number for Wait Time " + paramValStr; - logger.error(message, e); - throw new APPCException(message); - } - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StopSequenceGenerator.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StopSequenceGenerator.java deleted file mode 100644 index 77bee6b83..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/impl/StopSequenceGenerator.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.impl; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.FlowStrategies; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.SequenceGenerator; -import org.onap.appc.seqgen.objects.*; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.*; - -import static org.onap.appc.seqgen.objects.Constants.*; - -public class StopSequenceGenerator implements SequenceGenerator { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class); - - @Override - public List generateSequence(SequenceGeneratorInput input) throws APPCException { - if(input.getRequestInfo().getActionLevel().equals(ActionLevel.VM.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VNFC.getAction())|| - input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction())||input.getRequestInfo().getActionLevel().equals(ActionLevel.VF_MODULE.getAction())) { - if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) { - FlowStrategies flowStrategy = readStopFlowStrategy(input); - VnfcFlowModel flowModel = buildFlowModel(input.getInventoryModel() - , input.getDependencyModel(), flowStrategy); - logger.debug("Flow Model " + flowModel); - return generateSequenceWithDependencyModel(flowModel, input); - } else { - logger.info("Generating sequence without dependency model"); - return generateSequenceWithOutDependency(input); - } - }throw new APPCException("Invalid action level "+input.getRequestInfo().getActionLevel()); - - } - private List generateSequenceWithOutDependency(SequenceGeneratorInput input){ - List transactionList = new LinkedList<>(); - Integer transactionId = 1; - List transactionIds = new LinkedList<>(); - List invVnfcList = input.getInventoryModel().getVnf().getVnfcs(); - boolean singleTransaction=checkSingleTransaction(invVnfcList); - for (Vnfc vnfc : invVnfcList) { - List vms = vnfc.getVserverList(); - for(Vserver vm:vms){ - Transaction transaction = new Transaction(); - transaction.setTransactionId(transactionId); - transactionIds.add(transactionId++); - transaction.setAction(Action.STOP.getActionType()); - transaction.setActionLevel(ActionLevel.VM.getAction()); - ActionIdentifier actionIdentifier = new ActionIdentifier(); - actionIdentifier.setvServerId(vm.getId()); - transaction.setActionIdentifier(actionIdentifier); - transaction.setPayload(input.getRequestInfo().getPayload()); - if(!singleTransaction){ - updateStopResponse(transaction); - } - transactionList.add(transaction); - } - } - return transactionList; - } - - private void updateStopResponse(Transaction transaction) { - Response failureResponse = new Response(); - failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse()); - Map failureAction = new HashMap<>(); - failureAction.put(ResponseAction.IGNORE.getAction(),Boolean.TRUE.toString()); - failureResponse.setResponseAction(failureAction); - transaction.addResponse(failureResponse); - } - private boolean checkSingleTransaction(List invVnfcList) { - int vServerCount=0; - for(Vnfc vnfc : invVnfcList) { - List vms = vnfc.getVserverList(); - vServerCount=vServerCount+vms.size(); - } - return vServerCount <= 1; - } - - private List generateSequenceWithDependencyModel(VnfcFlowModel flowModel,SequenceGeneratorInput input){ - List transactionList = new LinkedList<>(); - Integer transactionId = 1; - List transactionIds = new LinkedList<>(); - Iterator> itr = flowModel.getModelIterator(); - while (itr.hasNext()){ - List vnfcs = itr.next(); - for(Vnfc vnfc:vnfcs){ - boolean stopApplicationSupported = readApplicationStopCapability(input); - if(stopApplicationSupported && !vnfc.getVserverList().isEmpty()){ - Transaction stopAppTransaction = new Transaction(); - stopAppTransaction.setTransactionId(transactionId++); - stopAppTransaction.setAction(Action.STOP_APPLICATION.getActionType()); - stopAppTransaction.setActionLevel(ActionLevel.VNFC.getAction()); - ActionIdentifier stopActionIdentifier = new ActionIdentifier(); - stopActionIdentifier .setVnfcName(vnfc.getVnfcName()); - stopAppTransaction.setActionIdentifier(stopActionIdentifier ); - stopAppTransaction.setPayload(input.getRequestInfo().getPayload()); - updateStopResponse(stopAppTransaction); - transactionList.add(stopAppTransaction); - } - List vms = vnfc.getVserverList(); - for(Vserver vm:vms){ - Transaction transaction = new Transaction(); - transaction.setTransactionId(transactionId); - transactionIds.add(transactionId++); - transaction.setAction(Action.STOP.getActionType()); - transaction.setActionLevel(ActionLevel.VM.getAction()); - ActionIdentifier actionIdentifier = new ActionIdentifier(); - actionIdentifier.setvServerId(vm.getId()); - transaction.setActionIdentifier(actionIdentifier); - transaction.setPayload(input.getRequestInfo().getPayload()); - - updateStopResponse(transaction); - transactionList.add(transaction); - } - } - } - return transactionList; - } - - private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException { - FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy); - if (flowBuilder == null) { - throw new APPCException("Flow Strategy not supported " + flowStrategy); - } - return flowBuilder.buildFlowModel(dependencyModel, inventoryModel); - } - - private FlowStrategies readStopFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) throws APPCException { - Map tunableParams = sequenceGeneratorInput.getTunableParams(); - FlowStrategies strategy; - String strategyStr = null; - if (tunableParams != null) { - strategyStr = tunableParams.get(Constants.STRATEGY); - if (StringUtils.isBlank(strategyStr)) { - return FlowStrategies.REVERSE; - } - strategy = FlowStrategies.findByString(strategyStr); - if (strategy != null) { - return strategy; - } - } - throw new APPCException("Invalid Strategy " + strategyStr); - } - private boolean readApplicationStopCapability(SequenceGeneratorInput input) { - Map> capability = input.getCapability(); - if(capability!= null){ - List vnfcCapabilities = capability.get(Constants.CapabilityLevel.VNFC.getLevel()); - if(vnfcCapabilities!=null) - return vnfcCapabilities.stream().anyMatch(p -> Capabilties.STOP_APPLICATION.getCapability().equalsIgnoreCase(p)); - } - return false; - } - - -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/ActionIdentifier.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/ActionIdentifier.java deleted file mode 100644 index 0703edf42..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/ActionIdentifier.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class ActionIdentifier { - - @JsonProperty("vnf-id") - private String vnfId; - - @JsonProperty("vnfc-name") - private String vnfcName; - - @JsonProperty("vserver-id") - private String vServerId; - - public String getVnfId() { - return vnfId; - } - - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - public String getVnfcName() { - return vnfcName; - } - - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - public String getvServerId() { - return vServerId; - } - - public void setvServerId(String vServerId) { - this.vServerId = vServerId; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Constants.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Constants.java deleted file mode 100644 index 476c5b718..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Constants.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -public class Constants { - public static final String RETRY_COUNT = "retry-count"; - public static final String WAIT_TIME = "wait-time"; - public static final Integer WAIT_TIME_VALUE = 60; - public static final Integer RETRY_COUNT_VALUE = 4; - public static final String STRATEGY = "strategy"; - public static final String VNFC_TYPE = "vnfc-type"; - - public enum CapabilityLevel{ - VNF("vnf"),VNFC("vnfc"),VM("vm"); - private String level; - CapabilityLevel(String level) { - this.level=level; - } - - public String getLevel() { - return level; - } - } - - public enum Capabilties{ - START_APPLICATION("StartApplication"),HEALTH_CHECK("HealthCheck"),STOP_APPLICATION("StopApplication"); - private String capability; - - Capabilties(String capability) { - this.capability=capability; - } - public String getCapability(){ - return capability; - } - } - - public enum ResponseMessage{ - HEALTHY("healthy"),UNHEALTHY("unhealthy"),SUCCESS("success"),FAILURE("failure"); - - public String getResponse() { - return response; - } - - private String response; - ResponseMessage(String response){ - this.response=response; - } - - } - - public enum ResponseAction{ - STOP("stop"),RETRY("retry"),IGNORE("ignore"),WAIT("wait"),CONTINUE("Continue"); - - ResponseAction(String action) { - this.action=action; - } - - private String action; - - public String getAction() { - return action; - } - - } - - public enum Action{ - START("Start"),START_APPLICATION("StartApplication"),HEALTH_CHECK("HealthCheck"),STOP_APPLICATION("StopApplication"),STOP("Stop"); - - Action(String actionType) { - this.actionType=actionType; - } - - public String getActionType() { - return actionType; - } - - private String actionType; - - } - public enum ActionLevel{ - VM("vm"),VNFC("vnfc"),VNF("vnf"),VF_MODULE("vf-module"); - private String action; - ActionLevel(String action){ - this.action=action; - } - public String getAction() { - return action; - } - } - - public enum PreCheckOperator{ - ANY("any"),ALL("all"); - - PreCheckOperator(String operator){ - this.operator=operator; - } - - public String getOperator() { - return operator; - } - - private String operator; - - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/PreCheckOption.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/PreCheckOption.java deleted file mode 100644 index 00d079b00..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/PreCheckOption.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class PreCheckOption { - - @JsonProperty("pre-transactionID") - private Integer preTransactionId; - - @JsonProperty("param-name") - private String paramName; - - @JsonProperty("param-value") - private String paramValue; - - private String rule; - - - public Integer getPreTransactionId() { - return preTransactionId; - } - - public void setPreTransactionId(Integer preTransactionId) { - this.preTransactionId = preTransactionId; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public String getParamValue() { - return paramValue; - } - - public void setParamValue(String paramValue) { - this.paramValue = paramValue; - } - - public String getRule() { - return rule; - } - - public void setRule(String rule) { - this.rule = rule; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfo.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfo.java deleted file mode 100644 index 1704d274f..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfo.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class RequestInfo { - - private String action; - - @JsonProperty("action-level") - private String actionLevel; - - @JsonProperty("action-identifier") - private ActionIdentifier actionIdentifier; - - private String payload; - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getActionLevel() { - return actionLevel; - } - - public void setActionLevel(String actionLevel) { - this.actionLevel = actionLevel; - } - - public ActionIdentifier getActionIdentifier() { - return actionIdentifier; - } - - public void setActionIdentifier(ActionIdentifier actionIdentifier) { - this.actionIdentifier = actionIdentifier; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfoBuilder.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfoBuilder.java deleted file mode 100644 index 4fad00013..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/RequestInfoBuilder.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -public class RequestInfoBuilder { - - private String action; - - private String actionLevel; - - private ActionIdentifier actionIdentifier; - - private String payload; - - public RequestInfoBuilder actionIdentifier(){ - this.actionIdentifier = new ActionIdentifier(); - return this; - } - - public RequestInfoBuilder vnfId(String vnfId){ - this.actionIdentifier.setVnfId(vnfId); - return this; - } - - public RequestInfoBuilder vnfcName(String vnfcName){ - this.actionIdentifier.setVnfcName(vnfcName); - return this; - } - - public RequestInfoBuilder vServerId(String vServerId){ - this.actionIdentifier.setvServerId(vServerId); - return this; - } - - public RequestInfoBuilder action(String action){ - this.action = action; - return this; - } - - public RequestInfoBuilder actionLevel(String actionLevel){ - this.actionLevel = actionLevel; - return this; - } - - public RequestInfoBuilder payload(String payload){ - this.payload = payload; - return this; - } - - public RequestInfo build(){ - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setAction(this.action); - requestInfo.setActionIdentifier(this.actionIdentifier); - requestInfo.setActionLevel(this.actionLevel); - requestInfo.setPayload(this.payload); - return requestInfo; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Response.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Response.java deleted file mode 100644 index ba3ccd400..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Response.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.util.Map; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class Response { - - @JsonProperty("response-code") - private String responseCode; - - @JsonProperty("response-message") - private String responseMessage; - - @JsonProperty("response-action") - private Map responseAction; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getResponseMessage() { - return responseMessage; - } - - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } - - public Map getResponseAction() { - return responseAction; - } - - public void setResponseAction(Map responseAction) { - this.responseAction = responseAction; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInput.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInput.java deleted file mode 100644 index d3f6a6d14..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInput.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import javax.validation.constraints.NotNull; -import java.util.List; -import java.util.Map; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class SequenceGeneratorInput { - - @NotNull - @JsonProperty("request-info") - private RequestInfo requestInfo; - - @JsonIgnore - private InventoryModel inventoryModel; - - @JsonIgnore - private VnfcDependencyModel dependencyModel; - - @JsonProperty("tunable-parameters") - private Map tunableParams; - - @JsonProperty("capabilities") - private Map> capability; - - public RequestInfo getRequestInfo() { - return requestInfo; - } - - public void setRequestInfo(RequestInfo requestInfo) { - this.requestInfo = requestInfo; - } - - public InventoryModel getInventoryModel() { - return inventoryModel; - } - - public void setInventoryModel(InventoryModel inventoryModel) { - this.inventoryModel = inventoryModel; - } - - public VnfcDependencyModel getDependencyModel() { - return dependencyModel; - } - - public void setDependencyModel(VnfcDependencyModel dependencyModel) { - this.dependencyModel = dependencyModel; - } - - public Map getTunableParams() { - return tunableParams; - } - - public void setTunableParams(Map tunableParams) { - this.tunableParams = tunableParams; - } - - public Map> getCapability() { - return capability; - } - - public void setCapability(Map> capability) { - this.capability = capability; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInputBuilder.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInputBuilder.java deleted file mode 100644 index 66cb111b5..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/SequenceGeneratorInputBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class SequenceGeneratorInputBuilder { - - private RequestInfo requestInfo; - - private InventoryModel inventoryModel; - - private VnfcDependencyModel dependencyModel; - - private Map tunableParams; - - private Map> capability; - - public SequenceGeneratorInputBuilder requestInfo(RequestInfo requestInfo){ - this.requestInfo = requestInfo; - return this; - } - - public SequenceGeneratorInputBuilder capability(String level,List capabilities){ - if(this.capability ==null){ - this.capability = new HashMap<>(); - } - this.capability.put(level,capabilities); - return this; - } - - public SequenceGeneratorInputBuilder tunableParameter(String key,String value){ - if(this.tunableParams ==null){ - this.tunableParams = new HashMap<>(); - } - this.tunableParams.put(key,value); - return this; - } - - public SequenceGeneratorInputBuilder inventoryModel(InventoryModel model){ - this.inventoryModel = model; - return this; - } - - public SequenceGeneratorInputBuilder dependendcyModel(VnfcDependencyModel model){ - this.dependencyModel = model; - return this; - } - - public SequenceGeneratorInput build(){ - SequenceGeneratorInput input = new SequenceGeneratorInput(); - input.setRequestInfo(this.requestInfo); - input.setCapability(this.capability); - input.setInventoryModel(this.inventoryModel); - input.setDependencyModel(this.dependencyModel); - input.setTunableParams(this.tunableParams); - return input; - } - - - -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Transaction.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Transaction.java deleted file mode 100644 index ce45ec9e5..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/objects/Transaction.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class Transaction { - - @JsonProperty("transactionId") - private Integer transactionId; - - @JsonProperty("action") - private String action; - - @JsonProperty("action-level") - private String actionLevel; - - @JsonProperty("action-identifier") - private ActionIdentifier actionIdentifier; - - @JsonProperty("payload") - private String payload; - - @JsonProperty("parameters") - private Map parameters; - - @JsonProperty("precheck-operator") - private String preCheckOperator; - - - @JsonProperty("precheck-options") - private List precheckOptions; - - @JsonProperty("responses") - private List responses; - - public Transaction(){ - responses = new LinkedList<>(); - } - - public Integer getTransactionId() { - return transactionId; - } - - public void setTransactionId(Integer transactionId) { - this.transactionId = transactionId; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getActionLevel() { - return actionLevel; - } - - public void setActionLevel(String actionLevel) { - this.actionLevel = actionLevel; - } - - public ActionIdentifier getActionIdentifier() { - return actionIdentifier; - } - - public void setActionIdentifier(ActionIdentifier actionIdentifier) { - this.actionIdentifier = actionIdentifier; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public Map getParameters() { - return parameters; - } - - public void setParameters(Map parameters) { - this.parameters = parameters; - } - - public List getResponses() { - return responses; - } - - public void setResponses(List responses) { - this.responses = responses; - } - - public void addResponse(Response response){ - this.responses.add(response); - } - - public String getPreCheckOperator() { - return preCheckOperator; - } - - public void setPreCheckOperator(String preCheckOperator) { - this.preCheckOperator = preCheckOperator; - } - - public List getPrecheckOptions() { - return precheckOptions; - } - - public void setPrecheckOptions(List precheckOptions) { - this.precheckOptions = precheckOptions; - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/provider/SequenceGeneratorProvider.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/provider/SequenceGeneratorProvider.java deleted file mode 100644 index ad9a68705..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/openecomp/appc/seqgen/provider/SequenceGeneratorProvider.java +++ /dev/null @@ -1,352 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen.provider; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.util.concurrent.Futures; -import org.apache.commons.lang.StringUtils; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceInput; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutput; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.SequenceGeneratorService; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.dependency.info.dependency.info.Vnfcs; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.inventory.info.inventory.info.vnf.info.Vm; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.StatusBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.Transactions; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.TransactionsBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.ActionIdentifier; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.*; -import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.responses.ResponseActionBuilder; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.seqgen.SequenceGenerator; -import org.onap.appc.seqgen.impl.SequenceGeneratorFactory; -import org.onap.appc.seqgen.objects.*; - -import java.util.*; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - - -public class SequenceGeneratorProvider implements AutoCloseable,SequenceGeneratorService{ - protected DataBroker dataBroker; - protected RpcProviderRegistry rpcRegistry; - protected NotificationProviderService notificationService; - protected BindingAwareBroker.RpcRegistration rpcRegistration; - private final EELFLogger log = EELFManager.getInstance().getLogger(SequenceGeneratorProvider.class); - private final ExecutorService executor; - private final static String APP_NAME = "SequenceGeneratorProvider"; - - public SequenceGeneratorProvider(DataBroker dataBroker2, NotificationProviderService notificationProviderService - , RpcProviderRegistry rpcRegistry2) { - log.info("Creating provider for " + APP_NAME); - executor = Executors.newFixedThreadPool(1); - this.dataBroker = dataBroker2; - this.notificationService = notificationProviderService; - - this.rpcRegistry = rpcRegistry2; - - if (this.rpcRegistry != null) { - rpcRegistration = rpcRegistry.addRpcImplementation(SequenceGeneratorService.class, this); - } - log.info("Initialization complete for " + APP_NAME); - } - - @Override - public void close() throws Exception { - log.info("Closing provider for " + APP_NAME); - if(this.executor != null){ - executor.shutdown(); - } - if(this.rpcRegistration != null){ - rpcRegistration.close(); - } - log.info("Successfully closed provider for " + APP_NAME); - } - - @Override - public Future> generateSequence(GenerateSequenceInput input) { - RpcResult rpcResult=null; - log.debug("Received input = " + input ); - try { - SequenceGenerator seqGenerator = SequenceGeneratorFactory.getInstance() - .createSequenceGenerator(VNFOperation.findByString(input.getRequestInfo().getAction().name())); - SequenceGeneratorInput seqGenInput = buildSeqGenInput(input); - List transactions = seqGenerator.generateSequence(seqGenInput); - rpcResult = buildSuccessResponse(transactions); - } catch (APPCException e) { - log.error("Error Generating Sequence",e); - rpcResult = buildFailureResponse(e.getMessage()); - } - return Futures.immediateFuture(rpcResult); - } - - private RpcResult buildSuccessResponse(List transactions) { - - List transactionList = new LinkedList<>(); - for(Transaction transaction:transactions){ - ActionIdentifier actionIdentifier = null; - if(transaction.getActionIdentifier() != null){ - actionIdentifier = new ActionIdentifierBuilder() - .setVnfId(transaction.getActionIdentifier().getVnfId()) - .setVnfcName(transaction.getActionIdentifier().getVnfcName()) - .setVserverId(transaction.getActionIdentifier().getvServerId()) - .build(); - } - - List precheckOptions = new LinkedList<>(); - if(transaction.getPrecheckOptions()!=null){ - for(PreCheckOption option:transaction.getPrecheckOptions()){ - PrecheckOptions precheckOption = new PrecheckOptionsBuilder() - .setParamName(option.getParamName()) - .setParamValue(option.getParamValue()) - .setPreTransactionId(option.getPreTransactionId()) - .setRule(option.getRule()) - .build(); - precheckOptions.add(precheckOption); - } - } - - List responseList = getResponses(transaction); - - Transactions transactionObj - = new TransactionsBuilder() - .setActionIdentifier(actionIdentifier) - .setAction(transaction.getAction()) - .setActionLevel(transaction.getActionLevel()) - .setPrecheckOperator(transaction.getPreCheckOperator()) - .setPayload(transaction.getPayload()) - .setTransactionId(transaction.getTransactionId()) - .setPrecheckOptions(precheckOptions) - .setResponses(responseList) - .build(); - transactionList.add(transactionObj); - } - - GenerateSequenceOutputBuilder builder = new GenerateSequenceOutputBuilder() - .setTransactions(transactionList); - - return RpcResultBuilder - . status(true) - .withResult(builder.build()).build(); - } - - private List getResponses(Transaction transaction) { - List responseList = new LinkedList<>(); - for(Response resp : transaction.getResponses()){ - Map responseActions = resp.getResponseAction(); - ResponseActionBuilder responseActionBuilder = new ResponseActionBuilder(); - if(responseActions.get(Constants.ResponseAction.WAIT.getAction())!=null){ - responseActionBuilder = responseActionBuilder.setWait(Integer.parseInt(responseActions.get(Constants.ResponseAction.WAIT.getAction()))); - } - if(responseActions.get(Constants.ResponseAction.RETRY.getAction())!=null){ - responseActionBuilder = responseActionBuilder.setRetry(Integer.parseInt(responseActions.get(Constants.ResponseAction.RETRY.getAction()))); - } - if(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase())!=null){ - responseActionBuilder = responseActionBuilder - .setContinue(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase()))); - } - if(responseActions.get(Constants.ResponseAction.IGNORE.getAction()) !=null){ - responseActionBuilder = responseActionBuilder.setIgnore(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.IGNORE.getAction()))); - } - if(responseActions.get(Constants.ResponseAction.STOP.getAction()) !=null){ - responseActionBuilder = responseActionBuilder.setStop(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.STOP.getAction()))); - } - Responses response = new ResponsesBuilder() - .setResponseMessage(resp.getResponseMessage()) - .setResponseAction(responseActionBuilder.build()) - .build(); - responseList.add(response); - } - return responseList; - } - - private SequenceGeneratorInput buildSeqGenInput(GenerateSequenceInput input) throws APPCException { - - validateMandatory(input); - - RequestInfoBuilder requestInfobuilder = new RequestInfoBuilder() - .action(input.getRequestInfo().getAction().name()) - .actionLevel(input.getRequestInfo().getActionLevel().getName().toLowerCase()) - .payload(input.getRequestInfo().getPayload()); - - if(input.getRequestInfo().getActionIdentifier() !=null){ - requestInfobuilder = requestInfobuilder - .actionIdentifier() - .vnfId(input.getRequestInfo().getActionIdentifier().getVnfId()) - .vnfcName(input.getRequestInfo().getActionIdentifier().getVnfcName()) - .vServerId(input.getRequestInfo().getActionIdentifier().getVserverId()); - } - - RequestInfo requestInfo = requestInfobuilder.build(); - - InventoryModel inventoryModel = readInventoryModel(input); - - VnfcDependencyModel dependencyModel = readDependencyModel(input); - - SequenceGeneratorInputBuilder builder = new SequenceGeneratorInputBuilder() - .requestInfo(requestInfo) - .inventoryModel(inventoryModel) - .dependendcyModel(dependencyModel); - - if(input.getCapabilities() !=null){ - if(input.getCapabilities().getVnf()!=null){ - builder = builder.capability("vnf",input.getCapabilities().getVnf()); - } - if(input.getCapabilities().getVnfc()!=null){ - builder = builder.capability("vnfc",input.getCapabilities().getVnfc()); - } - if(input.getCapabilities().getVm()!=null){ - builder = builder.capability("vm",input.getCapabilities().getVm()); - } - if(input.getCapabilities().getVfModule()!=null){ - builder = builder.capability("vf-module",input.getCapabilities().getVfModule()); - } - } - - if(input.getTunableParameters() != null){ - builder = builder.tunableParameter(Constants.RETRY_COUNT,String.valueOf(input.getTunableParameters().getRetryCount())) - .tunableParameter(Constants.WAIT_TIME,String.valueOf(input.getTunableParameters().getWaitTime())); - if(input.getTunableParameters().getStrategy() !=null){ - builder = builder.tunableParameter(Constants.STRATEGY,input.getTunableParameters().getStrategy().name()); - } - } - return builder.build(); - } - - - private void validateMandatory(GenerateSequenceInput input) throws APPCException { - if(input.getRequestInfo() ==null){ - throw new APPCException("Request Info is not present in the request"); - } - if(input.getRequestInfo().getAction() ==null){ - throw new APPCException("Action is not present in the request"); - } - if(input.getInventoryInfo() ==null){ - throw new APPCException("inventoryInfo is not provided in the input"); - } - } - - private VnfcDependencyModel readDependencyModel(GenerateSequenceInput input) { - if(input.getDependencyInfo() == null || input.getDependencyInfo().getVnfcs() ==null || input.getDependencyInfo().getVnfcs().isEmpty()){ - return null; - } - List vnfcs = input.getDependencyInfo().getVnfcs(); - Set> dependencies = new HashSet<>(); - for(Vnfcs vnfcObj:vnfcs){ - org.onap.appc.domainmodel.Vnfc vnfc; - Node currentNode = readNode(vnfcObj.getVnfcType(),dependencies); - if(currentNode == null){ - vnfc = new org.onap.appc.domainmodel.Vnfc(vnfcObj.getVnfcType(),vnfcObj.getResilience()); - currentNode = new Node<>(vnfc); - dependencies.add(currentNode); - } - else{ - currentNode.getChild().setResilienceType(vnfcObj.getResilience()); - currentNode.getChild().setMandatory(vnfcObj.isMandatory()); - } - for(String parentVnfcType:vnfcObj.getParents()){ - Node parentNode = readNode(parentVnfcType,dependencies); - if(parentNode == null){ - org.onap.appc.domainmodel.Vnfc parentVnfc = new org.onap.appc.domainmodel.Vnfc(parentVnfcType,null); - parentNode = new Node<>(parentVnfc); - currentNode.addParent(parentVnfc); - dependencies.add(parentNode); - } - else{ - currentNode.addParent(parentNode.getChild()); - } - } - } - return new VnfcDependencyModel(dependencies); - } - - private Node readNode(String vnfcType, Set> dependencies) { - for(Node node : dependencies){ - if(node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)){ - return node; - } - } - return null; - } - - private InventoryModel readInventoryModel(GenerateSequenceInput input) throws APPCException { - if (input.getInventoryInfo().getVnfInfo()== null) { - throw new APPCException("vnfInfo is not provided in the input"); - } - - Vnf vnf = new Vnf(input.getInventoryInfo().getVnfInfo().getVnfId(), - input.getInventoryInfo().getVnfInfo().getVnfType(),null); - - Map> map = new HashMap<>(); - for(Vm vm:input.getInventoryInfo().getVnfInfo().getVm()){ - if(StringUtils.isBlank(vm.getVserverId())){ - throw new APPCException("vserver-id not found "); - } - if(StringUtils.isBlank(vm.getVnfc().getVnfcType())){ - throw new APPCException("vnfc-type not found for vserver " + vm.getVserverId()); - } - if(StringUtils.isBlank(vm.getVnfc().getVnfcName())){ - throw new APPCException("vnfc-name not found for vserver " + vm.getVserverId()); - } - - org.onap.appc.domainmodel.Vnfc vnfc = new org.onap.appc.domainmodel.Vnfc(vm.getVnfc().getVnfcType(),null,vm.getVnfc().getVnfcName()); - List vms = map.get(vnfc); - if(vms ==null){ - vms = new LinkedList<>(); - map.put(vnfc,vms); - } - vms.add(new Vserver(null,null,vm.getVserverId(),null,null)); - } - for(Map.Entry> entry:map.entrySet()){ - org.onap.appc.domainmodel.Vnfc vnfc = entry.getKey(); - List vmList = entry.getValue(); - vnfc.addVms(vmList); - vnf.addVnfc(vnfc); - } - return new InventoryModel(vnf); - } - - private RpcResult buildFailureResponse(String errorMessage){ - GenerateSequenceOutputBuilder sequenceGeneratorOutputBuilder=new GenerateSequenceOutputBuilder(); - StatusBuilder statusBuilder =new StatusBuilder(); - statusBuilder.setCode(401); - statusBuilder.setMessage(errorMessage); - sequenceGeneratorOutputBuilder.setStatus(statusBuilder.build()); - return RpcResultBuilder - . status(true) - .withResult(sequenceGeneratorOutputBuilder.build()) - .build(); - } -} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/onap/appc/seqgen/TestSequenceGeneratorPlugin.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/onap/appc/seqgen/TestSequenceGeneratorPlugin.java new file mode 100644 index 000000000..748773a21 --- /dev/null +++ b/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/onap/appc/seqgen/TestSequenceGeneratorPlugin.java @@ -0,0 +1,272 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.seqgen.dgplugin.SequenceGeneratorPlugin; +import org.onap.appc.seqgen.dgplugin.impl.SequenceGeneratorPluginImpl; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; + +public class TestSequenceGeneratorPlugin { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSequenceGeneratorPlugin.class); + + @Test + public void testGenerateSequenceStart() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/start.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/start.json"); + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + + + @Test + public void testGenerateSequenceSingleVM()throws URISyntaxException, IOException { + String inputJSON = readInput("/input/start-single-vm.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/start-single-vm.json"); + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceNoStrategy() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/no-strategy.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/start.json"); + + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceStop() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/stop.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/stop.json"); + + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceWrongNumber() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/wrongnumber.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String errorCode = context.getAttribute("error-code"); + String errorMessage = context.getAttribute("error-message"); + logger.debug("errorCode = " + errorCode); + Assert.assertEquals(errorCode,"401"); + Assert.assertEquals(errorMessage,"Error generating sequence Invalid Number for Wait Time 6a"); + } + + + @Test + public void testGenerateSequenceCyclic() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/cyclic.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String errorCode = context.getAttribute("error-code"); + String errorMessage = context.getAttribute("error-message"); + logger.debug("errorCode = " + errorCode); + Assert.assertEquals(errorCode,"401"); + Assert.assertEquals(errorMessage,"Error generating sequence There seems to be no Root/Independent node for Vnfc dependencies"); + } + + + @Test + public void testGenerateSequenceWrongAction() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/wrongaction.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String errorCode = context.getAttribute("error-code"); + String errorMessage = context.getAttribute("error-message"); + logger.debug("errorCode = " + errorCode); + Assert.assertEquals(errorCode,"401"); + Assert.assertEquals(errorMessage,"Error generating sequence Invalid Action start"); + } + + + @Test + public void testGenerateSequenceMissingRequestInfo() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/missingrequestinfo.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String errorCode = context.getAttribute("error-code"); + String errorMessage = context.getAttribute("error-message"); + logger.debug("errorCode = " + errorCode); + Assert.assertEquals(errorCode,"401"); + Assert.assertEquals(errorMessage,"Error generating sequence Request info is not provided in the input"); + } + + @Test + public void testGenerateSequenceStopSingleVM() throws URISyntaxException, IOException{ + String inputJSON = readInput("/input/stop-single-vm.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/stop-single-vm.json"); + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceStopSingleVmPerVnfc() throws URISyntaxException, IOException{ + String inputJSON = readInput("/input/stop-single-vm-per-vnfc.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/stop-single-vm-per-vnfc.json"); + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceStartSingleVmPerVnfc() throws URISyntaxException, IOException{ + String inputJSON = readInput("/input/start-single-vm-per-vnfc.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/start-single-vm-per-vnfc.json"); + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + @Test + public void testGenerateSequenceVnfcNotPresentInInventory() throws URISyntaxException, IOException { + String inputJSON = readInput("/input/CheckVNfcInInventory.json"); + + Map params = new HashMap<>(); + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("inputJSON",inputJSON); + SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); + plugin.generateSequence(params,context); + + String outputJSON = context.getAttribute("output"); + String actualOutput = readOutput("/output/CheckVnfcInInventory.json"); + + Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); + } + + private String readInput(String inputFile) throws URISyntaxException, IOException { + File file = new File(this.getClass().getResource(inputFile).toURI()); + + byte[] bFile = new byte[(int) file.length()]; + FileInputStream fileInputStream = new FileInputStream(file); + fileInputStream.read(bFile); + fileInputStream.close(); + return new String(bFile); + } + private String readOutput(String outputFile) throws IOException,URISyntaxException { + File file = new File(this.getClass().getResource(outputFile).toURI()); + + byte[] bFile = new byte[(int) file.length()]; + FileInputStream fileInputStream = new FileInputStream(file); + fileInputStream.read(bFile); + fileInputStream.close(); + + String output=new String(bFile); + int start=output.indexOf("["); + int last=output.length(); + return output.substring(start,last); + + } +} diff --git a/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/openecomp/appc/seqgen/TestSequenceGeneratorPlugin.java b/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/openecomp/appc/seqgen/TestSequenceGeneratorPlugin.java deleted file mode 100644 index 748773a21..000000000 --- a/appc-sequence-generator/appc-sequence-generator-bundle/src/test/java/org/openecomp/appc/seqgen/TestSequenceGeneratorPlugin.java +++ /dev/null @@ -1,272 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.appc.seqgen; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.seqgen.dgplugin.SequenceGeneratorPlugin; -import org.onap.appc.seqgen.dgplugin.impl.SequenceGeneratorPluginImpl; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; - -public class TestSequenceGeneratorPlugin { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestSequenceGeneratorPlugin.class); - - @Test - public void testGenerateSequenceStart() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/start.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/start.json"); - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - - - @Test - public void testGenerateSequenceSingleVM()throws URISyntaxException, IOException { - String inputJSON = readInput("/input/start-single-vm.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/start-single-vm.json"); - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceNoStrategy() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/no-strategy.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/start.json"); - - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceStop() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/stop.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/stop.json"); - - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceWrongNumber() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/wrongnumber.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String errorCode = context.getAttribute("error-code"); - String errorMessage = context.getAttribute("error-message"); - logger.debug("errorCode = " + errorCode); - Assert.assertEquals(errorCode,"401"); - Assert.assertEquals(errorMessage,"Error generating sequence Invalid Number for Wait Time 6a"); - } - - - @Test - public void testGenerateSequenceCyclic() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/cyclic.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String errorCode = context.getAttribute("error-code"); - String errorMessage = context.getAttribute("error-message"); - logger.debug("errorCode = " + errorCode); - Assert.assertEquals(errorCode,"401"); - Assert.assertEquals(errorMessage,"Error generating sequence There seems to be no Root/Independent node for Vnfc dependencies"); - } - - - @Test - public void testGenerateSequenceWrongAction() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/wrongaction.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String errorCode = context.getAttribute("error-code"); - String errorMessage = context.getAttribute("error-message"); - logger.debug("errorCode = " + errorCode); - Assert.assertEquals(errorCode,"401"); - Assert.assertEquals(errorMessage,"Error generating sequence Invalid Action start"); - } - - - @Test - public void testGenerateSequenceMissingRequestInfo() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/missingrequestinfo.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String errorCode = context.getAttribute("error-code"); - String errorMessage = context.getAttribute("error-message"); - logger.debug("errorCode = " + errorCode); - Assert.assertEquals(errorCode,"401"); - Assert.assertEquals(errorMessage,"Error generating sequence Request info is not provided in the input"); - } - - @Test - public void testGenerateSequenceStopSingleVM() throws URISyntaxException, IOException{ - String inputJSON = readInput("/input/stop-single-vm.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/stop-single-vm.json"); - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceStopSingleVmPerVnfc() throws URISyntaxException, IOException{ - String inputJSON = readInput("/input/stop-single-vm-per-vnfc.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/stop-single-vm-per-vnfc.json"); - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceStartSingleVmPerVnfc() throws URISyntaxException, IOException{ - String inputJSON = readInput("/input/start-single-vm-per-vnfc.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/start-single-vm-per-vnfc.json"); - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - @Test - public void testGenerateSequenceVnfcNotPresentInInventory() throws URISyntaxException, IOException { - String inputJSON = readInput("/input/CheckVNfcInInventory.json"); - - Map params = new HashMap<>(); - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("inputJSON",inputJSON); - SequenceGeneratorPlugin plugin = new SequenceGeneratorPluginImpl(); - plugin.generateSequence(params,context); - - String outputJSON = context.getAttribute("output"); - String actualOutput = readOutput("/output/CheckVnfcInInventory.json"); - - Assert.assertEquals(outputJSON.trim(),actualOutput.trim()); - } - - private String readInput(String inputFile) throws URISyntaxException, IOException { - File file = new File(this.getClass().getResource(inputFile).toURI()); - - byte[] bFile = new byte[(int) file.length()]; - FileInputStream fileInputStream = new FileInputStream(file); - fileInputStream.read(bFile); - fileInputStream.close(); - return new String(bFile); - } - private String readOutput(String outputFile) throws IOException,URISyntaxException { - File file = new File(this.getClass().getResource(outputFile).toURI()); - - byte[] bFile = new byte[(int) file.length()]; - FileInputStream fileInputStream = new FileInputStream(file); - fileInputStream.read(bFile); - fileInputStream.close(); - - String output=new String(bFile); - int start=output.indexOf("["); - int last=output.length(); - return output.substring(start,last); - - } -} -- cgit 1.2.3-korg