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 --- .../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 --- 308 files changed, 14734 insertions(+), 14734 deletions(-) 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 (limited to 'appc-dispatcher') 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 - -- cgit 1.2.3-korg