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 --- .../main/java/org/onap/appc/dg/aai/AAIPlugin.java | 46 ++ .../appc/dg/aai/exception/AAIQueryException.java | 32 + .../org/onap/appc/dg/aai/impl/AAIPluginImpl.java | 401 ++++++++++++ .../java/org/onap/appc/dg/aai/impl/Constants.java | 120 ++++ .../onap/appc/dg/aai/objects/AAIQueryResult.java | 52 ++ .../org/onap/appc/dg/aai/objects/Relationship.java | 69 +++ .../java/org/openecomp/appc/dg/aai/AAIPlugin.java | 46 -- .../appc/dg/aai/exception/AAIQueryException.java | 32 - .../openecomp/appc/dg/aai/impl/AAIPluginImpl.java | 401 ------------ .../org/openecomp/appc/dg/aai/impl/Constants.java | 120 ---- .../appc/dg/aai/objects/AAIQueryResult.java | 52 -- .../appc/dg/aai/objects/Relationship.java | 69 --- .../org/onap/appc/dg/aai/impl/AAIClientMock.java | 547 +++++++++++++++++ .../onap/appc/dg/aai/impl/AAIPluginImplTest.java | 259 ++++++++ .../openecomp/appc/dg/aai/impl/AAIClientMock.java | 547 ----------------- .../appc/dg/aai/impl/AAIPluginImplTest.java | 259 -------- .../onap/appc/dg/common/DCAEReporterPlugin.java | 37 ++ .../org/onap/appc/dg/common/DgResolverPlugin.java | 35 ++ .../appc/dg/common/IntermediateMessageSender.java | 51 ++ .../java/org/onap/appc/dg/common/JsonDgUtil.java | 54 ++ .../java/org/onap/appc/dg/common/LegacyUtil.java | 43 ++ .../onap/appc/dg/common/OutputMessagePlugin.java | 38 ++ .../onap/appc/dg/common/VNFCDgResolverPlugin.java | 37 ++ .../org/onap/appc/dg/common/VNFConfigurator.java | 46 ++ .../org/onap/appc/dg/common/VnfExecutionFlow.java | 34 + .../onap/appc/dg/common/impl/AbstractResolver.java | 117 ++++ .../dg/common/impl/AbstractResolverDataReader.java | 130 ++++ .../org/onap/appc/dg/common/impl/Constants.java | 99 +++ .../dg/common/impl/DCAEReporterPluginImpl.java | 168 +++++ .../appc/dg/common/impl/DgResolverPluginImpl.java | 71 +++ .../java/org/onap/appc/dg/common/impl/FlowKey.java | 62 ++ .../common/impl/IntermediateMessageSenderImpl.java | 172 ++++++ .../onap/appc/dg/common/impl/JsonDgUtilImpl.java | 199 ++++++ .../onap/appc/dg/common/impl/LegacyUtilImpl.java | 60 ++ .../dg/common/impl/OutputMessagePluginImpl.java | 73 +++ .../dg/common/impl/ResolverDataReaderFactory.java | 47 ++ .../onap/appc/dg/common/impl/ResolverFactory.java | 46 ++ .../dg/common/impl/VNFCDgResolverPluginImpl.java | 39 ++ .../org/onap/appc/dg/common/impl/VNFCResolver.java | 67 ++ .../dg/common/impl/VNFCResolverDataReader.java | 40 ++ .../appc/dg/common/impl/VNFConfiguratorImpl.java | 115 ++++ .../org/onap/appc/dg/common/impl/VNFResolver.java | 63 ++ .../appc/dg/common/impl/VNFResolverDataReader.java | 43 ++ .../appc/dg/common/impl/VnfExecutionFlowImpl.java | 271 ++++++++ .../appc/dg/common/objects/ConnectionDetails.java | 68 ++ .../org/onap/appc/dg/common/utils/JAXBUtil.java | 53 ++ .../org/onap/appc/dg/common/utils/JSONUtil.java | 83 +++ .../appc/dg/common/DCAEReporterPlugin.java | 37 -- .../openecomp/appc/dg/common/DgResolverPlugin.java | 35 -- .../appc/dg/common/IntermediateMessageSender.java | 51 -- .../org/openecomp/appc/dg/common/JsonDgUtil.java | 54 -- .../org/openecomp/appc/dg/common/LegacyUtil.java | 43 -- .../appc/dg/common/OutputMessagePlugin.java | 38 -- .../appc/dg/common/VNFCDgResolverPlugin.java | 37 -- .../openecomp/appc/dg/common/VNFConfigurator.java | 46 -- .../openecomp/appc/dg/common/VnfExecutionFlow.java | 34 - .../appc/dg/common/impl/AbstractResolver.java | 117 ---- .../dg/common/impl/AbstractResolverDataReader.java | 130 ---- .../openecomp/appc/dg/common/impl/Constants.java | 99 --- .../dg/common/impl/DCAEReporterPluginImpl.java | 168 ----- .../appc/dg/common/impl/DgResolverPluginImpl.java | 71 --- .../org/openecomp/appc/dg/common/impl/FlowKey.java | 62 -- .../common/impl/IntermediateMessageSenderImpl.java | 172 ------ .../appc/dg/common/impl/JsonDgUtilImpl.java | 199 ------ .../appc/dg/common/impl/LegacyUtilImpl.java | 60 -- .../dg/common/impl/OutputMessagePluginImpl.java | 73 --- .../dg/common/impl/ResolverDataReaderFactory.java | 47 -- .../appc/dg/common/impl/ResolverFactory.java | 46 -- .../dg/common/impl/VNFCDgResolverPluginImpl.java | 39 -- .../appc/dg/common/impl/VNFCResolver.java | 67 -- .../dg/common/impl/VNFCResolverDataReader.java | 40 -- .../appc/dg/common/impl/VNFConfiguratorImpl.java | 115 ---- .../openecomp/appc/dg/common/impl/VNFResolver.java | 63 -- .../appc/dg/common/impl/VNFResolverDataReader.java | 43 -- .../appc/dg/common/impl/VnfExecutionFlowImpl.java | 271 -------- .../appc/dg/common/objects/ConnectionDetails.java | 68 -- .../openecomp/appc/dg/common/utils/JAXBUtil.java | 53 -- .../openecomp/appc/dg/common/utils/JSONUtil.java | 83 --- .../resources/org/onap/appc/default.properties | 50 ++ .../org/openecomp/appc/default.properties | 50 -- .../dg/common/impl/DCAEReporterPluginImplTest.java | 119 ++++ .../onap/appc/dg/common/impl/EventSenderMock.java | 69 +++ .../appc/dg/common/impl/JsonDgUtilImplTest.java | 172 ++++++ .../dg/common/impl/TestVNFConfiguratorImpl.java | 108 ++++ .../dg/common/impl/TestVnfExecutionFlowImpl.java | 420 +++++++++++++ .../dg/common/impl/DCAEReporterPluginImplTest.java | 119 ---- .../appc/dg/common/impl/EventSenderMock.java | 69 --- .../appc/dg/common/impl/JsonDgUtilImplTest.java | 172 ------ .../dg/common/impl/TestVNFConfiguratorImpl.java | 108 ---- .../dg/common/impl/TestVnfExecutionFlowImpl.java | 420 ------------- .../dg/dependencymanager/DependencyManager.java | 36 ++ .../appc/dg/dependencymanager/DependencyType.java | 35 ++ .../exception/DependencyModelNotFound.java | 32 + .../helper/DependencyModelParser.java | 193 ++++++ .../impl/DependencyManagerImpl.java | 74 +++ .../impl/DependencyModelFactory.java | 40 ++ .../dependencymanager/impl/ResourceDependency.java | 86 +++ .../org/onap/appc/dg/flowbuilder/FlowBuilder.java | 34 + .../org/onap/appc/dg/flowbuilder/FlowStrategy.java | 35 ++ .../exception/InvalidDependencyModel.java | 32 + .../org/onap/appc/dg/flowbuilder/helper/Graph.java | 67 ++ .../dg/flowbuilder/impl/AbstractFlowStrategy.java | 136 ++++ .../dg/flowbuilder/impl/FlowBuilderFactory.java | 51 ++ .../appc/dg/flowbuilder/impl/FlowBuilderImpl.java | 52 ++ .../dg/flowbuilder/impl/ForwardFlowStrategy.java | 117 ++++ .../dg/flowbuilder/impl/ReverseFlowStrategy.java | 118 ++++ .../org/onap/appc/dg/objects/DependencyTypes.java | 39 ++ .../org/onap/appc/dg/objects/FlowStrategies.java | 39 ++ .../org/onap/appc/dg/objects/InventoryModel.java | 46 ++ .../main/java/org/onap/appc/dg/objects/Node.java | 77 +++ .../onap/appc/dg/objects/VnfcDependencyModel.java | 51 ++ .../org/onap/appc/dg/objects/VnfcFlowModel.java | 92 +++ .../dg/dependencymanager/DependencyManager.java | 36 -- .../appc/dg/dependencymanager/DependencyType.java | 35 -- .../exception/DependencyModelNotFound.java | 32 - .../helper/DependencyModelParser.java | 193 ------ .../impl/DependencyManagerImpl.java | 74 --- .../impl/DependencyModelFactory.java | 40 -- .../dependencymanager/impl/ResourceDependency.java | 86 --- .../openecomp/appc/dg/flowbuilder/FlowBuilder.java | 34 - .../appc/dg/flowbuilder/FlowStrategy.java | 35 -- .../exception/InvalidDependencyModel.java | 32 - .../appc/dg/flowbuilder/helper/Graph.java | 67 -- .../dg/flowbuilder/impl/AbstractFlowStrategy.java | 136 ---- .../dg/flowbuilder/impl/FlowBuilderFactory.java | 51 -- .../appc/dg/flowbuilder/impl/FlowBuilderImpl.java | 52 -- .../dg/flowbuilder/impl/ForwardFlowStrategy.java | 117 ---- .../dg/flowbuilder/impl/ReverseFlowStrategy.java | 118 ---- .../openecomp/appc/dg/objects/DependencyTypes.java | 39 -- .../openecomp/appc/dg/objects/FlowStrategies.java | 39 -- .../openecomp/appc/dg/objects/InventoryModel.java | 46 -- .../java/org/openecomp/appc/dg/objects/Node.java | 77 --- .../appc/dg/objects/VnfcDependencyModel.java | 51 -- .../openecomp/appc/dg/objects/VnfcFlowModel.java | 92 --- .../onap/appc/dg/flowbuilder/TestFlowBuilder.java | 332 ++++++++++ .../appc/dg/flowbuilder/TestFlowBuilder.java | 332 ---------- .../main/java/org/onap/appc/domainmodel/Vnf.java | 72 +++ .../main/java/org/onap/appc/domainmodel/Vnfc.java | 148 +++++ .../java/org/onap/appc/domainmodel/Vserver.java | 78 +++ .../java/org/openecomp/appc/domainmodel/Vnf.java | 72 --- .../java/org/openecomp/appc/domainmodel/Vnfc.java | 148 ----- .../org/openecomp/appc/domainmodel/Vserver.java | 78 --- .../onap/appc/dg/licmgr/LicenseManagerPlugin.java | 55 ++ .../dg/licmgr/impl/LicenseManagerPluginImpl.java | 148 +++++ .../appc/dg/licmgr/LicenseManagerPlugin.java | 55 -- .../dg/licmgr/impl/LicenseManagerPluginImpl.java | 148 ----- .../main/java/org/onap/appc/mdsal/MDSALStore.java | 65 ++ .../appc/mdsal/exception/MDSALStoreException.java | 72 +++ .../java/org/onap/appc/mdsal/impl/Constants.java | 125 ++++ .../onap/appc/mdsal/impl/MDSALStoreFactory.java | 50 ++ .../org/onap/appc/mdsal/impl/MDSALStoreImpl.java | 154 +++++ .../org/onap/appc/mdsal/objects/BundleInfo.java | 74 +++ .../onap/appc/mdsal/operation/ConfigOperation.java | 295 +++++++++ .../mdsal/operation/ConfigOperation.java~ccmerge | 295 +++++++++ .../operation/ConfigOperationRequestFormatter.java | 53 ++ .../java/org/openecomp/appc/mdsal/MDSALStore.java | 65 -- .../appc/mdsal/exception/MDSALStoreException.java | 72 --- .../org/openecomp/appc/mdsal/impl/Constants.java | 125 ---- .../appc/mdsal/impl/MDSALStoreFactory.java | 50 -- .../openecomp/appc/mdsal/impl/MDSALStoreImpl.java | 154 ----- .../openecomp/appc/mdsal/objects/BundleInfo.java | 74 --- .../appc/mdsal/operation/ConfigOperation.java | 295 --------- .../mdsal/operation/ConfigOperation.java~ccmerge | 295 --------- .../operation/ConfigOperationRequestFormatter.java | 53 -- .../onap/appc/dg/netconf/NetconfClientPlugin.java | 41 ++ .../org/onap/appc/dg/netconf/NetconfDBPlugin.java | 40 ++ .../dg/netconf/impl/NetconfClientPluginImpl.java | 314 ++++++++++ .../appc/dg/netconf/impl/NetconfDBPluginImpl.java | 123 ++++ .../appc/dg/netconf/NetconfClientPlugin.java | 41 -- .../openecomp/appc/dg/netconf/NetconfDBPlugin.java | 40 -- .../dg/netconf/impl/NetconfClientPluginImpl.java | 314 ---------- .../appc/dg/netconf/impl/NetconfDBPluginImpl.java | 123 ---- .../onap/appc/dg/netconf/impl/DAOServiceMock.java | 100 +++ .../impl/MockOperationalStateValidatorImpl.java | 64 ++ .../dg/netconf/impl/NetconfClientFactoryMock.java | 46 ++ .../dg/netconf/impl/NetconfClientJschMock.java | 103 ++++ .../netconf/impl/NetconfClientPluginImplTest.java | 681 +++++++++++++++++++++ .../dg/netconf/impl/NetconfDBPluginImplTest.java | 253 ++++++++ .../appc/dg/netconf/impl/ObjectMapperMock.java | 48 ++ .../impl/OperationStateValidatorFactoryMock.java | 50 ++ .../appc/dg/netconf/impl/DAOServiceMock.java | 100 --- .../impl/MockOperationalStateValidatorImpl.java | 64 -- .../dg/netconf/impl/NetconfClientFactoryMock.java | 46 -- .../dg/netconf/impl/NetconfClientJschMock.java | 103 ---- .../netconf/impl/NetconfClientPluginImplTest.java | 681 --------------------- .../dg/netconf/impl/NetconfDBPluginImplTest.java | 253 -------- .../appc/dg/netconf/impl/ObjectMapperMock.java | 48 -- .../impl/OperationStateValidatorFactoryMock.java | 50 -- .../java/org/onap/appc/dg/ssh/SshDBPlugin.java | 35 ++ .../main/java/org/onap/appc/dg/ssh/SshService.java | 102 +++ .../org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java | 85 +++ .../org/onap/appc/dg/ssh/impl/SshServiceImpl.java | 109 ++++ .../org/openecomp/appc/dg/ssh/SshDBPlugin.java | 35 -- .../java/org/openecomp/appc/dg/ssh/SshService.java | 102 --- .../appc/dg/ssh/impl/SshDBPluginImpl.java | 85 --- .../openecomp/appc/dg/ssh/impl/SshServiceImpl.java | 109 ---- .../onap/appc/dg/ssh/impl/SshServiceImplTest.java | 173 ++++++ .../appc/dg/ssh/impl/SshServiceImplTest.java | 173 ------ 198 files changed, 10790 insertions(+), 10790 deletions(-) create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge create mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge delete mode 100644 appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java create mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java delete mode 100644 appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java (limited to 'appc-dg') diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java new file mode 100644 index 000000000..64033dd38 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/AAIPlugin.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public interface AAIPlugin extends SvcLogicJavaPlugin { + void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; + + void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; + + void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; + + void getResource(Map params, SvcLogicContext ctx) throws APPCException; + + void postResource(Map params, SvcLogicContext ctx) throws APPCException; + + void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java new file mode 100644 index 000000000..2ec604dcd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/exception/AAIQueryException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.exception; + + +public class AAIQueryException extends Exception{ + public AAIQueryException(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java new file mode 100644 index 000000000..1b510a8ca --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/AAIPluginImpl.java @@ -0,0 +1,401 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.i18n.EELFResourceManager; + +import org.onap.appc.dg.aai.AAIPlugin; +import org.onap.appc.dg.aai.exception.AAIQueryException; +import org.onap.appc.dg.aai.objects.AAIQueryResult; +import org.onap.appc.dg.aai.objects.Relationship; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + + +public class AAIPluginImpl implements AAIPlugin { + private AAIClient aaiClient; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class); + + @SuppressWarnings("unchecked") + public AAIPluginImpl() { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(AAIService.class); + aaiClient = (AAIClient) bctx.getService(sref); + } + + @Override + public void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { + String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); + String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); + + String key = "vnf-id = '" + vnf_id + "'"; + + Map data = new HashMap<>(); + for (Map.Entry entry : params.entrySet()) { + String paramKey = entry.getKey(); + int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA); + if (pos == 0) { + data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue()); + } + } + + try { + SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + logger.info("AAIResponse: " + response.toString()); + if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + } catch (SvcLogicException e) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error(msg); + throw new APPCException(e); + } + } + + @Override + public void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { + String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); + String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); + + String key = "vnf-id = '" + vnf_id + "'"; + try { + SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); +// String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(msg); + } + String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); + if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; + String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); + if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; + + ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty())); + ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty())); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + logger.info("AAIResponse: " + response.toString()); + } catch (SvcLogicException e) { + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error(msg); + throw new APPCException(e); + } + } + + @Override + public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { + + Map> vnfcMap = new HashMap<>(); + String vnfType,vnfVersion; + String vnfId = params.get("resourceKey"); + AAIQueryResult vnfQueryResult; + int vmCount =0; + try { + vnfQueryResult = readVnf(vnfId); + + vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type"); + vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID); + + for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){ + if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){ + vmCount++; + String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id"); + String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id"); + String vmRelatedLink = vnfRelationship.getRelatedLink(); + String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name"); + String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner"); + String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id"); + + AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId); + String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink"); + + Vserver vm = new Vserver(vmURL,tenantId,vmId,vmRelatedLink,vmName); + for(Relationship vmRelation:vmQueryResult.getRelationshipList()){ + + if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){ + String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name"); + AAIQueryResult vnfcQueryResult = readVnfc(vnfcName); + String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type"); + + Vnfc vnfc = new Vnfc(vnfcType,null,vnfcName); + Set vmSet = vnfcMap.get(vnfc); + if(vmSet == null){ + vmSet = new HashSet<>(); + vnfcMap.put(vnfc,vmSet); + } + vmSet.add(vm); + } + } + } + } + ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount)); + } catch (AAIQueryException e) { + ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); + String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx + .getAttribute("getResource_result")); + logger.warn("Incorrect or Incomplete VNF Hierarchy"); + throw new APPCException("Error Retrieving VNF hierarchy"); + } + + Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); + for(Vnfc vnfc:vnfcMap.keySet()){ + for(Vserver vm:vnfcMap.get(vnfc)){ + vnfc.addVm(vm); + } + vnf.addVnfc(vnfc); + } + + populateContext(vnf,ctx); + ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + + } + + private void populateContext(Vnf vnf ,SvcLogicContext ctx) { + ctx.setAttribute("vnf.type",vnf.getVnfType()); + ctx.setAttribute("vnf.version",vnf.getVnfVersion()); + ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size())); + int vnfcCount =0; + for(Vnfc vnfc:vnf.getVnfcs()){ + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName()); + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType()); + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size())); + int vmCount =0; + for(Vserver vm:vnfc.getVserverList()){ + ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl()); + } + vnfcCount++; + } + } + + private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException { + String query = "vnfc.vnfc-name = '" + vnfcName + "'"; + String prefix = "VNFC"; + String resourceType = "vnfc"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + String[] additionalProperties = new String[]{"vnfc-type","vnfc-name", + "vnfc-function-code","in-maint","prov-status", + "is-closed-loop-disabled","orchestration-status","resource-version"}; + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) + throws AAIQueryException { + String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId + + "' AND cloud-region.cloud-owner = '" + cloudOwner + + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; + String prefix = "VM"; + String resourceType = "vserver"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + String[] additionalProperties = new String[]{"vserver-id","vserver-selflink", + "vserver-name","in-maint","prov-status","is-closed-loop-disabled", + "vserver-name2","resource-version",}; + + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readVnf(String vnfId) throws AAIQueryException { + String query = "generic-vnf.vnf-id = '" + vnfId + "'"; + String prefix = "VNF"; + String resourceType = "generic-vnf"; + SvcLogicContext vnfContext = readResource(query,prefix,resourceType); + + String[] additionalProperties = new String[]{"vnf-type","vnf-name", + "in-maint","prov-status","heat-stack-id", + "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID}; + + return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); + } + + private AAIQueryResult readRelationDataAndProperties(String prefix, + SvcLogicContext context, + String[] additionalProperties) { + AAIQueryResult result = new AAIQueryResult(); + + if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) { + Integer relationsCount = Integer.parseInt(context.getAttribute( + prefix + ".relationship-list.relationship_length")); + for (int i = 0; i < relationsCount; i++) { + String rsKey = prefix + ".relationship-list.relationship[" + i + "]"; + Relationship relationShip = new Relationship(); + relationShip.setRelatedLink(context.getAttribute(rsKey + ".related-link")); + relationShip.setRelatedTo(context.getAttribute(rsKey + ".related-to")); + Integer relationDataCount = + Integer.parseInt(context.getAttribute(rsKey + ".relationship-data_length")); + for (int j = 0; j < relationDataCount; j++) { + String rsDataKey = rsKey + ".relationship-data[" + j + "]"; + String key = context.getAttribute(rsDataKey + ".relationship-key"); + String value = context.getAttribute(rsDataKey + ".relationship-value"); + relationShip.getRelationShipDataMap().put(key, value); + } + Integer relatedPropertyCount = 0; + String relatedPropertyCountStr = null; + try { + relatedPropertyCountStr = context.getAttribute(rsKey + ".related-to-property_length"); + relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr); + } catch (NumberFormatException e) { + logger.debug( + "Invalid value in the context for Related Property Count " + relatedPropertyCountStr); + } + + for (int j = 0; j < relatedPropertyCount; j++) { + String rsPropKey = rsKey + ".related-to-property[" + j + "]"; + String key = context.getAttribute(rsPropKey + ".property-key"); + String value = context.getAttribute(rsPropKey + ".property-value"); + relationShip.getRelatedProperties().put(key, value); + } + result.getRelationshipList().add(relationShip); + } + } else { + logger.error("Relationship-list not present in the SvcLogicContext attributes set." + + (context == null ? "" : "Attribute KeySet = "+ context.getAttributeKeySet())); + } + + if (context != null) { + for (String key : additionalProperties) { + result.getAdditionProperties().put(key, context.getAttribute(prefix + "." + key)); + } + } + return result; + } + + private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException { + SvcLogicContext resourceContext = new SvcLogicContext(); + try { + SvcLogicResource.QueryStatus response = + aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); + logger.info("AAIResponse: " + response.toString()); + if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ + throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); + } + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage())); + throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); + } + return resourceContext; + } + + @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"); + if (logger.isDebugEnabled()) { + logger.debug("inside getResorce"); + logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); + } + try { + SvcLogicResource.QueryStatus response = + aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("getResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error( + EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting getResource======"); + } + } + + @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = + params.get("resourceKey"), att_name = params.get("attributeName"), att_value = + params.get("attributeValue"); + if (logger.isDebugEnabled()) { + logger.debug("inside postResource"); + logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); + logger.debug("Updating " + att_name + " to : " + att_value); + } + Map data = new HashMap<>(); + data.put(att_name, att_value); + + try { + SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("postResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting postResource======"); + } + } + + @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { + String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); + + if (logger.isDebugEnabled()) { + logger.debug("inside deleteResource"); + logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); + } + try { + SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx); + logger.info("AAIResponse: " + response.toString()); + ctx.setAttribute("deleteResource_result", response.toString()); + } catch (SvcLogicException e) { + logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); + } + if (logger.isDebugEnabled()) { + logger.debug("exiting deleteResource======"); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java new file mode 100644 index 000000000..6a6818e06 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/impl/Constants.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + + +public class Constants { + public final static String VNF_ID_PARAM_NAME = "aai.vnfID"; + public static final String AAI_PREFIX_PARAM_NAME = "aai.prefix"; + public static final String AAI_INPUT_DATA = "aai.input.data"; + public static final String AAI_ERROR_MESSAGE = "org.onap.appc.dg.error"; + + public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; + public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; + public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; + public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; + + public static final String CONTROLLER_IP = "127.0.0.1"; + public static final int CONTROLLER_PORT = 8181; + public static final String PROTOCOL = "http"; + + public static final String VF_LICENSE = "VF_LICENSE"; + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String SDNCTL_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + public static final String SDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; + + // input fields names + public static final String PAYLOAD = "payload"; + + // constants fo DG + public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; + public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; + public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; + public static final String TARGET_VNF_TYPE = "target-vnf-type"; + public static final String FILE_CONTENT_FIELD_NAME = "file-content"; + public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; + public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String UPGRADE_VERSION = "upgrade-version"; + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String RESOURCEKEY = "resourceKey"; + public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; + public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; + public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; + public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; + public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; + public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; + public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; + public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; + + public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; + public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; + public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; + public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; + public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; + public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; + + /** + * AAI property names + */ + public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id"; + + public enum SDC_ARTIFACTS_FIELDS { + SERVICE_UUID, + DISTRIBUTION_ID, + SERVICE_NAME, + SERVICE_DESCRIPTION, + RESOURCE_UUID, + RESOURCE_INSTANCE_NAME, + RESOURCE_NAME, + RESOURCE_VERSION, + RESOURCE_TYPE, + ARTIFACT_UUID, + ARTIFACT_TYPE, + ARTIFACT_VERSION, + ARTIFACT_DESCRIPTION, + INTERNAL_VERSION, + CREATION_DATE, + ARTIFACT_NAME, + ARTIFACT_CONTENT + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java new file mode 100644 index 000000000..674da55dd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/AAIQueryResult.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.objects; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class AAIQueryResult { + private List relationshipList; + + private Map additionProperties; + + + public AAIQueryResult(){ + relationshipList = new ArrayList<>(); + additionProperties = new HashMap<>(); + } + + + public List getRelationshipList() { + return relationshipList; + } + + public Map getAdditionProperties() { + return additionProperties; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java new file mode 100644 index 000000000..d32898f1c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/onap/appc/dg/aai/objects/Relationship.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.objects; + +import java.util.HashMap; +import java.util.Map; + + +public class Relationship { + + private String relatedTo; + + private String relatedLink; + + private Map relationShipDataMap; + + private Map relatedProperties; + + public Relationship(){ + relationShipDataMap = new HashMap<>(); + relatedProperties = new HashMap<>(); + } + + public String getRelatedTo() { + return relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public Map getRelationShipDataMap() { + return relationShipDataMap; + } + + public Map getRelatedProperties() { + return relatedProperties; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java deleted file mode 100644 index 64033dd38..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/AAIPlugin.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public interface AAIPlugin extends SvcLogicJavaPlugin { - void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; - - void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException; - - void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException; - - void getResource(Map params, SvcLogicContext ctx) throws APPCException; - - void postResource(Map params, SvcLogicContext ctx) throws APPCException; - - void deleteResource(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java deleted file mode 100644 index 2ec604dcd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/exception/AAIQueryException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.exception; - - -public class AAIQueryException extends Exception{ - public AAIQueryException(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java deleted file mode 100644 index 1b510a8ca..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java +++ /dev/null @@ -1,401 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.i18n.EELFResourceManager; - -import org.onap.appc.dg.aai.AAIPlugin; -import org.onap.appc.dg.aai.exception.AAIQueryException; -import org.onap.appc.dg.aai.objects.AAIQueryResult; -import org.onap.appc.dg.aai.objects.Relationship; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - - -public class AAIPluginImpl implements AAIPlugin { - private AAIClient aaiClient; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class); - - @SuppressWarnings("unchecked") - public AAIPluginImpl() { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(AAIService.class); - aaiClient = (AAIClient) bctx.getService(sref); - } - - @Override - public void postGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { - String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); - String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); - - String key = "vnf-id = '" + vnf_id + "'"; - - Map data = new HashMap<>(); - for (Map.Entry entry : params.entrySet()) { - String paramKey = entry.getKey(); - int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA); - if (pos == 0) { - data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue()); - } - } - - try { - SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - logger.info("AAIResponse: " + response.toString()); - if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - } catch (SvcLogicException e) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error(msg); - throw new APPCException(e); - } - } - - @Override - public void getGenericVnfData(Map params, SvcLogicContext ctx) throws APPCException { - String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME); - String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME); - - String key = "vnf-id = '" + vnf_id + "'"; - try { - SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id); -// String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(msg); - } - String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); - if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; - String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); - if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; - - ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty())); - ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty())); - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - logger.info("AAIResponse: " + response.toString()); - } catch (SvcLogicException e) { - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error(msg); - throw new APPCException(e); - } - } - - @Override - public void getVnfHierarchy(Map params, SvcLogicContext ctx) throws APPCException { - - Map> vnfcMap = new HashMap<>(); - String vnfType,vnfVersion; - String vnfId = params.get("resourceKey"); - AAIQueryResult vnfQueryResult; - int vmCount =0; - try { - vnfQueryResult = readVnf(vnfId); - - vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type"); - vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID); - - for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){ - if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){ - vmCount++; - String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id"); - String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id"); - String vmRelatedLink = vnfRelationship.getRelatedLink(); - String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name"); - String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner"); - String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id"); - - AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId); - String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink"); - - Vserver vm = new Vserver(vmURL,tenantId,vmId,vmRelatedLink,vmName); - for(Relationship vmRelation:vmQueryResult.getRelationshipList()){ - - if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){ - String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name"); - AAIQueryResult vnfcQueryResult = readVnfc(vnfcName); - String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type"); - - Vnfc vnfc = new Vnfc(vnfcType,null,vnfcName); - Set vmSet = vnfcMap.get(vnfc); - if(vmSet == null){ - vmSet = new HashSet<>(); - vnfcMap.put(vnfc,vmSet); - } - vmSet.add(vm); - } - } - } - } - ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount)); - } catch (AAIQueryException e) { - ctx.setAttribute("getVnfHierarchy_result", "FAILURE"); - String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx - .getAttribute("getResource_result")); - logger.warn("Incorrect or Incomplete VNF Hierarchy"); - throw new APPCException("Error Retrieving VNF hierarchy"); - } - - Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); - for(Vnfc vnfc:vnfcMap.keySet()){ - for(Vserver vm:vnfcMap.get(vnfc)){ - vnfc.addVm(vm); - } - vnf.addVnfc(vnfc); - } - - populateContext(vnf,ctx); - ctx.setAttribute("getVnfHierarchy_result", "SUCCESS"); - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - - } - - private void populateContext(Vnf vnf ,SvcLogicContext ctx) { - ctx.setAttribute("vnf.type",vnf.getVnfType()); - ctx.setAttribute("vnf.version",vnf.getVnfVersion()); - ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size())); - int vnfcCount =0; - for(Vnfc vnfc:vnf.getVnfcs()){ - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName()); - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType()); - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size())); - int vmCount =0; - for(Vserver vm:vnfc.getVserverList()){ - ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl()); - } - vnfcCount++; - } - } - - private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException { - String query = "vnfc.vnfc-name = '" + vnfcName + "'"; - String prefix = "VNFC"; - String resourceType = "vnfc"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - String[] additionalProperties = new String[]{"vnfc-type","vnfc-name", - "vnfc-function-code","in-maint","prov-status", - "is-closed-loop-disabled","orchestration-status","resource-version"}; - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) - throws AAIQueryException { - String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId - + "' AND cloud-region.cloud-owner = '" + cloudOwner - + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'"; - String prefix = "VM"; - String resourceType = "vserver"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - String[] additionalProperties = new String[]{"vserver-id","vserver-selflink", - "vserver-name","in-maint","prov-status","is-closed-loop-disabled", - "vserver-name2","resource-version",}; - - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readVnf(String vnfId) throws AAIQueryException { - String query = "generic-vnf.vnf-id = '" + vnfId + "'"; - String prefix = "VNF"; - String resourceType = "generic-vnf"; - SvcLogicContext vnfContext = readResource(query,prefix,resourceType); - - String[] additionalProperties = new String[]{"vnf-type","vnf-name", - "in-maint","prov-status","heat-stack-id", - "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID}; - - return readRelationDataAndProperties(prefix, vnfContext,additionalProperties); - } - - private AAIQueryResult readRelationDataAndProperties(String prefix, - SvcLogicContext context, - String[] additionalProperties) { - AAIQueryResult result = new AAIQueryResult(); - - if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) { - Integer relationsCount = Integer.parseInt(context.getAttribute( - prefix + ".relationship-list.relationship_length")); - for (int i = 0; i < relationsCount; i++) { - String rsKey = prefix + ".relationship-list.relationship[" + i + "]"; - Relationship relationShip = new Relationship(); - relationShip.setRelatedLink(context.getAttribute(rsKey + ".related-link")); - relationShip.setRelatedTo(context.getAttribute(rsKey + ".related-to")); - Integer relationDataCount = - Integer.parseInt(context.getAttribute(rsKey + ".relationship-data_length")); - for (int j = 0; j < relationDataCount; j++) { - String rsDataKey = rsKey + ".relationship-data[" + j + "]"; - String key = context.getAttribute(rsDataKey + ".relationship-key"); - String value = context.getAttribute(rsDataKey + ".relationship-value"); - relationShip.getRelationShipDataMap().put(key, value); - } - Integer relatedPropertyCount = 0; - String relatedPropertyCountStr = null; - try { - relatedPropertyCountStr = context.getAttribute(rsKey + ".related-to-property_length"); - relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr); - } catch (NumberFormatException e) { - logger.debug( - "Invalid value in the context for Related Property Count " + relatedPropertyCountStr); - } - - for (int j = 0; j < relatedPropertyCount; j++) { - String rsPropKey = rsKey + ".related-to-property[" + j + "]"; - String key = context.getAttribute(rsPropKey + ".property-key"); - String value = context.getAttribute(rsPropKey + ".property-value"); - relationShip.getRelatedProperties().put(key, value); - } - result.getRelationshipList().add(relationShip); - } - } else { - logger.error("Relationship-list not present in the SvcLogicContext attributes set." - + (context == null ? "" : "Attribute KeySet = "+ context.getAttributeKeySet())); - } - - if (context != null) { - for (String key : additionalProperties) { - result.getAdditionProperties().put(key, context.getAttribute(prefix + "." + key)); - } - } - return result; - } - - private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException { - SvcLogicContext resourceContext = new SvcLogicContext(); - try { - SvcLogicResource.QueryStatus response = - aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext); - logger.info("AAIResponse: " + response.toString()); - if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){ - throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); - } - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage())); - throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI"); - } - return resourceContext; - } - - @Override public void getResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"); - if (logger.isDebugEnabled()) { - logger.debug("inside getResorce"); - logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey); - } - try { - SvcLogicResource.QueryStatus response = - aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("getResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error( - EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting getResource======"); - } - } - - @Override public void postResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey = - params.get("resourceKey"), att_name = params.get("attributeName"), att_value = - params.get("attributeValue"); - if (logger.isDebugEnabled()) { - logger.debug("inside postResource"); - logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey); - logger.debug("Updating " + att_name + " to : " + att_value); - } - Map data = new HashMap<>(); - data.put(att_name, att_value); - - try { - SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("postResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting postResource======"); - } - } - - @Override public void deleteResource(Map params, SvcLogicContext ctx) throws APPCException { - String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey"); - - if (logger.isDebugEnabled()) { - logger.debug("inside deleteResource"); - logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey); - } - try { - SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx); - logger.info("AAIResponse: " + response.toString()); - ctx.setAttribute("deleteResource_result", response.toString()); - } catch (SvcLogicException e) { - logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage())); - } - if (logger.isDebugEnabled()) { - logger.debug("exiting deleteResource======"); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java deleted file mode 100644 index 6a6818e06..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - - -public class Constants { - public final static String VNF_ID_PARAM_NAME = "aai.vnfID"; - public static final String AAI_PREFIX_PARAM_NAME = "aai.prefix"; - public static final String AAI_INPUT_DATA = "aai.input.data"; - public static final String AAI_ERROR_MESSAGE = "org.onap.appc.dg.error"; - - public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; - public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; - public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; - public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; - - public static final String CONTROLLER_IP = "127.0.0.1"; - public static final int CONTROLLER_PORT = 8181; - public static final String PROTOCOL = "http"; - - public static final String VF_LICENSE = "VF_LICENSE"; - - // tables and fields - public static final String NETCONF_SCHEMA = "sdnctl"; - public static final String SDNCTL_SCHEMA = "sdnctl"; - public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; - public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; - public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; - public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; - public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; - public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; - public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; - public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; - public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; - public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; - public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; - public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; - public static final String LOG_FIELD_NAME = "LOG"; - public static final String SDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; - - // input fields names - public static final String PAYLOAD = "payload"; - - // constants fo DG - public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; - public static final String VNF_VERSION_FIELD_NAME = "org.onap.appc.vfversion"; - public static final String VNF_RESOURCE_VERSION_FIELD_NAME = "org.onap.appc.resource-version"; - public static final String TARGET_VNF_TYPE = "target-vnf-type"; - public static final String FILE_CONTENT_FIELD_NAME = "file-content"; - public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; - public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; - public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; - public static final String UPGRADE_VERSION = "upgrade-version"; - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - public static final String RESOURCEKEY = "resourceKey"; - public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; - public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; - public static final String MODEL_ENTITLMENT_POOL_UUID_NAME = "model.entitlement.pool.uuid"; - public static final String MODEL_LICENSE_KEY_UUID_NAME = "model.license.key.uuid"; - public static final String ENTITLMENT_POOL_UUID_NAME = "entitlement.pool.uuid"; - public static final String LICENSE_KEY_UUID_NAME = "license.key.uuid"; - public static final String IS_ACQUIRE_LICENSE_REQUIRE ="is.acquire-license.require"; - public static final String IS_RELEASE_LICENSE_REQUIRE ="is.release-license.require"; - - public static final String AAI_ENTITLMENT_POOL_UUID_NAME = "aai.input.data.entitlement-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_UUID_NAME = "aai.input.data.license-assignment-group-uuid"; - public static final String AAI_LICENSE_KEY_VALUE = "aai.input.data.license-key"; - public static final String IS_AAI_ENTITLEMENT_UPDATE_REQUIRE = "is.aai-entitlement-update.require"; - public static final String IS_AAI_LICENSE_UPDATE_REQUIRE = "is.aai-license-update.require"; - public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require"; - public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require"; - - /** - * AAI property names - */ - public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id"; - - public enum SDC_ARTIFACTS_FIELDS { - SERVICE_UUID, - DISTRIBUTION_ID, - SERVICE_NAME, - SERVICE_DESCRIPTION, - RESOURCE_UUID, - RESOURCE_INSTANCE_NAME, - RESOURCE_NAME, - RESOURCE_VERSION, - RESOURCE_TYPE, - ARTIFACT_UUID, - ARTIFACT_TYPE, - ARTIFACT_VERSION, - ARTIFACT_DESCRIPTION, - INTERNAL_VERSION, - CREATION_DATE, - ARTIFACT_NAME, - ARTIFACT_CONTENT - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java deleted file mode 100644 index 674da55dd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/AAIQueryResult.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class AAIQueryResult { - private List relationshipList; - - private Map additionProperties; - - - public AAIQueryResult(){ - relationshipList = new ArrayList<>(); - additionProperties = new HashMap<>(); - } - - - public List getRelationshipList() { - return relationshipList; - } - - public Map getAdditionProperties() { - return additionProperties; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java deleted file mode 100644 index d32898f1c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/objects/Relationship.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.objects; - -import java.util.HashMap; -import java.util.Map; - - -public class Relationship { - - private String relatedTo; - - private String relatedLink; - - private Map relationShipDataMap; - - private Map relatedProperties; - - public Relationship(){ - relationShipDataMap = new HashMap<>(); - relatedProperties = new HashMap<>(); - } - - public String getRelatedTo() { - return relatedTo; - } - - public String getRelatedLink() { - return relatedLink; - } - - public Map getRelationShipDataMap() { - return relationShipDataMap; - } - - public Map getRelatedProperties() { - return relatedProperties; - } - - public void setRelatedTo(String relatedTo) { - this.relatedTo = relatedTo; - } - - public void setRelatedLink(String relatedLink) { - this.relatedLink = relatedLink; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java new file mode 100644 index 000000000..3de308392 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIClientMock.java @@ -0,0 +1,547 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException; +import org.onap.ccsdk.sli.adaptors.aai.data.*; +import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent; +import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer; +import org.onap.ccsdk.sli.adaptors.aai.update.Update; + + +public class AAIClientMock implements AAIClient { + + Map mockAAI = new HashMap<>(); + + public void setMockAAI(Map mockAAI) { + this.mockAAI = mockAAI; + } + + @Override + public AAIResponse requestSdnZoneQuery(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVceData(String s, Vce vce) throws AAIServiceException { + return false; + } + + @Override + public Vce requestNetworkVceData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean deleteNetworkVceData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public ServiceInstance requestServiceInterfaceData(String s) throws AAIServiceException { + return null; + } + + @Override + public ServiceInstance requestServiceInterfaceData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postServiceInterfaceData(String s, String s1, String s2, ServiceInstance serviceInstance) throws AAIServiceException { + return false; + } + + @Override + public SearchResults requestServiceInstanceURL(String s) throws AAIServiceException { + return null; + } + + @Override + public Vpe requestNetworkVpeData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVpeData(String s, Vpe vpe) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkVpeData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Vserver requestVServerData(String s, String s1, String s2, String s3) throws AAIServiceException { + return null; + } + + @Override + public boolean postVServerData(String s, String s1, String s2, String s3, Vserver vserver) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteVServerData(String s, String s1, String s2, String s3, String s4) throws AAIServiceException { + return false; + } + + @Override + public URL requestVserverURLNodeQuery(String s) throws AAIServiceException { + return null; + } + + @Override + public String getTenantIdFromVserverUrl(URL url) { + return null; + } + + @Override + public String getCloudOwnerFromVserverUrl(URL url) { + return null; + } + + @Override + public String getCloudRegionFromVserverUrl(URL url) { + return null; + } + + @Override + public String getVServerIdFromVserverUrl(URL url, String s) { + return null; + } + + @Override + public Vserver requestVServerDataByURL(URL url) throws AAIServiceException { + return null; + } + + @Override + public VplsPe requestNetworkVplsPeData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkVplsPeData(String s, VplsPe vplsPe) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkVplsPeData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Complex requestNetworkComplexData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postNetworkComplexData(String s, Complex complex) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteNetworkComplexData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public CtagPool requestCtagPoolData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException { + return null; + } + + @Override + public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException { + return null; + } + + @Override + public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException { + return null; + } + + @Override + public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException { + return null; + } + + @Override + public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException { + return null; + } + + @Override + public PServer dataChangeRequestPServerData(URL url) throws AAIServiceException { + return null; + } + + @Override + public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException { + return null; + } + + @Override + public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException { + return null; + } + + @Override + public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException { + return null; + } + + @Override + public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException { + return false; + } + + @Override + public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException { + return false; + } + + @Override + public GenericVnf requestGenericVnfData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postGenericVnfData(String s, GenericVnf genericVnf) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteGenericVnfData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public DvsSwitch requestDvsSwitchData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postDvsSwitchData(String s, DvsSwitch dvsSwitch) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteDvsSwitchData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public PInterface requestPInterfaceData(String s, String s1) throws AAIServiceException { + return null; + } + + @Override + public boolean postPInterfaceData(String s, String s1, PInterface pInterface) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePInterfaceData(String s, String s1, String s2) throws AAIServiceException { + return false; + } + + @Override + public PhysicalLink requestPhysicalLinkData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postPhysicalLinkData(String s, PhysicalLink physicalLink) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePhysicalLinkData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public PServer requestPServerData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postPServerData(String s, PServer pServer) throws AAIServiceException { + return false; + } + + @Override + public boolean deletePServerData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public L3Network requestL3NetworkData(String s) throws AAIServiceException { + return null; + } + + @Override + public L3Network requestL3NetworkQueryByName(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postL3NetworkData(String s, L3Network l3Network) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteL3NetworkData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public VpnBinding requestVpnBindingData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean deleteVpnBindingData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public VnfImage requestVnfImageData(String s) throws AAIServiceException { + return null; + } + + @Override + public VnfImage requestVnfImageDataByVendorModel(String s, String s1) throws AAIServiceException { + return null; + } + + @Override + public VnfImage requestVnfImageDataByVendorModelVersion(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean sendNotify(NotifyEvent notifyEvent, String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public SitePairSet requestSitePairSetData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postSitePairSetData(String s, SitePairSet sitePairSet) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteSitePairSetData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public Service requestServiceData(String s) throws AAIServiceException { + return null; + } + + @Override + public boolean postServiceData(String s, Service service) throws AAIServiceException { + return false; + } + + @Override + public boolean deleteServiceData(String s, String s1) throws AAIServiceException { + return false; + } + + @Override + public QueryResponse requestNodeQuery(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public String requestDataByURL(URL url) throws AAIServiceException { + return null; + } + + @Override + public GenericVnf requestGenericVnfeNodeQuery(String s) throws AAIServiceException { + return null; + } + + @Override + public Tenant requestTenantData(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public Tenant requestTenantDataByName(String s, String s1, String s2) throws AAIServiceException { + return null; + } + + @Override + public boolean postTenantData(String s, String s1, String s2, Tenant tenant) throws AAIServiceException { + return false; + } + + @Override + public boolean updateAnAIEntry(Update update) throws AAIServiceException { + return false; + } + + @Override + public QueryStatus backup(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus restore(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus isAvailable(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus exists(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus query(String s, boolean b, String s1, String key, String prefix, String s4, SvcLogicContext ctx) throws SvcLogicException { + if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { + for (Map.Entry entry : mockAAI.entrySet()) { + ctx.setAttribute(prefix + "." + entry.getKey(), entry.getValue()); + } + return QueryStatus.SUCCESS; + + + } else if (key.equals("vnf-id = 'test_VNF1'")){ + return QueryStatus.NOT_FOUND; + } + else if (key.equals("vnf-id = 'test_VNF3'")){ + throw new SvcLogicException(); + } + else { + return QueryStatus.FAILURE; + } + + + } + + @Override + public QueryStatus reserve(String s, String s1, String s2, String s3, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus save(String s, boolean b, boolean b1, String s1, Map map, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus release(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus delete(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus notify(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { + return null; + } + + @Override + public QueryStatus update(String s, String key, Map data, String prefix, SvcLogicContext ctx) throws SvcLogicException { + if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { + for (Map.Entry entry : data.entrySet()) { + mockAAI.put(entry.getKey(), entry.getValue()); + } + return QueryStatus.SUCCESS; + + + } else if (key.equals("vnf-id = 'test_VNF1'")){ + return QueryStatus.NOT_FOUND; + } + else if (key.equals("vnf-id = 'test_VNF3'")){ + throw new SvcLogicException(); + } + else { + return QueryStatus.FAILURE; + } + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java new file mode 100644 index 000000000..d2f08597e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/onap/appc/dg/aai/impl/AAIPluginImplTest.java @@ -0,0 +1,259 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.aai.impl; + +import org.junit.runner.RunWith; +import org.onap.appc.dg.aai.Constants; +import org.onap.appc.dg.aai.impl.AAIPluginImpl; +import org.onap.appc.dg.common.dao.DAOService; +import org.onap.appc.dg.common.impl.LicenseManagerImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIClient; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AAIPluginImpl.class, FrameworkUtil.class}) +public class AAIPluginImplTest { + private AAIPluginImpl aaiPlugin; + private AAIClientMock aaiClient; + + private final BundleContext bundleContext= Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + String prefix = "aai.input.data"; + String vnfId = "test_VNF"; + String vnfId1 = "test_VNF1"; + String vnfId2 = "test_VNF2"; + String vnfId3 = "test_VNF3"; + + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + aaiClient = new AAIClientMock(); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiClient); + aaiPlugin = new AAIPluginImpl(); + + + } + + + + + @Test + public void testPostGenericVnfData() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId); + ctx.setAttribute("aai.prefix", prefix); + + aaiPlugin.postGenericVnfData(params, ctx); + + Assert.assertEquals("wrong license-key-uuid","123", mockAAI.get("license-key-uuid")); + Assert.assertEquals("wrong license-assignment-group-uuid","1234", mockAAI.get("license-assignment-group-uuid")); + Assert.assertEquals("wrong data.license-key","12345", mockAAI.get("data.license-key")); + } + + + @Test + public void testPostGenericVnfDataNegativeVnfNotFound() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId1); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + + @Test + public void testPostGenericVnfDataNegativeFailure() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId2); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + + @Test + public void testPostGenericVnfDataNegativeSvcLogicException() throws Exception { + Map params = new HashMap<>(); + params.put(prefix+"."+"license-key-uuid", "123"); + params.put(prefix+"."+"license-assignment-group-uuid", "1234"); + params.put(prefix+"."+"data.license-key", "12345"); + + HashMap mockAAI = new HashMap<>(); + + aaiClient.setMockAAI(mockAAI); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId3); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.postGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + + } + + @Test + public void testGetGenericVnfData() throws Exception { + String vnfNameKey = "vnf-name"; + String vnfType = "VSCP"; + String vnfTypeKey = "vnf-type"; + String provStatus = "Active"; + String provStatusKey = "prov-status"; + String orchestrationStatus = "Running"; + String orchestrationStatusKey = "orchestration-status"; + + Map params = new HashMap<>(); + HashMap mockAAI = new HashMap<>(); + mockAAI.put(vnfNameKey,vnfId); + mockAAI.put(vnfTypeKey,vnfType); + mockAAI.put(provStatusKey, provStatus); + mockAAI.put(orchestrationStatusKey, orchestrationStatus); + aaiClient.setMockAAI(mockAAI); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId); + ctx.setAttribute("aai.prefix", prefix); + + + aaiPlugin.getGenericVnfData(params, ctx); + + Assert.assertEquals("wrong "+vnfNameKey,vnfId, ctx.getAttribute(prefix + "." + vnfNameKey)); + Assert.assertEquals("wrong "+orchestrationStatusKey,orchestrationStatus, ctx.getAttribute(prefix + "." + orchestrationStatusKey)); + Assert.assertEquals("wrong "+vnfTypeKey,vnfType, ctx.getAttribute(prefix + "." + vnfTypeKey)); + Assert.assertEquals("wrong "+provStatusKey,provStatus, ctx.getAttribute(prefix + "." + provStatusKey )); + } + + + + + @Test + public void testGetGenericVnfDataNegativeVnfNotFound() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId1); + ctx.setAttribute("aai.prefix", prefix); + + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + + @Test + public void testGetGenericVnfDataNegativeFailure() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId2); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + + @Test + public void testGetGenericVnfDataNegativeSvcLogicException() throws Exception { + + Map params = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("aai.vnfID", vnfId3); + ctx.setAttribute("aai.prefix", prefix); + + try { + aaiPlugin.getGenericVnfData(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java deleted file mode 100644 index 3de308392..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIClientMock.java +++ /dev/null @@ -1,547 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException; -import org.onap.ccsdk.sli.adaptors.aai.data.*; -import org.onap.ccsdk.sli.adaptors.aai.data.notify.NotifyEvent; -import org.onap.ccsdk.sli.adaptors.aai.data.v1507.VServer; -import org.onap.ccsdk.sli.adaptors.aai.update.Update; - - -public class AAIClientMock implements AAIClient { - - Map mockAAI = new HashMap<>(); - - public void setMockAAI(Map mockAAI) { - this.mockAAI = mockAAI; - } - - @Override - public AAIResponse requestSdnZoneQuery(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVceData(String s, Vce vce) throws AAIServiceException { - return false; - } - - @Override - public Vce requestNetworkVceData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean deleteNetworkVceData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public ServiceInstance requestServiceInterfaceData(String s) throws AAIServiceException { - return null; - } - - @Override - public ServiceInstance requestServiceInterfaceData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postServiceInterfaceData(String s, String s1, String s2, ServiceInstance serviceInstance) throws AAIServiceException { - return false; - } - - @Override - public SearchResults requestServiceInstanceURL(String s) throws AAIServiceException { - return null; - } - - @Override - public Vpe requestNetworkVpeData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVpeData(String s, Vpe vpe) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkVpeData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Vserver requestVServerData(String s, String s1, String s2, String s3) throws AAIServiceException { - return null; - } - - @Override - public boolean postVServerData(String s, String s1, String s2, String s3, Vserver vserver) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteVServerData(String s, String s1, String s2, String s3, String s4) throws AAIServiceException { - return false; - } - - @Override - public URL requestVserverURLNodeQuery(String s) throws AAIServiceException { - return null; - } - - @Override - public String getTenantIdFromVserverUrl(URL url) { - return null; - } - - @Override - public String getCloudOwnerFromVserverUrl(URL url) { - return null; - } - - @Override - public String getCloudRegionFromVserverUrl(URL url) { - return null; - } - - @Override - public String getVServerIdFromVserverUrl(URL url, String s) { - return null; - } - - @Override - public Vserver requestVServerDataByURL(URL url) throws AAIServiceException { - return null; - } - - @Override - public VplsPe requestNetworkVplsPeData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkVplsPeData(String s, VplsPe vplsPe) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkVplsPeData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Complex requestNetworkComplexData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postNetworkComplexData(String s, Complex complex) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteNetworkComplexData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public CtagPool requestCtagPoolData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public VServer dataChangeRequestVServerData(URL url) throws AAIServiceException { - return null; - } - - @Override - public CtagPool dataChangeRequestCtagPoolData(URL url) throws AAIServiceException { - return null; - } - - @Override - public VplsPe dataChangeRequestVplsPeData(URL url) throws AAIServiceException { - return null; - } - - @Override - public Vpe dataChangeRequestVpeData(URL url) throws AAIServiceException { - return null; - } - - @Override - public DvsSwitch dataChangeRequestDvsSwitchData(URL url) throws AAIServiceException { - return null; - } - - @Override - public PServer dataChangeRequestPServerData(URL url) throws AAIServiceException { - return null; - } - - @Override - public OamNetwork dataChangeRequestOAMNetworkData(URL url) throws AAIServiceException { - return null; - } - - @Override - public AvailabilityZone dataChangeRequestAvailabilityZoneData(URL url) throws AAIServiceException { - return null; - } - - @Override - public Complex dataChangeRequestComplexData(URL url) throws AAIServiceException { - return null; - } - - @Override - public boolean dataChangeDeleteVServerData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteCtagPoolData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteVplsPeData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteVpeData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteDvsSwitchData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteOAMNetworkData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteAvailabilityZoneData(URL url) throws AAIServiceException { - return false; - } - - @Override - public boolean dataChangeDeleteComplexData(URL url) throws AAIServiceException { - return false; - } - - @Override - public GenericVnf requestGenericVnfData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postGenericVnfData(String s, GenericVnf genericVnf) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteGenericVnfData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public DvsSwitch requestDvsSwitchData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postDvsSwitchData(String s, DvsSwitch dvsSwitch) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteDvsSwitchData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public PInterface requestPInterfaceData(String s, String s1) throws AAIServiceException { - return null; - } - - @Override - public boolean postPInterfaceData(String s, String s1, PInterface pInterface) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePInterfaceData(String s, String s1, String s2) throws AAIServiceException { - return false; - } - - @Override - public PhysicalLink requestPhysicalLinkData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postPhysicalLinkData(String s, PhysicalLink physicalLink) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePhysicalLinkData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public PServer requestPServerData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postPServerData(String s, PServer pServer) throws AAIServiceException { - return false; - } - - @Override - public boolean deletePServerData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public L3Network requestL3NetworkData(String s) throws AAIServiceException { - return null; - } - - @Override - public L3Network requestL3NetworkQueryByName(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postL3NetworkData(String s, L3Network l3Network) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteL3NetworkData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public VpnBinding requestVpnBindingData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean deleteVpnBindingData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public VnfImage requestVnfImageData(String s) throws AAIServiceException { - return null; - } - - @Override - public VnfImage requestVnfImageDataByVendorModel(String s, String s1) throws AAIServiceException { - return null; - } - - @Override - public VnfImage requestVnfImageDataByVendorModelVersion(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean sendNotify(NotifyEvent notifyEvent, String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public SitePairSet requestSitePairSetData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postSitePairSetData(String s, SitePairSet sitePairSet) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteSitePairSetData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public Service requestServiceData(String s) throws AAIServiceException { - return null; - } - - @Override - public boolean postServiceData(String s, Service service) throws AAIServiceException { - return false; - } - - @Override - public boolean deleteServiceData(String s, String s1) throws AAIServiceException { - return false; - } - - @Override - public QueryResponse requestNodeQuery(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public String requestDataByURL(URL url) throws AAIServiceException { - return null; - } - - @Override - public GenericVnf requestGenericVnfeNodeQuery(String s) throws AAIServiceException { - return null; - } - - @Override - public Tenant requestTenantData(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public Tenant requestTenantDataByName(String s, String s1, String s2) throws AAIServiceException { - return null; - } - - @Override - public boolean postTenantData(String s, String s1, String s2, Tenant tenant) throws AAIServiceException { - return false; - } - - @Override - public boolean updateAnAIEntry(Update update) throws AAIServiceException { - return false; - } - - @Override - public QueryStatus backup(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus restore(Map map, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus isAvailable(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus exists(String s, String s1, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus query(String s, boolean b, String s1, String key, String prefix, String s4, SvcLogicContext ctx) throws SvcLogicException { - if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { - for (Map.Entry entry : mockAAI.entrySet()) { - ctx.setAttribute(prefix + "." + entry.getKey(), entry.getValue()); - } - return QueryStatus.SUCCESS; - - - } else if (key.equals("vnf-id = 'test_VNF1'")){ - return QueryStatus.NOT_FOUND; - } - else if (key.equals("vnf-id = 'test_VNF3'")){ - throw new SvcLogicException(); - } - else { - return QueryStatus.FAILURE; - } - - - } - - @Override - public QueryStatus reserve(String s, String s1, String s2, String s3, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus save(String s, boolean b, boolean b1, String s1, Map map, String s2, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus release(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus delete(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus notify(String s, String s1, SvcLogicContext svcLogicContext) throws SvcLogicException { - return null; - } - - @Override - public QueryStatus update(String s, String key, Map data, String prefix, SvcLogicContext ctx) throws SvcLogicException { - if (s.equals("generic-vnf") && key.equals("vnf-id = 'test_VNF'") && ctx != null) { - for (Map.Entry entry : data.entrySet()) { - mockAAI.put(entry.getKey(), entry.getValue()); - } - return QueryStatus.SUCCESS; - - - } else if (key.equals("vnf-id = 'test_VNF1'")){ - return QueryStatus.NOT_FOUND; - } - else if (key.equals("vnf-id = 'test_VNF3'")){ - throw new SvcLogicException(); - } - else { - return QueryStatus.FAILURE; - } - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java deleted file mode 100644 index d2f08597e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-aai/src/main/test/java/org/openecomp/appc/dg/aai/impl/AAIPluginImplTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.aai.impl; - -import org.junit.runner.RunWith; -import org.onap.appc.dg.aai.Constants; -import org.onap.appc.dg.aai.impl.AAIPluginImpl; -import org.onap.appc.dg.common.dao.DAOService; -import org.onap.appc.dg.common.impl.LicenseManagerImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.*; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({AAIPluginImpl.class, FrameworkUtil.class}) -public class AAIPluginImplTest { - private AAIPluginImpl aaiPlugin; - private AAIClientMock aaiClient; - - private final BundleContext bundleContext= Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - String prefix = "aai.input.data"; - String vnfId = "test_VNF"; - String vnfId1 = "test_VNF1"; - String vnfId2 = "test_VNF2"; - String vnfId3 = "test_VNF3"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - aaiClient = new AAIClientMock(); - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiClient); - aaiPlugin = new AAIPluginImpl(); - - - } - - - - - @Test - public void testPostGenericVnfData() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId); - ctx.setAttribute("aai.prefix", prefix); - - aaiPlugin.postGenericVnfData(params, ctx); - - Assert.assertEquals("wrong license-key-uuid","123", mockAAI.get("license-key-uuid")); - Assert.assertEquals("wrong license-assignment-group-uuid","1234", mockAAI.get("license-assignment-group-uuid")); - Assert.assertEquals("wrong data.license-key","12345", mockAAI.get("data.license-key")); - } - - - @Test - public void testPostGenericVnfDataNegativeVnfNotFound() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId1); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - - @Test - public void testPostGenericVnfDataNegativeFailure() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId2); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - - @Test - public void testPostGenericVnfDataNegativeSvcLogicException() throws Exception { - Map params = new HashMap<>(); - params.put(prefix+"."+"license-key-uuid", "123"); - params.put(prefix+"."+"license-assignment-group-uuid", "1234"); - params.put(prefix+"."+"data.license-key", "12345"); - - HashMap mockAAI = new HashMap<>(); - - aaiClient.setMockAAI(mockAAI); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId3); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.postGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - - } - - @Test - public void testGetGenericVnfData() throws Exception { - String vnfNameKey = "vnf-name"; - String vnfType = "VSCP"; - String vnfTypeKey = "vnf-type"; - String provStatus = "Active"; - String provStatusKey = "prov-status"; - String orchestrationStatus = "Running"; - String orchestrationStatusKey = "orchestration-status"; - - Map params = new HashMap<>(); - HashMap mockAAI = new HashMap<>(); - mockAAI.put(vnfNameKey,vnfId); - mockAAI.put(vnfTypeKey,vnfType); - mockAAI.put(provStatusKey, provStatus); - mockAAI.put(orchestrationStatusKey, orchestrationStatus); - aaiClient.setMockAAI(mockAAI); - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId); - ctx.setAttribute("aai.prefix", prefix); - - - aaiPlugin.getGenericVnfData(params, ctx); - - Assert.assertEquals("wrong "+vnfNameKey,vnfId, ctx.getAttribute(prefix + "." + vnfNameKey)); - Assert.assertEquals("wrong "+orchestrationStatusKey,orchestrationStatus, ctx.getAttribute(prefix + "." + orchestrationStatusKey)); - Assert.assertEquals("wrong "+vnfTypeKey,vnfType, ctx.getAttribute(prefix + "." + vnfTypeKey)); - Assert.assertEquals("wrong "+provStatusKey,provStatus, ctx.getAttribute(prefix + "." + provStatusKey )); - } - - - - - @Test - public void testGetGenericVnfDataNegativeVnfNotFound() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId1); - ctx.setAttribute("aai.prefix", prefix); - - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - - @Test - public void testGetGenericVnfDataNegativeFailure() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId2); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - - @Test - public void testGetGenericVnfDataNegativeSvcLogicException() throws Exception { - - Map params = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("aai.vnfID", vnfId3); - ctx.setAttribute("aai.prefix", prefix); - - try { - aaiPlugin.getGenericVnfData(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java new file mode 100644 index 000000000..17bb56f66 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DCAEReporterPlugin.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface DCAEReporterPlugin extends SvcLogicJavaPlugin { + void report(Map params, SvcLogicContext ctx) throws APPCException; + void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java new file mode 100644 index 000000000..b0ee4a5c9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/DgResolverPlugin.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +public interface DgResolverPlugin extends SvcLogicJavaPlugin { + void resolveDg(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java new file mode 100644 index 000000000..3e03c2ff7 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/IntermediateMessageSender.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +/** + * This interface provides api for sending intermediate messages from DG to initiator + */ +public interface IntermediateMessageSender extends SvcLogicJavaPlugin{ + + /** + * DG plugin which sends intermediate messages generated from DG to the initiator + * @param params expects 1. code, (mandatory) + * 2. message, (mandatory) + * 3. payload, + * 4. prefix + * @param context expects 1. input.common-header.timestamp, + * 2. input.common-header.api-ver, + * 3. input.common-header.originator-id, + * 4. input.common-header.request-id, (mandatory) + * 5. input.common-header.sub-request-id, + * 6. input.action + */ + void sendMessage(Map params, SvcLogicContext context); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java new file mode 100644 index 000000000..95143e145 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/JsonDgUtil.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface JsonDgUtil extends SvcLogicJavaPlugin { + void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException; + + void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Creates filename and content in Json format. + * @param params + * @param ctx + * @throws APPCException + */ + void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Checks if a file is created. + * @param params + * @param ctx + * @throws APPCException + */ + void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java new file mode 100644 index 000000000..54456b385 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/LegacyUtil.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public interface LegacyUtil extends SvcLogicJavaPlugin { + + void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException; + + void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException; + + void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java new file mode 100644 index 000000000..935aa877d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/OutputMessagePlugin.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; + +public interface OutputMessagePlugin extends SvcLogicJavaPlugin { + + void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java new file mode 100644 index 000000000..06036c225 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFCDgResolverPlugin.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; + + +public interface VNFCDgResolverPlugin extends SvcLogicJavaPlugin { + void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java new file mode 100644 index 000000000..4ce0a9150 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VNFConfigurator.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; +/** + * DG plugin created for VNF configuration operation to store data in MD-SAL store + **/ +public interface VNFConfigurator extends SvcLogicJavaPlugin{ + /** + * it is invoked from the DG, and it performs following operations + * 1. checks whether given yang module is present in the MD-SAL store + * 2. if it is absent, loads it into MD-SAL store + * 3. Stores the VNF configuration into MD-SAL store + * @param params should have 1. uniqueId, 2. yang, 3.configJSON, 4.requestId + * @param context - DG context + * @throws APPCException + */ + void storeConfig(Map params, SvcLogicContext context) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java new file mode 100644 index 000000000..b25eaf10f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/VnfExecutionFlow.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +public interface VnfExecutionFlow extends SvcLogicJavaPlugin { + void getVnfExecutionFlowData(Map params, SvcLogicContext context); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java new file mode 100644 index 000000000..3c70bab84 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolver.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesResolver; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.locks.ReentrantLock; + +abstract class AbstractResolver { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractResolver.class); + + private long interval; + + private volatile long lastUpdate = 0l; + private volatile boolean isUpdateInProgress = false; + private volatile RankedAttributesResolver dgResolver; + + private final ReentrantLock INIT_LOCK = new ReentrantLock(); + + AbstractResolver(int interval) { + this.interval = interval * 1000; + } + + private RankedAttributesResolver createResolver(String resolverType) { + AbstractResolverDataReader reader = ResolverDataReaderFactory.createResolverDataReader(resolverType); + return reader.read(); + } + + private boolean isExpired() { + return (System.currentTimeMillis() - lastUpdate) > interval; + } + + protected RankedAttributesResolver resolver(String resolverType) { + + /* + * In general case, the method implementation is non-blocking. The first + * thread that identifies data expiration will be used to refresh it. In + * meanwhile, any other thread will get the old instance without waiting + * for the updated one. The only exception is the very first time when + * previous instance doesn't exist - in such a cases all the threads + * will be waiting on INIT_LOCK while one of them initializes the + * resolver instance. NOTE: The initialization is intentionally + * implemented in lazy manner to make sure the bundle is initialized + * properly on startup regardless whether or not the data is correct. + * Afterwards, the resolver may be instantiated as many times as needed. + */ + + try { + + if (dgResolver == null) { + INIT_LOCK.lock(); + if (dgResolver != null) { + INIT_LOCK.unlock(); + } + } + + if (!isUpdateInProgress && isExpired()) { + + boolean doUpgrade = false; + + synchronized (this) { + if (!isUpdateInProgress) { + isUpdateInProgress = true; + doUpgrade = true; + } + } + + if (doUpgrade) { + + logger.info("DG resolver configuration data has expired - initiating refresh"); + + try { + RankedAttributesResolver temp = createResolver(resolverType); + dgResolver = temp; + lastUpdate = System.currentTimeMillis(); + + logger.info("DG resolver configuration data has been refreshed successfully"); + } finally { + isUpdateInProgress = false; + } + } + } + } finally { + if (INIT_LOCK.isHeldByCurrentThread()) { + INIT_LOCK.unlock(); + } + } + + return dgResolver; + } + protected abstract FlowKey resolve(final String...args); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java new file mode 100644 index 000000000..c5fe87c77 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/AbstractResolverDataReader.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.dao.util.DBUtils; +import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; +import org.onap.appc.rankingframework.ConfigurationEntry; +import org.onap.appc.rankingframework.ConfigurationSet; +import org.onap.appc.rankingframework.RankedAttributesResolver; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; +import java.util.Iterator; + +abstract class AbstractResolverDataReader { + + private class ConfigurationSetAdaptor implements ConfigurationSet { + + private final ResultSet resultSet; + + private class ResultSetIterator implements Iterator>, ConfigurationEntry { + @Override + public boolean hasNext() { + try { + return resultSet.next(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public ConfigurationEntry next() { + return this; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public Object getAttributeValue(String name) { + try { + return resultSet.getObject(name); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public FlowKey getResult() { + try { + return new FlowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + } + + ConfigurationSetAdaptor(ResultSet resultSet) { + this.resultSet = resultSet; + } + + @Override + public Iterable> getEntries() { + return new Iterable>() { + + @Override + public Iterator> iterator() { + return new ResultSetIterator(); + } + }; + } + + @Override + public Collection getRankedAttributeNames() { + return getAttributeNames(); + } + } + + protected abstract Collection getAttributeNames(); + protected abstract String getQueryStmt(); + + + + RankedAttributesResolver read() { + try { + try (Connection conn = DBUtils.getConnection("sdnctl")) { + try (PreparedStatement stmt = conn.prepareStatement(getQueryStmt())) { + try (ResultSet res = stmt.executeQuery()) { + if (res.next()) { + res.beforeFirst(); + ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); + return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); + } else { + throw new IllegalStateException(); + } + } + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java new file mode 100644 index 000000000..603b65a19 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/Constants.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + + + +class Constants { + + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + public static final String EVENT_MESSAGE = "event-message"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; + public static final String DG_ERROR_CODE = "output.status.dgerror.code"; + public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; + public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; + public static final String PAYLOAD = "payload"; + public static final String OUTPUT_PAYLOAD = "output.payload"; + + //Added for VnfExecution Flow + public static final String FLOW_STRATEGY = "FlowStrategy" ; + public static final String DEPENDENCY_TYPE = "DependencyType"; + public static final String VNF_TYPE = "vnfType"; + public static final String VNF_VERION = "vnfVersion"; + + + public static final String APPC_INSTANCE_ID= "appc-instance-id"; + + //Added for Cvaas + public static final String CVAAS_DIRECTORY_PATH = "cvaas-directory-path"; + public static final String CVAAS_FILE_NAME = "cvaas-file-name"; + public static final String CVAAS_FILE_CONTENT = "cvaas-file-content"; + + enum LegacyAttributes { + Action("org.onap.appc.action"), + VMID("org.onap.appc.vmid"), + IdentityURL("org.onap.appc.identity.url"), + TenantID("org.onap.appc.tenant.id"), + SkipHypervisorCheck("org.onap.appc.skiphypervisorcheck"); + + private String value; + LegacyAttributes(String value) {this.value = value;} + String getValue() {return value;} + }; + + enum LCMAttributes { + Action("input.action"), + Payload("input.payload"), + VMID("vm-id"), + IdentityURL("identity-url"), + TenantID("tenant.id"), + SkipHypervisorCheck("skip-hypervisor-check"); + + private String value; + LCMAttributes(String value) {this.value = value;} + String getValue() {return value;} + }; + + // DG Resolver Constants + public static final String IN_PARAM_VNF_TYPE = "vnfType"; + public static final String IN_PARAM_VNFC_TYPE = "vnfcType"; + public static final String IN_PARAM_ACTION = "action"; + public static final String IN_PARAM_API_VERSION = "api-ver"; + + public static final String OUT_PARAM_DG_NAME = "dg_name"; + public static final String OUT_PARAM_DG_VERSION= "dg_version"; + public static final String OUT_PARAM_DG_MODULE = "dg_module"; + + public static final String TABLE_NAME = "VNFC_DG_MAPPING"; + public static final String TABLE_COLUMN_VNF_TYPE = "VNF_TYPE"; + public static final String TABLE_COLUMN_VNFC_TYPE = "VNFC_TYPE"; + public static final String TABLE_COLUMN_ACTION = "ACTION"; + public static final String TABLE_COLUMN_API_VERSION = "API_VERSION"; + public static final String TABLE_COLUMN_DG_NAME = "DG_NAME"; + public static final String TABLE_COLUMN_DG_VERSION= "DG_VERSION"; + public static final String TABLE_COLUMN_DG_MODULE = "DG_MODULE"; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java new file mode 100644 index 000000000..68f3cdc68 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImpl.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventHeader; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.adapter.message.event.EventStatus; +import org.onap.appc.dg.common.DCAEReporterPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +public class DCAEReporterPluginImpl implements DCAEReporterPlugin { + + private EventSender eventSender; + + public DCAEReporterPluginImpl() { + // do nothing + } + + /** + * Injected by blueprint + * + * @param eventSender to be set + */ + public void setEventSender(EventSender eventSender) { + this.eventSender = eventSender; + } + + @Override + public void report(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription,apiVersion,eventId ; + + Integer errorCode = readErrorCode(params,ctx); + errorDescription = params.get(Constants.EVENT_MESSAGE); + + if(StringUtils.isEmpty(errorDescription)) { + reportLegacy(params , ctx); + }else{ + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(errorCode, errorDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + } + + private Integer readErrorCode(Map params, SvcLogicContext ctx) { + Integer errorReportCode = 501; + String errorCodeStr = params.get(Constants.DG_ERROR_CODE); + errorCodeStr = StringUtils.isEmpty(errorCodeStr)? + ctx.getAttribute(Constants.DG_ERROR_CODE):errorCodeStr; + try{ + errorReportCode = Integer.parseInt(errorCodeStr); + } + catch (NumberFormatException e){ + // Ignore Exception + } + return errorReportCode; + } + + @Override + public void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException { + Integer successReportCode = 500; + String successDescription, apiVersion, eventId; + successDescription = params.get(Constants.EVENT_MESSAGE); + + if(StringUtils.isEmpty(successDescription)) { + successDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); + } + + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + if (null == successDescription) { + successDescription = "Success"; + } + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(successReportCode, successDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + + private void reportLegacy(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription,apiVersion,eventId ; + + Integer errorCode = readErrorCode(params,ctx); + errorDescription = getErrorDescriptionAndAddToCtx(params,ctx); + + apiVersion = ctx.getAttribute("input.common-header.api-ver"); + eventId = ctx.getAttribute("input.common-header.request-id"); + + EventMessage eventMessage = new EventMessage(new EventHeader( + (new java.util.Date()).toString(), apiVersion, eventId), + new EventStatus(errorCode, errorDescription)); + String eventWriteTopic = params.get("event-topic-name"); + if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ + eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); + }else { + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + } + + private String getErrorDescriptionAndAddToCtx(Map params, SvcLogicContext ctx) { + String errorDescription; + errorDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); + if(StringUtils.isEmpty(errorDescription)) { + errorDescription = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); + } + if(StringUtils.isEmpty(errorDescription)) { + errorDescription = "Unknown"; + } + addToContextIfNotContains(errorDescription,ctx); + return errorDescription; + } + + private void addToContextIfNotContains(String errorDescription, SvcLogicContext ctx) { + String errorDescriptionFromCtx; + errorDescriptionFromCtx = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); + if(StringUtils.isEmpty(errorDescriptionFromCtx)){ + errorDescriptionFromCtx = ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE); + } + if(StringUtils.isEmpty(errorDescriptionFromCtx)){ + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); + }else if (!errorDescriptionFromCtx.contains(errorDescription)){ + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescriptionFromCtx+ " | "+ errorDescription); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java new file mode 100644 index 000000000..c68fde5a2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/DgResolverPluginImpl.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +import org.onap.appc.dg.common.DgResolverPlugin; + +public class DgResolverPluginImpl implements DgResolverPlugin { + + @Override + public void resolveDg(Map params, SvcLogicContext ctx) throws APPCException { + + String DGName, DGVersion, DGModule = null; + String prefix = params.containsKey("prefix") ? params.get("prefix") + "." : ""; + AbstractResolver resolver = ResolverFactory.createResolver(params.get("DGResolutionType")); + FlowKey flowKey = null; + try { + + if(params.get("DGResolutionType").equalsIgnoreCase("VNFC")) { + flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get(Constants.IN_PARAM_VNFC_TYPE), params.get(Constants.IN_PARAM_API_VERSION)); + }else if(params.get("DGResolutionType").equalsIgnoreCase("VNF")){ + flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get("vnfVersion"), params.get(Constants.IN_PARAM_API_VERSION)); + } + if (flowKey != null) { + DGName = flowKey.name(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_NAME, DGName); + DGVersion = flowKey.version(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_VERSION, DGVersion); + DGModule = flowKey.module(); + ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_MODULE, DGModule); + } else { + throw new RuntimeException(params.get("DGResolutionType")+ " DG not found for vnf type :" + params.get(Constants.IN_PARAM_VNF_TYPE) + + " vnfc type : " + params.get(Constants.IN_PARAM_VNFC_TYPE) + + " action : " + params.get(Constants.IN_PARAM_ACTION) + + " api version : " + params.get(Constants.IN_PARAM_API_VERSION)); + } + } catch (Exception e) { + String msg = EELFResourceManager.format(Msg.FAILURE_RETRIEVE_VNFC_DG,params.get(Constants.IN_PARAM_VNFC_TYPE), e.getMessage()); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw new RuntimeException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java new file mode 100644 index 000000000..68f596f5d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/FlowKey.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +class FlowKey { + private final String name; + private final String version; + private final String module; + + FlowKey(String name, String version, String module) { + this.name = name; + this.version = version; + this.module = module; + } + + String name() { + return name; + } + + String version() { + return version; + } + + String module() { + return module; + } + + @Override + public String toString() { + StringBuilder buff = new StringBuilder(128); + buff.append("{"); + buff.append("module = ").append(module); + buff.append(", "); + buff.append("name = ").append(name); + buff.append(", "); + buff.append("version = ").append(version); + buff.append("}"); + return buff.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java new file mode 100644 index 000000000..026fa2841 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/IntermediateMessageSenderImpl.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.dg.common.IntermediateMessageSender; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +public class IntermediateMessageSenderImpl implements IntermediateMessageSender { + + + private Producer producer; + + private Configuration configuration; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(IntermediateMessageSenderImpl.class); + + private static final String STATUS = "STATUS"; + private static final String FAILURE = "FAILURE"; + private static final String SUCCESS = "SUCCESS"; + private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; + + private static final String RESPONSE = "response"; + private static final String MSO = "MSO"; + + public void init(){ + configuration = ConfigurationFactory.getConfiguration(); + Properties properties=configuration.getProperties(); + + String writeTopic = properties.getProperty("appc.LCM.topic.write"); + String apiKey = properties.getProperty("appc.LCM.client.key"); + String apiSecret = properties.getProperty("appc.LCM.client.secret"); + String hostNames = properties.getProperty("appc.LCM.poolMembers"); + + logger.debug("Configuration Read : writeTopic = " + writeTopic +", " + + "hostNames = " + hostNames); + + Set pool = new HashSet<>(); + if (!StringUtils.isEmpty(hostNames)) { + for (String name : hostNames.split(",")) { + pool.add(name); + } + } + + BundleContext ctx = FrameworkUtil.getBundle(IntermediateMessageSenderImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); + } + } + } + + @Override + public void sendMessage(Map params, SvcLogicContext context) { + String prefix = params.get("prefix"); + prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; + try{ + validateInputs(params,context); + String jsonMessage = getJsonMessage(params, context); + logger.debug("Constructed JSON Message : " + jsonMessage); + producer.post("",jsonMessage); + context.setAttribute(prefix + STATUS, SUCCESS); + } + catch(Exception e){ + String errorMessage = "Error sending intermediate message to initiator " + e.getMessage(); + context.setAttribute(prefix + STATUS, FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + logger.error(errorMessage,e); + } + } + + private void validateInputs(Map params, SvcLogicContext context) throws APPCException { + String code = params.get("code"); + String message = params.get("message"); + if(StringUtils.isEmpty(code) || StringUtils.isEmpty(message)){ + throw new APPCException("code or message is empty"); + } + String requestId = context.getAttribute("input.common-header.request-id"); + if(StringUtils.isEmpty(requestId)){ + throw new APPCException("requestId is empty"); + } + } + + private String getJsonMessage(Map params, SvcLogicContext context) { + ObjectMapper objectMapper = new ObjectMapper(); + + ObjectNode commonHeader = getCommonHeader(context); + ObjectNode status = getStatus(params); + + ObjectNode output = objectMapper.createObjectNode(); + output.put("common-header",commonHeader); + output.put("status",status); + + ObjectNode body = objectMapper.createObjectNode(); + body.put("output",output); + + ObjectNode root = objectMapper.createObjectNode(); + root.put("type", RESPONSE); + root.put("rpc-name",context.getAttribute("input.action")); + root.put("cambria.partition", MSO); + root.put("correlation-id",getCorrelationId(context)); + root.put("body",body); + + return root.toString(); + } + + private String getCorrelationId(SvcLogicContext context) { + String requestId = context.getAttribute("input.common-header.request-id"); + String subRequestId = context.getAttribute("input.common-header.sub-request-id"); + return requestId + (StringUtils.isEmpty(subRequestId)?"":("-"+subRequestId)); + } + + private ObjectNode getStatus(Map params) { + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode status = objectMapper.createObjectNode(); + status.put("code",params.get("code")); + status.put("message",params.get("message")); + return status; + } + + private ObjectNode getCommonHeader(SvcLogicContext context) { + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode commonHeader = objectMapper.createObjectNode(); + commonHeader.put("api-ver",context.getAttribute("input.common-header.api-ver")); + commonHeader.put("timestamp",context.getAttribute("input.common-header.timestamp")); + commonHeader.put("originator-id",context.getAttribute("input.common-header.originator-id")); + commonHeader.put("request-id",context.getAttribute("input.common-header.request-id")); + commonHeader.put("sub-request-id",context.getAttribute("input.common-header.sub-request-id")); + return commonHeader; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java new file mode 100644 index 000000000..fff43cbf5 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/JsonDgUtilImpl.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.common.JsonDgUtil; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.util.JsonUtil; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public class JsonDgUtilImpl implements JsonDgUtil { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class); + + private static final ThreadLocal DATE_TIME_PARSER_THREAD_LOCAL = new ThreadLocal() { + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + } + }; + + @Override + public void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to flatAndAddToContext with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + try { + String paramName = Constants.PAYLOAD; + String payload = params.get(paramName); + if (payload == "") + payload = ctx.getAttribute("input.payload"); + if (!StringUtils.isEmpty(payload)) { + Map flatMap = JsonUtil.convertJsonStringToFlatMap(payload); + if (flatMap != null && flatMap.size() > 0) { + for (Map.Entry entry : flatMap.entrySet()) { + ctx.setAttribute(entry.getKey(), entry.getValue()); + } + } + } else { + logger.warn("input payload param value is empty (\"\") or null"); + } + } catch (Exception e) { + logger.error(e.toString()); + String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED,params.get(Constants.PAYLOAD)); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(e); + } + } + + @Override + public void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException{ + if (logger.isTraceEnabled()) { + logger.trace("Entering to generateOutputPayloadFromContext with SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + + try { + Set keys = ctx.getAttributeKeySet(); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode JsonNode = objectMapper.createObjectNode(); + for (String key : keys) { + if(key.startsWith(Constants.OUTPUT_PAYLOAD+".")){ + String objkey= key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", ""); + if(objkey.contains("[") && objkey.contains("]")){ + ArrayNode arrayNode; + String arrayKey = objkey.substring(0,objkey.indexOf('[')); + int arrayIndex = Integer.parseInt(objkey.substring(objkey.indexOf('[')+1,objkey.indexOf(']'))); + if(JsonNode.has(arrayKey)){ + arrayNode = (ArrayNode)JsonNode.get(arrayKey); + arrayNode.insert(arrayIndex,ctx.getAttribute(key)); + }else { + arrayNode = objectMapper.createArrayNode(); + arrayNode.insert(arrayIndex,ctx.getAttribute(key)); + JsonNode.put(arrayKey,arrayNode); + } + }else { + JsonNode.put(objkey, ctx.getAttribute(key)); + } + } + } + if(JsonNode.size()>0) { + ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(JsonNode)); + } + } catch (Exception e) { + logger.error(e.toString()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw new APPCException(e); + } + + } + + @Override + public void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) + throws APPCException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = " + + ObjectUtils.toString(ctx)); + } + + String vnfId = null; + try { + String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH); + String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID); + + /* + * File name + */ + vnfId = params.get("vnf-id"); + long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis(); + + ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_" + + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json"); + + /* + * File content + */ + + String uploadDate = ctx.getAttribute("running-config.upload-date"); + long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime(); + + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode jsonNode = objectMapper.createObjectNode(); + jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id")); + jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id")); + jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id")); + jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description")); + jsonNode.put("ACTION", ctx.getAttribute("running-config.action")); + jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp); + jsonNode.put("UPLOAD_DATE", uploadDate); + jsonNode.put("VNF_ID", vnfId); + jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name")); + jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name")); + jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type")); + jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type")); + jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address")); + jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator")); + jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete")); + jsonNode.put("CONTENT", ctx.getAttribute("running-config.content")); + + ctx.setAttribute(Constants.CVAAS_FILE_CONTENT, + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)); + + } catch (Exception e) { + String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId; + logger.error(errorMessage, e); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); + throw new APPCException(e); + } + } + + @Override + public void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException { + String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME); + File file = new File(filePath); + + if (!file.exists()) { + String vnfId = params.get("vnf-id"); + String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId; + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); + throw new APPCException(errorMessage); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java new file mode 100644 index 000000000..ad0884b94 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/LegacyUtilImpl.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Map; + +import org.onap.appc.dg.common.LegacyUtil; +import org.onap.appc.dg.common.utils.JSONUtil; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class LegacyUtilImpl implements LegacyUtil { + + @Override public void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException { + ctx.setAttribute(Constants.LegacyAttributes.Action.getValue(), ctx.getAttribute(Constants.LCMAttributes.Action.getValue()).toLowerCase()); + + String payloadStr = ctx.getAttribute(Constants.LCMAttributes.Payload.getValue()); + Map payloads = JSONUtil.extractPlainValues(payloadStr, + Constants.LCMAttributes.VMID.getValue(), Constants.LCMAttributes.IdentityURL.getValue(), Constants.LCMAttributes.TenantID.getValue(), + Constants.LCMAttributes.SkipHypervisorCheck.getValue()); + + ctx.setAttribute(Constants.LegacyAttributes.VMID.getValue(), payloads.get(Constants.LCMAttributes.VMID.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.IdentityURL.getValue(), payloads.get(Constants.LCMAttributes.IdentityURL.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.TenantID.getValue(), payloads.get(Constants.LCMAttributes.TenantID.getValue())); + ctx.setAttribute(Constants.LegacyAttributes.SkipHypervisorCheck.getValue(), payloads.get(Constants.LCMAttributes.SkipHypervisorCheck.getValue())); + + } + + @Override + public void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException { + } + + @Override + public void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException { + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java new file mode 100644 index 000000000..66ac82fcb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/OutputMessagePluginImpl.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +import org.onap.appc.dg.common.OutputMessagePlugin; +import org.onap.appc.exceptions.APPCException; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + +public class OutputMessagePluginImpl implements OutputMessagePlugin { + + @Override + public void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException { + String errorDescription, eventDescription; + + //making output.status.message + errorDescription = params.get(Constants.ATTRIBUTE_ERROR_MESSAGE); + eventDescription = params.get(Constants.EVENT_MESSAGE); + + addToContextIfNotContains(errorDescription , eventDescription, ctx); + + //making event-message + + if (!isEmpty(eventDescription)) { + ctx.setAttribute(Constants.EVENT_MESSAGE, eventDescription); + } else { + ctx.setAttribute(Constants.EVENT_MESSAGE, ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + } + } + + public static void addToContextIfNotContains(String errorDescription, String eventDescription, SvcLogicContext ctx) { + if (!isEmpty(errorDescription)){ + if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); + }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(errorDescription)) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + errorDescription); + } + } + if (!isEmpty(eventDescription)){ + if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, eventDescription); + }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(eventDescription)) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + eventDescription); + } + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java new file mode 100644 index 000000000..790547f37 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverDataReaderFactory.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class ResolverDataReaderFactory { + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private static class ReferenceHolder{ + private static final AbstractResolverDataReader VNFC_RESOLVER_DATA_READER = new VNFCResolverDataReader(); + + private static final AbstractResolverDataReader VNF_RESOLVER_DATA_READER = new VNFResolverDataReader(); + } + + public static AbstractResolverDataReader createResolverDataReader(String resolverType){ + if(resolverType.equalsIgnoreCase("VNF")){ + return ReferenceHolder.VNF_RESOLVER_DATA_READER; + }else if(resolverType.equalsIgnoreCase("VNFC")){ + return ReferenceHolder.VNFC_RESOLVER_DATA_READER; + }else { + return null; + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java new file mode 100644 index 000000000..e39546846 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/ResolverFactory.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class ResolverFactory { + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private static class ReferenceHolder{ + private static final AbstractResolver VNFC_RESOLVER = new VNFCResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); + private static final AbstractResolver VNF_RESOLVER = new VNFResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); + } + + public static AbstractResolver createResolver(String resolverType){ + if(resolverType.equalsIgnoreCase("VNF")){ + return ReferenceHolder.VNF_RESOLVER; + }else if(resolverType.equalsIgnoreCase("VNFC")){ + return ReferenceHolder.VNFC_RESOLVER; + }else { + return null; + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java new file mode 100644 index 000000000..304bdf882 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCDgResolverPluginImpl.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Map; + +public class VNFCDgResolverPluginImpl implements org.onap.appc.dg.common.VNFCDgResolverPlugin { + @Override + public void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException { + DgResolverPluginImpl dgResolverPlugin = new DgResolverPluginImpl(); + params.put("DGResolutionType" , "VNFC"); + dgResolverPlugin.resolveDg(params,ctx); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java new file mode 100644 index 000000000..e2893951b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolver.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesContext; + + +public class VNFCResolver extends AbstractResolver { + VNFCResolver(int interval) { + super(interval); + } + + @Override + protected FlowKey resolve(String... args) { + if(args.length !=4){ + throw new IllegalStateException(args.toString()); + } + return resolve(args[0],args[1],args[2],args[3]); + } + + protected FlowKey resolve(final String action, final String vnfType, final String vnfcType, final String apiVersion) { + RankedAttributesContext context = new RankedAttributesContext() { + @Override + public Object getAttributeValue(String name) { + switch (name) { + case "action": + return action; + case "api_version": + return apiVersion; + case "vnf_type": + return vnfType; + case "vnfc_type": + return vnfcType; + default: + throw new IllegalStateException(name); + } + } + }; + + FlowKey wfKey = resolver("VNFC").resolve(context); + + return wfKey; + } +} + diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java new file mode 100644 index 000000000..c78da685c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFCResolverDataReader.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Arrays; +import java.util.Collection; + +public class VNFCResolverDataReader extends AbstractResolverDataReader { + @Override + protected Collection getAttributeNames() { + return Arrays.asList("action","api_version", "vnf_type", "vnfc_type"); + } + + @Override + protected String getQueryStmt() { + return "select vnf_type,vnfc_type,api_version,action,dg_name,dg_version,dg_module FROM VNFC_DG_MAPPING"; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java new file mode 100644 index 000000000..c46a9c227 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFConfiguratorImpl.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.Constants; +import org.onap.appc.dg.common.VNFConfigurator; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.impl.MDSALStoreFactory; +import org.onap.appc.mdsal.objects.BundleInfo; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.apache.commons.lang3.StringUtils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + + +public class VNFConfiguratorImpl implements VNFConfigurator { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(VNFConfiguratorImpl.class); + private static final String STATUS = "STATUS"; + private static final String FAILURE = "FAILURE"; + private static final String SUCCESS = "SUCCESS"; + private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; + + @Override + public void storeConfig(Map params, SvcLogicContext context) throws APPCException { + String uniqueId = params.get("uniqueId"); + String yang = params.get("yang"); + String configJSON = params.get("configJSON"); + String requestId = params.get("requestId"); + String prefix = params.get("prefix"); + prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; + + MDSALStore store = MDSALStoreFactory.createMDSALStore(); + + logger.debug("Inputs Received : uniqueId = " + uniqueId + + " , yang = " + yang + + " , configJSON = " + configJSON + + " , requestId = " + requestId + + " , prefix = " +prefix); + + try { + + if(StringUtils.isEmpty(uniqueId) + ||StringUtils.isEmpty(yang) + || StringUtils.isEmpty(configJSON) + || StringUtils.isEmpty(requestId)){ + throw new APPCException("One or more input parameters are empty : uniqueId = " + uniqueId + " " + + ", yang = " + yang + + " , configJSON = " + configJSON + + " , requestId = " + requestId); + } + + Date revision = new SimpleDateFormat(Constants.YANG_REVISION_FORMAT).parse(Constants.YANG_REVISION); + + boolean isYangAlreadyLoaded = store.isModulePresent(uniqueId,revision); + + if(!isYangAlreadyLoaded){ + BundleInfo bundleInfo = getBundleInfo(uniqueId); + store.storeYangModule(yang,bundleInfo); + } + store.storeJson(uniqueId, requestId , configJSON); + context.setAttribute(prefix + STATUS, SUCCESS); + } catch (ParseException e) { + String errorMessage ="Error parsing the date : " + Constants.YANG_REVISION + " into format " + Constants.YANG_REVISION_FORMAT; + logger.error(errorMessage,e); + context.setAttribute(prefix + STATUS, FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + throw new APPCException(e.getMessage()); + }catch (MDSALStoreException e){ + String errorMessage = "Error while adding yang to MD-SAL store." + e.getMessage(); + logger.error(errorMessage,e); + context.setAttribute(prefix + STATUS,FAILURE); + context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); + throw new APPCException(e.getMessage()); + } + + } + + private BundleInfo getBundleInfo(String uniqueId) { + BundleInfo bundleInfo = new BundleInfo(); + bundleInfo.setDescription(uniqueId); + bundleInfo.setName(uniqueId); + bundleInfo.setLocation(uniqueId); + return bundleInfo; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java new file mode 100644 index 000000000..501ad0713 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolver.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.rankingframework.RankedAttributesContext; + +public class VNFResolver extends AbstractResolver { + VNFResolver(int interval) { + super(interval); + } + + @Override + protected FlowKey resolve(String... args) { + return resolve(args[0],args[1],args[2],args[3]); + } + + + protected FlowKey resolve(final String action, final String vnfType, final String vnfVersion, final String apiVersion) { + RankedAttributesContext context = new RankedAttributesContext() { + @Override + public Object getAttributeValue(String name) { + switch (name) { + case "action": + return action; + case "api_version": + return apiVersion; + case "vnf_type": + return vnfType; + case "vnf_version": + return vnfVersion; + default: + throw new IllegalStateException(name); + } + } + }; + + FlowKey wfKey = resolver("VNF").resolve(context); + + return wfKey; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java new file mode 100644 index 000000000..3c4cf837e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VNFResolverDataReader.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Arrays; +import java.util.Collection; + +/** + * @since January 19,2017 + */ +public class VNFResolverDataReader extends AbstractResolverDataReader { + @Override + protected Collection getAttributeNames() { + return Arrays.asList("action","api_version", "vnf_type", "vnf_version"); + } + + @Override + protected String getQueryStmt() { + return "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java new file mode 100644 index 000000000..65b364f62 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/impl/VnfExecutionFlowImpl.java @@ -0,0 +1,271 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.*; + +import org.onap.appc.dg.common.VnfExecutionFlow; +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; +import org.onap.appc.i18n.Msg; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public class VnfExecutionFlowImpl implements VnfExecutionFlow { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(VnfExecutionFlowImpl.class); + + public VnfExecutionFlowImpl(){ + + } + + @Override + public void getVnfExecutionFlowData(Map params, SvcLogicContext context) { + String dependencyType = params.get(Constants.DEPENDENCY_TYPE); + String flowStrategy = params.get(Constants.FLOW_STRATEGY); + DependencyModelIdentifier modelIdentifier = readDependencyModelIdentifier(params); + VnfcDependencyModel dependencyModel = null; + try { + validateInput(dependencyType, flowStrategy, params); + + if (logger.isTraceEnabled()) { + logger.trace("Input received from DG Node : dependencyType = " + dependencyType + + " , flowStrategy = " + flowStrategy + + ", DependencyModelIdentifier = " + modelIdentifier.toString()); + } + + DependencyManager dependencyManager = DependencyModelFactory.createDependencyManager(); + + + dependencyModel = dependencyManager.getVnfcDependencyModel( + modelIdentifier, DependencyTypes.findByString(dependencyType)); + } catch (DependencyModelNotFound e) { + String msg = EELFResourceManager.format(Msg.DEPENDENCY_MODEL_NOT_FOUND,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + context.setAttribute("dependencyModelFound","false"); + return; + } catch (InvalidDependencyModel e){ + String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + }catch (RuntimeException e){ + logger.error(e.getMessage()); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); + throw e; + } + + + context.setAttribute("dependencyModelFound","true"); + if(logger.isDebugEnabled()){ + logger.debug("Dependency Model = " +dependencyModel); + } + logger.info("Building Inventory Model from DG context"); + InventoryModel inventoryModel = readInventoryModel(context); + if(logger.isDebugEnabled()){ + logger.debug("Inventory Model = " +inventoryModel); + } + + if(logger.isDebugEnabled()){ + logger.debug("Validating inventory model with dependency model"); + } + try { + validateInventoryModelWithDependencyModel(dependencyModel, inventoryModel); + }catch (RuntimeException e){ + logger.error(e.getMessage()); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); + throw e; + } + logger.info("Creating flow builder"); + FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder( + FlowStrategies.findByString(flowStrategy)); + + logger.info("Building Vnf flow model"); + VnfcFlowModel flowModel = null; + try{ + flowModel = flowBuilder.buildFlowModel(dependencyModel,inventoryModel); + } + catch (InvalidDependencyModel e){ + String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); + logger.error(msg); + context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + } + + // remove VNFCs from the flow model where vserver list is empty + reconcileFlowModel(flowModel); + populateContext(flowModel,context); + if(logger.isDebugEnabled()){ + logContext(context); + } + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVnfExecutionFlowData","VNF ID " + params.get(Constants.VNF_TYPE)); + context.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } + + private void validateInput(String dependencyType, String flowStrategy, Map params) { + DependencyTypes dependencyTypes = DependencyTypes.findByString(dependencyType); + if(dependencyTypes == null){ + throw new RuntimeException("Dependency type from the input : " + dependencyType +" is invalid."); + } + FlowStrategies flowStrategies = FlowStrategies.findByString(flowStrategy); + if(flowStrategies == null){ + throw new RuntimeException("Flow Strategy from the input : " + flowStrategy +" is invalid."); + } + String vnfType = params.get(Constants.VNF_TYPE); + if(vnfType ==null || vnfType.length() ==0){ + throw new RuntimeException("Vnf Type is not passed in the input"); + } + String vnfVersion = params.get(Constants.VNF_VERION); + if(vnfVersion == null || vnfVersion.length() ==0){ + throw new RuntimeException("Vnf Version not found"); + } + } + + private void logContext(SvcLogicContext context) { + for(String key:context.getAttributeKeySet()){ + logger.debug(key + " = " + context.getAttribute(key) + "\n" ); + } + } + + private void populateContext(VnfcFlowModel flowModel, SvcLogicContext context) { + int flowIndex=0; + Iterator> iterator = flowModel.getModelIterator(); + while (iterator.hasNext()){ + for(Vnfc vnfc:iterator.next()){ + context.setAttribute("vnfcFlow["+flowIndex+"].vnfcName",vnfc.getVnfcName()); + context.setAttribute("vnfcFlow["+flowIndex+"].vnfcType",vnfc.getVnfcType()); + context.setAttribute("vnfcFlow["+flowIndex+"].resilienceType",vnfc.getResilienceType()); + context.setAttribute("vnfcFlow["+flowIndex+"].vmCount",Integer.toString(vnfc.getVserverList().size())); + int vmIndex =0; + for(Vserver vm :vnfc.getVserverList()){ + context.setAttribute("vnfcFlow["+flowIndex+"].vm["+vmIndex+"].url",vm.getUrl()); + vmIndex++; + } + flowIndex++; + } + } + context.setAttribute("vnfcFlowCount",Integer.toString(flowIndex)); + } + + private InventoryModel readInventoryModel(SvcLogicContext context) { + String vnfId = context.getAttribute("input.action-identifiers.vnf-id"); + String vnfType = context.getAttribute("vnf.type"); + String vnfVersion = context.getAttribute("vnf.version"); + String vnfcCountStr = context.getAttribute("vnf.vnfcCount"); + Integer vnfcCount = Integer.parseInt(vnfcCountStr); + + Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); + + for(Integer i=0;i params) { + String vnfType = params.get(Constants.VNF_TYPE); + String catalogVersion = params.get(Constants.VNF_VERION); + return new DependencyModelIdentifier(vnfType,catalogVersion); + } + + private void validateInventoryModelWithDependencyModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + Set dependencyModelVnfcSet = new HashSet(); + Set dependencyModelMandatoryVnfcSet = new HashSet(); + Set inventoryModelVnfcsSet = new HashSet(); + + for (Node node : dependencyModel.getDependencies()) { + dependencyModelVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); + if (node.getChild().isMandatory()) { + dependencyModelMandatoryVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); + } + } + + for (Vnfc vnfc : inventoryModel.getVnf().getVnfcs()) { + inventoryModelVnfcsSet.add(vnfc.getVnfcType().toLowerCase()); + } + + // if dependency model and inventory model contains same set of VNFCs, validation succeed and hence return + if (dependencyModelVnfcSet.equals(inventoryModelVnfcsSet)) { + return; + } + + if (inventoryModelVnfcsSet.size() >= dependencyModelVnfcSet.size()) { + Set difference = new HashSet(inventoryModelVnfcsSet); + difference.removeAll(dependencyModelVnfcSet); + logger.error("Dependency model is missing following vnfc type(s): " + difference); + throw new RuntimeException("Dependency model is missing following vnfc type(s): " + difference); + } else { + Set difference = new HashSet(dependencyModelVnfcSet); + difference.removeAll(inventoryModelVnfcsSet); + difference.retainAll(dependencyModelMandatoryVnfcSet); + if (difference.size() > 0) { + logger.error("Inventory model is missing following mandatory vnfc type(s): " + difference); + throw new RuntimeException("Inventory model is missing following mandatory vnfc type(s): " + difference); + } + } + } + + private void reconcileFlowModel(VnfcFlowModel flowModel) { + Iterator> flowIterator = flowModel.getModelIterator(); + while (flowIterator.hasNext()) { + Iterator vnfcIterator = flowIterator.next().iterator(); + while (vnfcIterator.hasNext()) { + Vnfc vnfc = vnfcIterator.next(); + if (vnfc.getVserverList().size() == 0) { + if (logger.isDebugEnabled()) { + logger.debug("No vservers present for Vnfc type: " + vnfc.getVnfcType() + ". Hence, removing it from the flow model."); + } + vnfcIterator.remove(); + } + } + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java new file mode 100644 index 000000000..1572e726b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/objects/ConnectionDetails.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.objects; + + + +public class ConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java new file mode 100644 index 000000000..38012b1bd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JAXBUtil.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.utils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; + + + +public class JAXBUtil { + + public static T toObject(String xml, Class type) throws JAXBException { + + //create JAXB context + JAXBContext context = JAXBContext.newInstance(type); + + //Create Unmarshaller using JAXB context + Unmarshaller unmarshaller = context.createUnmarshaller(); + + InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes()); + BufferedReader reader = new BufferedReader(new InputStreamReader(xmlInputStream)); + + return type.cast(unmarshaller.unmarshal(reader)); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java new file mode 100644 index 000000000..388295a7d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/onap/appc/dg/common/utils/JSONUtil.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.utils; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.Reader; +import java.util.*; + + +public class JSONUtil { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + public static T fromJson(String json, Class clazz) { + + try { + return OBJECT_MAPPER.readValue(json, clazz); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static T fromJson(Reader reader, Class clazz) { + + try { + return OBJECT_MAPPER.readValue(reader, clazz); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static String toJson(Object object) { + + try { + return OBJECT_MAPPER.writeValueAsString(object); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static Map extractPlainValues(String json, String ... names) { + if (null == names) return Collections.emptyMap(); + Map values = new HashMap<>(); + try { + final JsonNode jsonNode = OBJECT_MAPPER.readTree(json); + for (String name : names) { + values.put(name, jsonNode.path(name).asText()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return values; + } + + + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java deleted file mode 100644 index 17bb56f66..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DCAEReporterPlugin.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface DCAEReporterPlugin extends SvcLogicJavaPlugin { - void report(Map params, SvcLogicContext ctx) throws APPCException; - void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java deleted file mode 100644 index b0ee4a5c9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/DgResolverPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -public interface DgResolverPlugin extends SvcLogicJavaPlugin { - void resolveDg(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java deleted file mode 100644 index 3e03c2ff7..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/IntermediateMessageSender.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -/** - * This interface provides api for sending intermediate messages from DG to initiator - */ -public interface IntermediateMessageSender extends SvcLogicJavaPlugin{ - - /** - * DG plugin which sends intermediate messages generated from DG to the initiator - * @param params expects 1. code, (mandatory) - * 2. message, (mandatory) - * 3. payload, - * 4. prefix - * @param context expects 1. input.common-header.timestamp, - * 2. input.common-header.api-ver, - * 3. input.common-header.originator-id, - * 4. input.common-header.request-id, (mandatory) - * 5. input.common-header.sub-request-id, - * 6. input.action - */ - void sendMessage(Map params, SvcLogicContext context); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java deleted file mode 100644 index 95143e145..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/JsonDgUtil.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface JsonDgUtil extends SvcLogicJavaPlugin { - void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException; - - void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Creates filename and content in Json format. - * @param params - * @param ctx - * @throws APPCException - */ - void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Checks if a file is created. - * @param params - * @param ctx - * @throws APPCException - */ - void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java deleted file mode 100644 index 54456b385..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/LegacyUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - - -public interface LegacyUtil extends SvcLogicJavaPlugin { - - void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException; - - void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException; - - void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java deleted file mode 100644 index 935aa877d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/OutputMessagePlugin.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; - -public interface OutputMessagePlugin extends SvcLogicJavaPlugin { - - void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java deleted file mode 100644 index 06036c225..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFCDgResolverPlugin.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; - - -public interface VNFCDgResolverPlugin extends SvcLogicJavaPlugin { - void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java deleted file mode 100644 index 4ce0a9150..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VNFConfigurator.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; -/** - * DG plugin created for VNF configuration operation to store data in MD-SAL store - **/ -public interface VNFConfigurator extends SvcLogicJavaPlugin{ - /** - * it is invoked from the DG, and it performs following operations - * 1. checks whether given yang module is present in the MD-SAL store - * 2. if it is absent, loads it into MD-SAL store - * 3. Stores the VNF configuration into MD-SAL store - * @param params should have 1. uniqueId, 2. yang, 3.configJSON, 4.requestId - * @param context - DG context - * @throws APPCException - */ - void storeConfig(Map params, SvcLogicContext context) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java deleted file mode 100644 index b25eaf10f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/VnfExecutionFlow.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -public interface VnfExecutionFlow extends SvcLogicJavaPlugin { - void getVnfExecutionFlowData(Map params, SvcLogicContext context); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java deleted file mode 100644 index 3c70bab84..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolver.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesResolver; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.locks.ReentrantLock; - -abstract class AbstractResolver { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractResolver.class); - - private long interval; - - private volatile long lastUpdate = 0l; - private volatile boolean isUpdateInProgress = false; - private volatile RankedAttributesResolver dgResolver; - - private final ReentrantLock INIT_LOCK = new ReentrantLock(); - - AbstractResolver(int interval) { - this.interval = interval * 1000; - } - - private RankedAttributesResolver createResolver(String resolverType) { - AbstractResolverDataReader reader = ResolverDataReaderFactory.createResolverDataReader(resolverType); - return reader.read(); - } - - private boolean isExpired() { - return (System.currentTimeMillis() - lastUpdate) > interval; - } - - protected RankedAttributesResolver resolver(String resolverType) { - - /* - * In general case, the method implementation is non-blocking. The first - * thread that identifies data expiration will be used to refresh it. In - * meanwhile, any other thread will get the old instance without waiting - * for the updated one. The only exception is the very first time when - * previous instance doesn't exist - in such a cases all the threads - * will be waiting on INIT_LOCK while one of them initializes the - * resolver instance. NOTE: The initialization is intentionally - * implemented in lazy manner to make sure the bundle is initialized - * properly on startup regardless whether or not the data is correct. - * Afterwards, the resolver may be instantiated as many times as needed. - */ - - try { - - if (dgResolver == null) { - INIT_LOCK.lock(); - if (dgResolver != null) { - INIT_LOCK.unlock(); - } - } - - if (!isUpdateInProgress && isExpired()) { - - boolean doUpgrade = false; - - synchronized (this) { - if (!isUpdateInProgress) { - isUpdateInProgress = true; - doUpgrade = true; - } - } - - if (doUpgrade) { - - logger.info("DG resolver configuration data has expired - initiating refresh"); - - try { - RankedAttributesResolver temp = createResolver(resolverType); - dgResolver = temp; - lastUpdate = System.currentTimeMillis(); - - logger.info("DG resolver configuration data has been refreshed successfully"); - } finally { - isUpdateInProgress = false; - } - } - } - } finally { - if (INIT_LOCK.isHeldByCurrentThread()) { - INIT_LOCK.unlock(); - } - } - - return dgResolver; - } - protected abstract FlowKey resolve(final String...args); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java deleted file mode 100644 index c5fe87c77..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/AbstractResolverDataReader.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.dao.util.DBUtils; -import org.onap.appc.rankingframework.AbstractRankedAttributesResolverFactory; -import org.onap.appc.rankingframework.ConfigurationEntry; -import org.onap.appc.rankingframework.ConfigurationSet; -import org.onap.appc.rankingframework.RankedAttributesResolver; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Iterator; - -abstract class AbstractResolverDataReader { - - private class ConfigurationSetAdaptor implements ConfigurationSet { - - private final ResultSet resultSet; - - private class ResultSetIterator implements Iterator>, ConfigurationEntry { - @Override - public boolean hasNext() { - try { - return resultSet.next(); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public ConfigurationEntry next() { - return this; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Object getAttributeValue(String name) { - try { - return resultSet.getObject(name); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - @Override - public FlowKey getResult() { - try { - return new FlowKey(resultSet.getString("dg_name"), resultSet.getString("dg_version"), resultSet.getString("dg_module")); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - } - - ConfigurationSetAdaptor(ResultSet resultSet) { - this.resultSet = resultSet; - } - - @Override - public Iterable> getEntries() { - return new Iterable>() { - - @Override - public Iterator> iterator() { - return new ResultSetIterator(); - } - }; - } - - @Override - public Collection getRankedAttributeNames() { - return getAttributeNames(); - } - } - - protected abstract Collection getAttributeNames(); - protected abstract String getQueryStmt(); - - - - RankedAttributesResolver read() { - try { - try (Connection conn = DBUtils.getConnection("sdnctl")) { - try (PreparedStatement stmt = conn.prepareStatement(getQueryStmt())) { - try (ResultSet res = stmt.executeQuery()) { - if (res.next()) { - res.beforeFirst(); - ConfigurationSet resolverConfig = new ConfigurationSetAdaptor(res); - return AbstractRankedAttributesResolverFactory.getInstance().create(resolverConfig); - } else { - throw new IllegalStateException(); - } - } - } - } - } catch (SQLException e) { - throw new RuntimeException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java deleted file mode 100644 index 603b65a19..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/Constants.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - - - -class Constants { - - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - public static final String EVENT_MESSAGE = "event-message"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; - public static final String DG_ERROR_CODE = "output.status.dgerror.code"; - public static final String API_VERSION_FIELD_NAME = "org.onap.appc.apiversion"; - public static final String REQ_ID_FIELD_NAME = "org.onap.appc.reqid"; - public static final String PAYLOAD = "payload"; - public static final String OUTPUT_PAYLOAD = "output.payload"; - - //Added for VnfExecution Flow - public static final String FLOW_STRATEGY = "FlowStrategy" ; - public static final String DEPENDENCY_TYPE = "DependencyType"; - public static final String VNF_TYPE = "vnfType"; - public static final String VNF_VERION = "vnfVersion"; - - - public static final String APPC_INSTANCE_ID= "appc-instance-id"; - - //Added for Cvaas - public static final String CVAAS_DIRECTORY_PATH = "cvaas-directory-path"; - public static final String CVAAS_FILE_NAME = "cvaas-file-name"; - public static final String CVAAS_FILE_CONTENT = "cvaas-file-content"; - - enum LegacyAttributes { - Action("org.onap.appc.action"), - VMID("org.onap.appc.vmid"), - IdentityURL("org.onap.appc.identity.url"), - TenantID("org.onap.appc.tenant.id"), - SkipHypervisorCheck("org.onap.appc.skiphypervisorcheck"); - - private String value; - LegacyAttributes(String value) {this.value = value;} - String getValue() {return value;} - }; - - enum LCMAttributes { - Action("input.action"), - Payload("input.payload"), - VMID("vm-id"), - IdentityURL("identity-url"), - TenantID("tenant.id"), - SkipHypervisorCheck("skip-hypervisor-check"); - - private String value; - LCMAttributes(String value) {this.value = value;} - String getValue() {return value;} - }; - - // DG Resolver Constants - public static final String IN_PARAM_VNF_TYPE = "vnfType"; - public static final String IN_PARAM_VNFC_TYPE = "vnfcType"; - public static final String IN_PARAM_ACTION = "action"; - public static final String IN_PARAM_API_VERSION = "api-ver"; - - public static final String OUT_PARAM_DG_NAME = "dg_name"; - public static final String OUT_PARAM_DG_VERSION= "dg_version"; - public static final String OUT_PARAM_DG_MODULE = "dg_module"; - - public static final String TABLE_NAME = "VNFC_DG_MAPPING"; - public static final String TABLE_COLUMN_VNF_TYPE = "VNF_TYPE"; - public static final String TABLE_COLUMN_VNFC_TYPE = "VNFC_TYPE"; - public static final String TABLE_COLUMN_ACTION = "ACTION"; - public static final String TABLE_COLUMN_API_VERSION = "API_VERSION"; - public static final String TABLE_COLUMN_DG_NAME = "DG_NAME"; - public static final String TABLE_COLUMN_DG_VERSION= "DG_VERSION"; - public static final String TABLE_COLUMN_DG_MODULE = "DG_MODULE"; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java deleted file mode 100644 index 68f3cdc68..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImpl.java +++ /dev/null @@ -1,168 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventHeader; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.adapter.message.event.EventStatus; -import org.onap.appc.dg.common.DCAEReporterPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -public class DCAEReporterPluginImpl implements DCAEReporterPlugin { - - private EventSender eventSender; - - public DCAEReporterPluginImpl() { - // do nothing - } - - /** - * Injected by blueprint - * - * @param eventSender to be set - */ - public void setEventSender(EventSender eventSender) { - this.eventSender = eventSender; - } - - @Override - public void report(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription,apiVersion,eventId ; - - Integer errorCode = readErrorCode(params,ctx); - errorDescription = params.get(Constants.EVENT_MESSAGE); - - if(StringUtils.isEmpty(errorDescription)) { - reportLegacy(params , ctx); - }else{ - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(errorCode, errorDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - } - - private Integer readErrorCode(Map params, SvcLogicContext ctx) { - Integer errorReportCode = 501; - String errorCodeStr = params.get(Constants.DG_ERROR_CODE); - errorCodeStr = StringUtils.isEmpty(errorCodeStr)? - ctx.getAttribute(Constants.DG_ERROR_CODE):errorCodeStr; - try{ - errorReportCode = Integer.parseInt(errorCodeStr); - } - catch (NumberFormatException e){ - // Ignore Exception - } - return errorReportCode; - } - - @Override - public void reportSuccess(Map params, SvcLogicContext ctx) throws APPCException { - Integer successReportCode = 500; - String successDescription, apiVersion, eventId; - successDescription = params.get(Constants.EVENT_MESSAGE); - - if(StringUtils.isEmpty(successDescription)) { - successDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); - } - - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - if (null == successDescription) { - successDescription = "Success"; - } - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(successReportCode, successDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - - private void reportLegacy(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription,apiVersion,eventId ; - - Integer errorCode = readErrorCode(params,ctx); - errorDescription = getErrorDescriptionAndAddToCtx(params,ctx); - - apiVersion = ctx.getAttribute("input.common-header.api-ver"); - eventId = ctx.getAttribute("input.common-header.request-id"); - - EventMessage eventMessage = new EventMessage(new EventHeader( - (new java.util.Date()).toString(), apiVersion, eventId), - new EventStatus(errorCode, errorDescription)); - String eventWriteTopic = params.get("event-topic-name"); - if(!StringUtils.isEmpty(eventWriteTopic) && eventWriteTopic!=null){ - eventSender.sendEvent(MessageDestination.DCAE, eventMessage,eventWriteTopic); - }else { - eventSender.sendEvent(MessageDestination.DCAE, eventMessage); - } - } - - private String getErrorDescriptionAndAddToCtx(Map params, SvcLogicContext ctx) { - String errorDescription; - errorDescription = params.get(Constants.DG_OUTPUT_STATUS_MESSAGE); - if(StringUtils.isEmpty(errorDescription)) { - errorDescription = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); - } - if(StringUtils.isEmpty(errorDescription)) { - errorDescription = "Unknown"; - } - addToContextIfNotContains(errorDescription,ctx); - return errorDescription; - } - - private void addToContextIfNotContains(String errorDescription, SvcLogicContext ctx) { - String errorDescriptionFromCtx; - errorDescriptionFromCtx = ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE); - if(StringUtils.isEmpty(errorDescriptionFromCtx)){ - errorDescriptionFromCtx = ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE); - } - if(StringUtils.isEmpty(errorDescriptionFromCtx)){ - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); - }else if (!errorDescriptionFromCtx.contains(errorDescription)){ - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescriptionFromCtx+ " | "+ errorDescription); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java deleted file mode 100644 index c68fde5a2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/DgResolverPluginImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -import org.onap.appc.dg.common.DgResolverPlugin; - -public class DgResolverPluginImpl implements DgResolverPlugin { - - @Override - public void resolveDg(Map params, SvcLogicContext ctx) throws APPCException { - - String DGName, DGVersion, DGModule = null; - String prefix = params.containsKey("prefix") ? params.get("prefix") + "." : ""; - AbstractResolver resolver = ResolverFactory.createResolver(params.get("DGResolutionType")); - FlowKey flowKey = null; - try { - - if(params.get("DGResolutionType").equalsIgnoreCase("VNFC")) { - flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get(Constants.IN_PARAM_VNFC_TYPE), params.get(Constants.IN_PARAM_API_VERSION)); - }else if(params.get("DGResolutionType").equalsIgnoreCase("VNF")){ - flowKey = resolver.resolve(params.get(Constants.IN_PARAM_ACTION), params.get(Constants.IN_PARAM_VNF_TYPE), params.get("vnfVersion"), params.get(Constants.IN_PARAM_API_VERSION)); - } - if (flowKey != null) { - DGName = flowKey.name(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_NAME, DGName); - DGVersion = flowKey.version(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_VERSION, DGVersion); - DGModule = flowKey.module(); - ctx.setAttribute(prefix + Constants.OUT_PARAM_DG_MODULE, DGModule); - } else { - throw new RuntimeException(params.get("DGResolutionType")+ " DG not found for vnf type :" + params.get(Constants.IN_PARAM_VNF_TYPE) - + " vnfc type : " + params.get(Constants.IN_PARAM_VNFC_TYPE) - + " action : " + params.get(Constants.IN_PARAM_ACTION) - + " api version : " + params.get(Constants.IN_PARAM_API_VERSION)); - } - } catch (Exception e) { - String msg = EELFResourceManager.format(Msg.FAILURE_RETRIEVE_VNFC_DG,params.get(Constants.IN_PARAM_VNFC_TYPE), e.getMessage()); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw new RuntimeException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java deleted file mode 100644 index 68f596f5d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/FlowKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -class FlowKey { - private final String name; - private final String version; - private final String module; - - FlowKey(String name, String version, String module) { - this.name = name; - this.version = version; - this.module = module; - } - - String name() { - return name; - } - - String version() { - return version; - } - - String module() { - return module; - } - - @Override - public String toString() { - StringBuilder buff = new StringBuilder(128); - buff.append("{"); - buff.append("module = ").append(module); - buff.append(", "); - buff.append("name = ").append(name); - buff.append(", "); - buff.append("version = ").append(version); - buff.append("}"); - return buff.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java deleted file mode 100644 index 026fa2841..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/IntermediateMessageSenderImpl.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.dg.common.IntermediateMessageSender; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -public class IntermediateMessageSenderImpl implements IntermediateMessageSender { - - - private Producer producer; - - private Configuration configuration; - - private final EELFLogger logger = EELFManager.getInstance().getLogger(IntermediateMessageSenderImpl.class); - - private static final String STATUS = "STATUS"; - private static final String FAILURE = "FAILURE"; - private static final String SUCCESS = "SUCCESS"; - private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; - - private static final String RESPONSE = "response"; - private static final String MSO = "MSO"; - - public void init(){ - configuration = ConfigurationFactory.getConfiguration(); - Properties properties=configuration.getProperties(); - - String writeTopic = properties.getProperty("appc.LCM.topic.write"); - String apiKey = properties.getProperty("appc.LCM.client.key"); - String apiSecret = properties.getProperty("appc.LCM.client.secret"); - String hostNames = properties.getProperty("appc.LCM.poolMembers"); - - logger.debug("Configuration Read : writeTopic = " + writeTopic +", " + - "hostNames = " + hostNames); - - Set pool = new HashSet<>(); - if (!StringUtils.isEmpty(hostNames)) { - for (String name : hostNames.split(",")) { - pool.add(name); - } - } - - BundleContext ctx = FrameworkUtil.getBundle(IntermediateMessageSenderImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); - } - } - } - - @Override - public void sendMessage(Map params, SvcLogicContext context) { - String prefix = params.get("prefix"); - prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; - try{ - validateInputs(params,context); - String jsonMessage = getJsonMessage(params, context); - logger.debug("Constructed JSON Message : " + jsonMessage); - producer.post("",jsonMessage); - context.setAttribute(prefix + STATUS, SUCCESS); - } - catch(Exception e){ - String errorMessage = "Error sending intermediate message to initiator " + e.getMessage(); - context.setAttribute(prefix + STATUS, FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - logger.error(errorMessage,e); - } - } - - private void validateInputs(Map params, SvcLogicContext context) throws APPCException { - String code = params.get("code"); - String message = params.get("message"); - if(StringUtils.isEmpty(code) || StringUtils.isEmpty(message)){ - throw new APPCException("code or message is empty"); - } - String requestId = context.getAttribute("input.common-header.request-id"); - if(StringUtils.isEmpty(requestId)){ - throw new APPCException("requestId is empty"); - } - } - - private String getJsonMessage(Map params, SvcLogicContext context) { - ObjectMapper objectMapper = new ObjectMapper(); - - ObjectNode commonHeader = getCommonHeader(context); - ObjectNode status = getStatus(params); - - ObjectNode output = objectMapper.createObjectNode(); - output.put("common-header",commonHeader); - output.put("status",status); - - ObjectNode body = objectMapper.createObjectNode(); - body.put("output",output); - - ObjectNode root = objectMapper.createObjectNode(); - root.put("type", RESPONSE); - root.put("rpc-name",context.getAttribute("input.action")); - root.put("cambria.partition", MSO); - root.put("correlation-id",getCorrelationId(context)); - root.put("body",body); - - return root.toString(); - } - - private String getCorrelationId(SvcLogicContext context) { - String requestId = context.getAttribute("input.common-header.request-id"); - String subRequestId = context.getAttribute("input.common-header.sub-request-id"); - return requestId + (StringUtils.isEmpty(subRequestId)?"":("-"+subRequestId)); - } - - private ObjectNode getStatus(Map params) { - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode status = objectMapper.createObjectNode(); - status.put("code",params.get("code")); - status.put("message",params.get("message")); - return status; - } - - private ObjectNode getCommonHeader(SvcLogicContext context) { - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode commonHeader = objectMapper.createObjectNode(); - commonHeader.put("api-ver",context.getAttribute("input.common-header.api-ver")); - commonHeader.put("timestamp",context.getAttribute("input.common-header.timestamp")); - commonHeader.put("originator-id",context.getAttribute("input.common-header.originator-id")); - commonHeader.put("request-id",context.getAttribute("input.common-header.request-id")); - commonHeader.put("sub-request-id",context.getAttribute("input.common-header.sub-request-id")); - return commonHeader; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java deleted file mode 100644 index fff43cbf5..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImpl.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.common.JsonDgUtil; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.util.JsonUtil; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - - -public class JsonDgUtilImpl implements JsonDgUtil { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class); - - private static final ThreadLocal DATE_TIME_PARSER_THREAD_LOCAL = new ThreadLocal() { - protected SimpleDateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; - - @Override - public void flatAndAddToContext(Map params, SvcLogicContext ctx) throws APPCException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to flatAndAddToContext with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - try { - String paramName = Constants.PAYLOAD; - String payload = params.get(paramName); - if (payload == "") - payload = ctx.getAttribute("input.payload"); - if (!StringUtils.isEmpty(payload)) { - Map flatMap = JsonUtil.convertJsonStringToFlatMap(payload); - if (flatMap != null && flatMap.size() > 0) { - for (Map.Entry entry : flatMap.entrySet()) { - ctx.setAttribute(entry.getKey(), entry.getValue()); - } - } - } else { - logger.warn("input payload param value is empty (\"\") or null"); - } - } catch (Exception e) { - logger.error(e.toString()); - String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED,params.get(Constants.PAYLOAD)); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(e); - } - } - - @Override - public void generateOutputPayloadFromContext(Map params, SvcLogicContext ctx) throws APPCException{ - if (logger.isTraceEnabled()) { - logger.trace("Entering to generateOutputPayloadFromContext with SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - - try { - Set keys = ctx.getAttributeKeySet(); - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode JsonNode = objectMapper.createObjectNode(); - for (String key : keys) { - if(key.startsWith(Constants.OUTPUT_PAYLOAD+".")){ - String objkey= key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", ""); - if(objkey.contains("[") && objkey.contains("]")){ - ArrayNode arrayNode; - String arrayKey = objkey.substring(0,objkey.indexOf('[')); - int arrayIndex = Integer.parseInt(objkey.substring(objkey.indexOf('[')+1,objkey.indexOf(']'))); - if(JsonNode.has(arrayKey)){ - arrayNode = (ArrayNode)JsonNode.get(arrayKey); - arrayNode.insert(arrayIndex,ctx.getAttribute(key)); - }else { - arrayNode = objectMapper.createArrayNode(); - arrayNode.insert(arrayIndex,ctx.getAttribute(key)); - JsonNode.put(arrayKey,arrayNode); - } - }else { - JsonNode.put(objkey, ctx.getAttribute(key)); - } - } - } - if(JsonNode.size()>0) { - ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(JsonNode)); - } - } catch (Exception e) { - logger.error(e.toString()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw new APPCException(e); - } - - } - - @Override - public void cvaasFileNameAndFileContentToContext(Map params, SvcLogicContext ctx) - throws APPCException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = " - + ObjectUtils.toString(ctx)); - } - - String vnfId = null; - try { - String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH); - String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID); - - /* - * File name - */ - vnfId = params.get("vnf-id"); - long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis(); - - ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_" - + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json"); - - /* - * File content - */ - - String uploadDate = ctx.getAttribute("running-config.upload-date"); - long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime(); - - ObjectMapper objectMapper = new ObjectMapper(); - ObjectNode jsonNode = objectMapper.createObjectNode(); - jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id")); - jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id")); - jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id")); - jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description")); - jsonNode.put("ACTION", ctx.getAttribute("running-config.action")); - jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp); - jsonNode.put("UPLOAD_DATE", uploadDate); - jsonNode.put("VNF_ID", vnfId); - jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name")); - jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name")); - jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type")); - jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type")); - jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address")); - jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator")); - jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete")); - jsonNode.put("CONTENT", ctx.getAttribute("running-config.content")); - - ctx.setAttribute(Constants.CVAAS_FILE_CONTENT, - objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)); - - } catch (Exception e) { - String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId; - logger.error(errorMessage, e); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); - throw new APPCException(e); - } - } - - @Override - public void checkFileCreated(Map params, SvcLogicContext ctx) throws APPCException { - String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME); - File file = new File(filePath); - - if (!file.exists()) { - String vnfId = params.get("vnf-id"); - String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId; - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage); - throw new APPCException(errorMessage); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java deleted file mode 100644 index ad0884b94..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/LegacyUtilImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Map; - -import org.onap.appc.dg.common.LegacyUtil; -import org.onap.appc.dg.common.utils.JSONUtil; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class LegacyUtilImpl implements LegacyUtil { - - @Override public void prepareRequest(Map params, SvcLogicContext ctx) throws APPCException { - ctx.setAttribute(Constants.LegacyAttributes.Action.getValue(), ctx.getAttribute(Constants.LCMAttributes.Action.getValue()).toLowerCase()); - - String payloadStr = ctx.getAttribute(Constants.LCMAttributes.Payload.getValue()); - Map payloads = JSONUtil.extractPlainValues(payloadStr, - Constants.LCMAttributes.VMID.getValue(), Constants.LCMAttributes.IdentityURL.getValue(), Constants.LCMAttributes.TenantID.getValue(), - Constants.LCMAttributes.SkipHypervisorCheck.getValue()); - - ctx.setAttribute(Constants.LegacyAttributes.VMID.getValue(), payloads.get(Constants.LCMAttributes.VMID.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.IdentityURL.getValue(), payloads.get(Constants.LCMAttributes.IdentityURL.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.TenantID.getValue(), payloads.get(Constants.LCMAttributes.TenantID.getValue())); - ctx.setAttribute(Constants.LegacyAttributes.SkipHypervisorCheck.getValue(), payloads.get(Constants.LCMAttributes.SkipHypervisorCheck.getValue())); - - } - - @Override - public void convertPositiveResponse(Map params, SvcLogicContext ctx) throws APPCException { - } - - @Override - public void convertNegativeResponse(Map params, SvcLogicContext ctx) throws APPCException { - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java deleted file mode 100644 index 66ac82fcb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/OutputMessagePluginImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -import org.onap.appc.dg.common.OutputMessagePlugin; -import org.onap.appc.exceptions.APPCException; - -import static org.apache.commons.lang3.StringUtils.isEmpty; - -public class OutputMessagePluginImpl implements OutputMessagePlugin { - - @Override - public void outputMessageBuilder(Map params, SvcLogicContext ctx) throws APPCException { - String errorDescription, eventDescription; - - //making output.status.message - errorDescription = params.get(Constants.ATTRIBUTE_ERROR_MESSAGE); - eventDescription = params.get(Constants.EVENT_MESSAGE); - - addToContextIfNotContains(errorDescription , eventDescription, ctx); - - //making event-message - - if (!isEmpty(eventDescription)) { - ctx.setAttribute(Constants.EVENT_MESSAGE, eventDescription); - } else { - ctx.setAttribute(Constants.EVENT_MESSAGE, ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); - } - } - - public static void addToContextIfNotContains(String errorDescription, String eventDescription, SvcLogicContext ctx) { - if (!isEmpty(errorDescription)){ - if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, errorDescription); - }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(errorDescription)) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + errorDescription); - } - } - if (!isEmpty(eventDescription)){ - if (isEmpty(ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE))) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, eventDescription); - }else if (!ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE).contains(eventDescription)) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, ctx.getAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE) + " | " + eventDescription); - } - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java deleted file mode 100644 index 790547f37..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverDataReaderFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class ResolverDataReaderFactory { - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - private static class ReferenceHolder{ - private static final AbstractResolverDataReader VNFC_RESOLVER_DATA_READER = new VNFCResolverDataReader(); - - private static final AbstractResolverDataReader VNF_RESOLVER_DATA_READER = new VNFResolverDataReader(); - } - - public static AbstractResolverDataReader createResolverDataReader(String resolverType){ - if(resolverType.equalsIgnoreCase("VNF")){ - return ReferenceHolder.VNF_RESOLVER_DATA_READER; - }else if(resolverType.equalsIgnoreCase("VNFC")){ - return ReferenceHolder.VNFC_RESOLVER_DATA_READER; - }else { - return null; - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java deleted file mode 100644 index e39546846..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/ResolverFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class ResolverFactory { - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - private static class ReferenceHolder{ - private static final AbstractResolver VNFC_RESOLVER = new VNFCResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); - private static final AbstractResolver VNF_RESOLVER = new VNFResolver(configuration.getIntegerProperty("org.onap.appc.workflow.resolver.refresh_interval", 300)); - } - - public static AbstractResolver createResolver(String resolverType){ - if(resolverType.equalsIgnoreCase("VNF")){ - return ReferenceHolder.VNF_RESOLVER; - }else if(resolverType.equalsIgnoreCase("VNFC")){ - return ReferenceHolder.VNFC_RESOLVER; - }else { - return null; - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java deleted file mode 100644 index 304bdf882..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCDgResolverPluginImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Map; - -public class VNFCDgResolverPluginImpl implements org.onap.appc.dg.common.VNFCDgResolverPlugin { - @Override - public void resolveVNFCDg(Map params, SvcLogicContext ctx) throws APPCException { - DgResolverPluginImpl dgResolverPlugin = new DgResolverPluginImpl(); - params.put("DGResolutionType" , "VNFC"); - dgResolverPlugin.resolveDg(params,ctx); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java deleted file mode 100644 index e2893951b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolver.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesContext; - - -public class VNFCResolver extends AbstractResolver { - VNFCResolver(int interval) { - super(interval); - } - - @Override - protected FlowKey resolve(String... args) { - if(args.length !=4){ - throw new IllegalStateException(args.toString()); - } - return resolve(args[0],args[1],args[2],args[3]); - } - - protected FlowKey resolve(final String action, final String vnfType, final String vnfcType, final String apiVersion) { - RankedAttributesContext context = new RankedAttributesContext() { - @Override - public Object getAttributeValue(String name) { - switch (name) { - case "action": - return action; - case "api_version": - return apiVersion; - case "vnf_type": - return vnfType; - case "vnfc_type": - return vnfcType; - default: - throw new IllegalStateException(name); - } - } - }; - - FlowKey wfKey = resolver("VNFC").resolve(context); - - return wfKey; - } -} - diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java deleted file mode 100644 index c78da685c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFCResolverDataReader.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Arrays; -import java.util.Collection; - -public class VNFCResolverDataReader extends AbstractResolverDataReader { - @Override - protected Collection getAttributeNames() { - return Arrays.asList("action","api_version", "vnf_type", "vnfc_type"); - } - - @Override - protected String getQueryStmt() { - return "select vnf_type,vnfc_type,api_version,action,dg_name,dg_version,dg_module FROM VNFC_DG_MAPPING"; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java deleted file mode 100644 index c46a9c227..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFConfiguratorImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.Constants; -import org.onap.appc.dg.common.VNFConfigurator; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.impl.MDSALStoreFactory; -import org.onap.appc.mdsal.objects.BundleInfo; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.apache.commons.lang3.StringUtils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; - - -public class VNFConfiguratorImpl implements VNFConfigurator { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(VNFConfiguratorImpl.class); - private static final String STATUS = "STATUS"; - private static final String FAILURE = "FAILURE"; - private static final String SUCCESS = "SUCCESS"; - private static final String ERROR_MESSAGE = "ERROR_MESSAGE"; - - @Override - public void storeConfig(Map params, SvcLogicContext context) throws APPCException { - String uniqueId = params.get("uniqueId"); - String yang = params.get("yang"); - String configJSON = params.get("configJSON"); - String requestId = params.get("requestId"); - String prefix = params.get("prefix"); - prefix = StringUtils.isEmpty(prefix)? "":prefix+"."; - - MDSALStore store = MDSALStoreFactory.createMDSALStore(); - - logger.debug("Inputs Received : uniqueId = " + uniqueId + - " , yang = " + yang + - " , configJSON = " + configJSON + - " , requestId = " + requestId + - " , prefix = " +prefix); - - try { - - if(StringUtils.isEmpty(uniqueId) - ||StringUtils.isEmpty(yang) - || StringUtils.isEmpty(configJSON) - || StringUtils.isEmpty(requestId)){ - throw new APPCException("One or more input parameters are empty : uniqueId = " + uniqueId + " " + - ", yang = " + yang + - " , configJSON = " + configJSON + - " , requestId = " + requestId); - } - - Date revision = new SimpleDateFormat(Constants.YANG_REVISION_FORMAT).parse(Constants.YANG_REVISION); - - boolean isYangAlreadyLoaded = store.isModulePresent(uniqueId,revision); - - if(!isYangAlreadyLoaded){ - BundleInfo bundleInfo = getBundleInfo(uniqueId); - store.storeYangModule(yang,bundleInfo); - } - store.storeJson(uniqueId, requestId , configJSON); - context.setAttribute(prefix + STATUS, SUCCESS); - } catch (ParseException e) { - String errorMessage ="Error parsing the date : " + Constants.YANG_REVISION + " into format " + Constants.YANG_REVISION_FORMAT; - logger.error(errorMessage,e); - context.setAttribute(prefix + STATUS, FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - throw new APPCException(e.getMessage()); - }catch (MDSALStoreException e){ - String errorMessage = "Error while adding yang to MD-SAL store." + e.getMessage(); - logger.error(errorMessage,e); - context.setAttribute(prefix + STATUS,FAILURE); - context.setAttribute(prefix + ERROR_MESSAGE, errorMessage); - throw new APPCException(e.getMessage()); - } - - } - - private BundleInfo getBundleInfo(String uniqueId) { - BundleInfo bundleInfo = new BundleInfo(); - bundleInfo.setDescription(uniqueId); - bundleInfo.setName(uniqueId); - bundleInfo.setLocation(uniqueId); - return bundleInfo; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java deleted file mode 100644 index 501ad0713..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolver.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.rankingframework.RankedAttributesContext; - -public class VNFResolver extends AbstractResolver { - VNFResolver(int interval) { - super(interval); - } - - @Override - protected FlowKey resolve(String... args) { - return resolve(args[0],args[1],args[2],args[3]); - } - - - protected FlowKey resolve(final String action, final String vnfType, final String vnfVersion, final String apiVersion) { - RankedAttributesContext context = new RankedAttributesContext() { - @Override - public Object getAttributeValue(String name) { - switch (name) { - case "action": - return action; - case "api_version": - return apiVersion; - case "vnf_type": - return vnfType; - case "vnf_version": - return vnfVersion; - default: - throw new IllegalStateException(name); - } - } - }; - - FlowKey wfKey = resolver("VNF").resolve(context); - - return wfKey; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java deleted file mode 100644 index 3c4cf837e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VNFResolverDataReader.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Arrays; -import java.util.Collection; - -/** - * @since January 19,2017 - */ -public class VNFResolverDataReader extends AbstractResolverDataReader { - @Override - protected Collection getAttributeNames() { - return Arrays.asList("action","api_version", "vnf_type", "vnf_version"); - } - - @Override - protected String getQueryStmt() { - return "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING"; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java deleted file mode 100644 index 65b364f62..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/impl/VnfExecutionFlowImpl.java +++ /dev/null @@ -1,271 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.*; - -import org.onap.appc.dg.common.VnfExecutionFlow; -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; -import org.onap.appc.i18n.Msg; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public class VnfExecutionFlowImpl implements VnfExecutionFlow { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(VnfExecutionFlowImpl.class); - - public VnfExecutionFlowImpl(){ - - } - - @Override - public void getVnfExecutionFlowData(Map params, SvcLogicContext context) { - String dependencyType = params.get(Constants.DEPENDENCY_TYPE); - String flowStrategy = params.get(Constants.FLOW_STRATEGY); - DependencyModelIdentifier modelIdentifier = readDependencyModelIdentifier(params); - VnfcDependencyModel dependencyModel = null; - try { - validateInput(dependencyType, flowStrategy, params); - - if (logger.isTraceEnabled()) { - logger.trace("Input received from DG Node : dependencyType = " + dependencyType + - " , flowStrategy = " + flowStrategy + - ", DependencyModelIdentifier = " + modelIdentifier.toString()); - } - - DependencyManager dependencyManager = DependencyModelFactory.createDependencyManager(); - - - dependencyModel = dependencyManager.getVnfcDependencyModel( - modelIdentifier, DependencyTypes.findByString(dependencyType)); - } catch (DependencyModelNotFound e) { - String msg = EELFResourceManager.format(Msg.DEPENDENCY_MODEL_NOT_FOUND,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - context.setAttribute("dependencyModelFound","false"); - return; - } catch (InvalidDependencyModel e){ - String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - }catch (RuntimeException e){ - logger.error(e.getMessage()); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); - throw e; - } - - - context.setAttribute("dependencyModelFound","true"); - if(logger.isDebugEnabled()){ - logger.debug("Dependency Model = " +dependencyModel); - } - logger.info("Building Inventory Model from DG context"); - InventoryModel inventoryModel = readInventoryModel(context); - if(logger.isDebugEnabled()){ - logger.debug("Inventory Model = " +inventoryModel); - } - - if(logger.isDebugEnabled()){ - logger.debug("Validating inventory model with dependency model"); - } - try { - validateInventoryModelWithDependencyModel(dependencyModel, inventoryModel); - }catch (RuntimeException e){ - logger.error(e.getMessage()); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,e.getMessage()); - throw e; - } - logger.info("Creating flow builder"); - FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder( - FlowStrategies.findByString(flowStrategy)); - - logger.info("Building Vnf flow model"); - VnfcFlowModel flowModel = null; - try{ - flowModel = flowBuilder.buildFlowModel(dependencyModel,inventoryModel); - } - catch (InvalidDependencyModel e){ - String msg = EELFResourceManager.format(Msg.INVALID_DEPENDENCY_MODEL,params.get(Constants.VNF_TYPE), e.getMessage()); - logger.error(msg); - context.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - } - - // remove VNFCs from the flow model where vserver list is empty - reconcileFlowModel(flowModel); - populateContext(flowModel,context); - if(logger.isDebugEnabled()){ - logContext(context); - } - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVnfExecutionFlowData","VNF ID " + params.get(Constants.VNF_TYPE)); - context.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - } - - private void validateInput(String dependencyType, String flowStrategy, Map params) { - DependencyTypes dependencyTypes = DependencyTypes.findByString(dependencyType); - if(dependencyTypes == null){ - throw new RuntimeException("Dependency type from the input : " + dependencyType +" is invalid."); - } - FlowStrategies flowStrategies = FlowStrategies.findByString(flowStrategy); - if(flowStrategies == null){ - throw new RuntimeException("Flow Strategy from the input : " + flowStrategy +" is invalid."); - } - String vnfType = params.get(Constants.VNF_TYPE); - if(vnfType ==null || vnfType.length() ==0){ - throw new RuntimeException("Vnf Type is not passed in the input"); - } - String vnfVersion = params.get(Constants.VNF_VERION); - if(vnfVersion == null || vnfVersion.length() ==0){ - throw new RuntimeException("Vnf Version not found"); - } - } - - private void logContext(SvcLogicContext context) { - for(String key:context.getAttributeKeySet()){ - logger.debug(key + " = " + context.getAttribute(key) + "\n" ); - } - } - - private void populateContext(VnfcFlowModel flowModel, SvcLogicContext context) { - int flowIndex=0; - Iterator> iterator = flowModel.getModelIterator(); - while (iterator.hasNext()){ - for(Vnfc vnfc:iterator.next()){ - context.setAttribute("vnfcFlow["+flowIndex+"].vnfcName",vnfc.getVnfcName()); - context.setAttribute("vnfcFlow["+flowIndex+"].vnfcType",vnfc.getVnfcType()); - context.setAttribute("vnfcFlow["+flowIndex+"].resilienceType",vnfc.getResilienceType()); - context.setAttribute("vnfcFlow["+flowIndex+"].vmCount",Integer.toString(vnfc.getVserverList().size())); - int vmIndex =0; - for(Vserver vm :vnfc.getVserverList()){ - context.setAttribute("vnfcFlow["+flowIndex+"].vm["+vmIndex+"].url",vm.getUrl()); - vmIndex++; - } - flowIndex++; - } - } - context.setAttribute("vnfcFlowCount",Integer.toString(flowIndex)); - } - - private InventoryModel readInventoryModel(SvcLogicContext context) { - String vnfId = context.getAttribute("input.action-identifiers.vnf-id"); - String vnfType = context.getAttribute("vnf.type"); - String vnfVersion = context.getAttribute("vnf.version"); - String vnfcCountStr = context.getAttribute("vnf.vnfcCount"); - Integer vnfcCount = Integer.parseInt(vnfcCountStr); - - Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion); - - for(Integer i=0;i params) { - String vnfType = params.get(Constants.VNF_TYPE); - String catalogVersion = params.get(Constants.VNF_VERION); - return new DependencyModelIdentifier(vnfType,catalogVersion); - } - - private void validateInventoryModelWithDependencyModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - Set dependencyModelVnfcSet = new HashSet(); - Set dependencyModelMandatoryVnfcSet = new HashSet(); - Set inventoryModelVnfcsSet = new HashSet(); - - for (Node node : dependencyModel.getDependencies()) { - dependencyModelVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); - if (node.getChild().isMandatory()) { - dependencyModelMandatoryVnfcSet.add(node.getChild().getVnfcType().toLowerCase()); - } - } - - for (Vnfc vnfc : inventoryModel.getVnf().getVnfcs()) { - inventoryModelVnfcsSet.add(vnfc.getVnfcType().toLowerCase()); - } - - // if dependency model and inventory model contains same set of VNFCs, validation succeed and hence return - if (dependencyModelVnfcSet.equals(inventoryModelVnfcsSet)) { - return; - } - - if (inventoryModelVnfcsSet.size() >= dependencyModelVnfcSet.size()) { - Set difference = new HashSet(inventoryModelVnfcsSet); - difference.removeAll(dependencyModelVnfcSet); - logger.error("Dependency model is missing following vnfc type(s): " + difference); - throw new RuntimeException("Dependency model is missing following vnfc type(s): " + difference); - } else { - Set difference = new HashSet(dependencyModelVnfcSet); - difference.removeAll(inventoryModelVnfcsSet); - difference.retainAll(dependencyModelMandatoryVnfcSet); - if (difference.size() > 0) { - logger.error("Inventory model is missing following mandatory vnfc type(s): " + difference); - throw new RuntimeException("Inventory model is missing following mandatory vnfc type(s): " + difference); - } - } - } - - private void reconcileFlowModel(VnfcFlowModel flowModel) { - Iterator> flowIterator = flowModel.getModelIterator(); - while (flowIterator.hasNext()) { - Iterator vnfcIterator = flowIterator.next().iterator(); - while (vnfcIterator.hasNext()) { - Vnfc vnfc = vnfcIterator.next(); - if (vnfc.getVserverList().size() == 0) { - if (logger.isDebugEnabled()) { - logger.debug("No vservers present for Vnfc type: " + vnfc.getVnfcType() + ". Hence, removing it from the flow model."); - } - vnfcIterator.remove(); - } - } - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java deleted file mode 100644 index 1572e726b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/objects/ConnectionDetails.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.objects; - - - -public class ConnectionDetails { - - private String host; - private int port; - private String username; - private String password; - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java deleted file mode 100644 index 38012b1bd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JAXBUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.utils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; - - - -public class JAXBUtil { - - public static T toObject(String xml, Class type) throws JAXBException { - - //create JAXB context - JAXBContext context = JAXBContext.newInstance(type); - - //Create Unmarshaller using JAXB context - Unmarshaller unmarshaller = context.createUnmarshaller(); - - InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes()); - BufferedReader reader = new BufferedReader(new InputStreamReader(xmlInputStream)); - - return type.cast(unmarshaller.unmarshal(reader)); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java b/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java deleted file mode 100644 index 388295a7d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/java/org/openecomp/appc/dg/common/utils/JSONUtil.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.utils; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.Reader; -import java.util.*; - - -public class JSONUtil { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - public static T fromJson(String json, Class clazz) { - - try { - return OBJECT_MAPPER.readValue(json, clazz); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static T fromJson(Reader reader, Class clazz) { - - try { - return OBJECT_MAPPER.readValue(reader, clazz); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static String toJson(Object object) { - - try { - return OBJECT_MAPPER.writeValueAsString(object); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static Map extractPlainValues(String json, String ... names) { - if (null == names) return Collections.emptyMap(); - Map values = new HashMap<>(); - try { - final JsonNode jsonNode = OBJECT_MAPPER.readTree(json); - for (String name : names) { - values.put(name, jsonNode.path(name).asText()); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - return values; - } - - - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..ec2a2b709 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,50 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.netconfctl=test +org.onap.appc.netconf.db.pass.netconfctl=123456 + +org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +org.onap.appc.netconf.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.sdnctl=test +org.onap.appc.netconf.db.pass.sdnctl=123456 + +### ### +### Properties commented out below provided in appc.properties ### +### ### +#event.pool.members= +event.topic.write=APPC-TEST1 +event.client.key=VIlbtVl6YLhNUrtU +event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT +#restconf.user= +#restconf.pass= + +org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties b/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index ec2a2b709..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,50 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.netconf.db.user.netconfctl=test -org.onap.appc.netconf.db.pass.netconfctl=123456 - -org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -org.onap.appc.netconf.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.netconf.db.user.sdnctl=test -org.onap.appc.netconf.db.pass.sdnctl=123456 - -### ### -### Properties commented out below provided in appc.properties ### -### ### -#event.pool.members= -event.topic.write=APPC-TEST1 -event.client.key=VIlbtVl6YLhNUrtU -event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT -#restconf.user= -#restconf.pass= - -org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java new file mode 100644 index 000000000..7c36360f8 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/DCAEReporterPluginImplTest.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import java.util.HashMap; +import java.util.Map; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DCAEReporterPluginImpl.class, FrameworkUtil.class}) +public class DCAEReporterPluginImplTest { + private SvcLogicContext ctx; + private Map params; + + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref = Mockito.mock(ServiceReference.class); + + @InjectMocks + private DCAEReporterPluginImpl dcaeReporterPlugin; + @Spy + private EventSenderMock eventSender = new EventSenderMock(); + + private String apiVer = "2.0.0"; + private String requestId = "123"; + private String error = "test-error"; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(eventSender); + } + + @Test + public void testReportErrorDescriptionNullBwcModeFalse() throws Exception { + ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("output.status.message", null); + ctx.setAttribute("input.common-header.api-ver", apiVer); + ctx.setAttribute("input.common-header.request-id", requestId); + + errorReasonNullAssert(); + } + + @Test + public void testReportBwcFalse() throws Exception { + ctx = new SvcLogicContext(); + params = new HashMap<>(); + ctx.setAttribute("isBwcMode", "false"); + params.put("output.status.message", error); + ctx.setAttribute("input.common-header.api-ver", apiVer); + ctx.setAttribute("input.common-header.request-id", requestId); + + positiveAssert(); + } + + private void errorReasonNullAssert() throws APPCException { + dcaeReporterPlugin.report(params, ctx); + MessageDestination destination = eventSender.getDestination(); + EventMessage msg = eventSender.getMsg(); + Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); + Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); + Assert.assertEquals("wrong error message", "Unknown", msg.getEventStatus().getReason()); + Assert.assertEquals("wrong destination", destination.name(), "DCAE"); + } + + private void positiveAssert() throws APPCException { + dcaeReporterPlugin.report(params, ctx); + MessageDestination destination = eventSender.getDestination(); + EventMessage msg = eventSender.getMsg(); + Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); + Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); + Assert.assertEquals("wrong error message", error, msg.getEventStatus().getReason()); + Assert.assertEquals("wrong destination", destination.name(), "DCAE"); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java new file mode 100644 index 000000000..cc30d3aea --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/EventSenderMock.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import java.util.Map; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class EventSenderMock implements EventSender { + EventMessage msg; + MessageDestination destination; + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg) { + if (destination != null && msg != null){ + this.msg = msg; + this.destination = destination; + return true; + } + else{ + return false; + } + } + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { + return false; + } + + @Override + public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { + return false; + } + + public EventMessage getMsg() { + return msg; + } + + public MessageDestination getDestination() { + return destination; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java new file mode 100644 index 000000000..6f5a0f13d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/JsonDgUtilImplTest.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import ch.qos.logback.core.Appender; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.dg.common.impl.JsonDgUtilImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; + +public class JsonDgUtilImplTest { + + private final Appender appender = mock(Appender.class); + + + @Test + public void testFlatAndAddToContext() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, payload); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); + Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); + + + + } + + + @Test + public void testFlatAndAddToContextNegativeWrongPayload() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, payload); + try { + jsonDgUtil.flatAndAddToContext(params, ctx); + + } catch (APPCException e) { + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + Assert.assertNotNull(ctx.getAttribute("error-message")); + } + + + } + + + @Test + public void testFlatAndAddToContextPayloadFromContext() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueValue = "test-value"; + String testValueKey2 = "test-key2"; + String testValueValue2 = "test-value2"; + String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, ""); + ctx.setAttribute("input.payload", payload); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); + Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); + } + + @Test + public void testFlatAndAddToContextNegativeNullPayload() throws Exception { + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String testValueKey = "test-key"; + String testValueKey2 = "test-key2"; + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + jsonDgUtil.flatAndAddToContext(params, ctx); + + + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + } + + + @Test + public void testFlatAndAddToContextNegativeEmptyPayload() throws Exception { + + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "payload"; + String testValueKey = "test-key"; + String testValueKey2 = "test-key2"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + params.put(key, ""); + jsonDgUtil.flatAndAddToContext(params, ctx); + + Assert.assertNull(ctx.getAttribute(testValueKey)); + Assert.assertNull(ctx.getAttribute(testValueKey2)); + } + + + @Test + public void testGenerateOutputPayloadFromContext() throws Exception { + + JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); + String key = "output.payload"; + String key1 = "output.payload.test-key[0]"; + String key2 = "output.payload.test-key[1]"; + String testValueKey1 = "value1"; + String testValueKey2 = "value2"; + + String key3 = "output.payload.test-key3"; + String testValueKey3 = "value3"; + + SvcLogicContext ctx = new SvcLogicContext(); + Map params = new HashMap<>(); + ctx.setAttribute(key1, testValueKey1); + ctx.setAttribute(key2, testValueKey2); + ctx.setAttribute(key3, testValueKey3); + jsonDgUtil.generateOutputPayloadFromContext(params, ctx); + + Assert.assertNotNull(ctx.getAttribute(key)); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java new file mode 100644 index 000000000..ca3e7f5e2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVNFConfiguratorImpl.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import org.onap.appc.dg.common.VNFConfigurator; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.impl.MDSALStoreFactory; +import org.onap.appc.mdsal.impl.MDSALStoreImpl; +import org.onap.appc.mdsal.objects.BundleInfo; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MDSALStoreImpl.class,MDSALStoreFactory.class}) +public class TestVNFConfiguratorImpl { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVNFConfiguratorImpl.class); + + @Before + public void setUp() { + logger.setLevel(EELFLogger.Level.DEBUG); + } + + @Test(expected = APPCException.class) + public void testValidations() throws APPCException { + VNFConfigurator configurator = new VNFConfiguratorImpl(); + Map params = new HashMap(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + configurator.storeConfig(params,new SvcLogicContext()); + } + + @Test + public void testYangPresentScenario() throws APPCException { + + VNFConfigurator configurator = new VNFConfiguratorImpl(); + PowerMockito.mockStatic(MDSALStoreFactory.class); + MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); + PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); + PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(true); + + Map params = new HashMap(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + params.put("requestId","requestId"); + configurator.storeConfig(params,new SvcLogicContext()); + } + + @Test + public void testYangAbsentScenario() throws Exception { + + VNFConfigurator configurator = new VNFConfiguratorImpl(); + PowerMockito.mockStatic(MDSALStoreFactory.class); + + MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); + + PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); + + PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(false); + + PowerMockito.doNothing().when(mdsalStore).storeYangModule(Matchers.anyString(),(BundleInfo)Matchers.anyObject()); + + Map params = new HashMap<>(); + params.put("uniqueId","uniqueId"); + params.put("yang","yang"); + params.put("configJSON","configJSON"); + params.put("requestId","requestId"); + configurator.storeConfig(params,new SvcLogicContext()); + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java new file mode 100644 index 000000000..bad862030 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/onap/appc/dg/common/impl/TestVnfExecutionFlowImpl.java @@ -0,0 +1,420 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.common.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.onap.appc.dg.common.VnfExecutionFlow; +import org.onap.appc.dg.common.impl.Constants; +import org.onap.appc.dg.common.impl.VnfExecutionFlowImpl; +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({TestVnfExecutionFlowImpl.class, FrameworkUtil.class,DependencyManager.class,DependencyModelFactory.class}) +public class TestVnfExecutionFlowImpl { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVnfExecutionFlowImpl.class); + + @Before + public void setUp() { + logger.setLevel(EELFLogger.Level.DEBUG); + } + + @Test + public void testPositiveFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testComplexFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContextForComplexDependency(); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test(expected = InvalidDependencyModel.class) + public void testCycleFlow() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContextForComplexDependency(); + VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + private VnfcDependencyModel readCyclicDependencyModel() { + + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + cNode.addParent(b); + + bNode.addParent(d); + dNode.addParent(c); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + + } + + private SvcLogicContext prepareContextForComplexDependency() { + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("input.action-identifiers.vnf-id","1"); + context.setAttribute("vnf.type","vSCP"); + context.setAttribute("vnf.vnfcCount","7"); + + context.setAttribute("vnf.vnfc[0].name","A"); + context.setAttribute("vnf.vnfc[0].type","A"); + context.setAttribute("vnf.vnfc[0].vm_count","2"); + context.setAttribute("vnf.vnfc[0].vm[0].url","A1"); + context.setAttribute("vnf.vnfc[0].vm[1].url","A2"); + + context.setAttribute("vnf.vnfc[1].name","B"); + context.setAttribute("vnf.vnfc[1].type","B"); + context.setAttribute("vnf.vnfc[1].vm_count","5"); + context.setAttribute("vnf.vnfc[1].vm[0].url","B1"); + context.setAttribute("vnf.vnfc[1].vm[1].url","B2"); + context.setAttribute("vnf.vnfc[1].vm[2].url","B3"); + context.setAttribute("vnf.vnfc[1].vm[3].url","B4"); + context.setAttribute("vnf.vnfc[1].vm[4].url","B5"); + + context.setAttribute("vnf.vnfc[2].name","C"); + context.setAttribute("vnf.vnfc[2].type","C"); + context.setAttribute("vnf.vnfc[2].vm_count","4"); + context.setAttribute("vnf.vnfc[2].vm[0].url","C1"); + context.setAttribute("vnf.vnfc[2].vm[1].url","C2"); + context.setAttribute("vnf.vnfc[2].vm[2].url","C3"); + context.setAttribute("vnf.vnfc[2].vm[3].url","C4"); + + context.setAttribute("vnf.vnfc[3].name","D"); + context.setAttribute("vnf.vnfc[3].type","D"); + context.setAttribute("vnf.vnfc[3].vm_count","3"); + context.setAttribute("vnf.vnfc[3].vm[0].url","D1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","D2"); + context.setAttribute("vnf.vnfc[3].vm[2].url","D3"); + + context.setAttribute("vnf.vnfc[4].name","E"); + context.setAttribute("vnf.vnfc[4].type","E"); + context.setAttribute("vnf.vnfc[4].vm_count","2"); + context.setAttribute("vnf.vnfc[4].vm[0].url","E1"); + context.setAttribute("vnf.vnfc[4].vm[1].url","E2"); + + context.setAttribute("vnf.vnfc[5].name","F"); + context.setAttribute("vnf.vnfc[5].type","F"); + context.setAttribute("vnf.vnfc[5].vm_count","1"); + context.setAttribute("vnf.vnfc[5].vm[0].url","F1"); + + context.setAttribute("vnf.vnfc[6].name","G"); + context.setAttribute("vnf.vnfc[6].type","G"); + context.setAttribute("vnf.vnfc[6].vm_count","1"); + context.setAttribute("vnf.vnfc[6].vm[0].url","G1"); + + + return context; + } + + private VnfcDependencyModel readComplexDependencyModel() { + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + + dNode.addParent(b); + eNode.addParent(b); + gNode.addParent(b); + + fNode.addParent(c); + + gNode.addParent(f); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + } + + private VnfcDependencyModel readDependencyModel() { + + Vnfc smp = new Vnfc("SMP","Active-Passive",null); + Vnfc be = new Vnfc("BE","Active-Active",null); + Vnfc fe = new Vnfc("FE","Active-Active",null); + + + Node smpNode = new Node(smp); + Node beNode = new Node(be); + Node feNode = new Node(fe); + + beNode.addParent(smp); + feNode.addParent(be); +// smpNode.addParent(fe); + + Set> dependencies = new HashSet<>(); + dependencies.add(smpNode); + dependencies.add(feNode); + dependencies.add(beNode); + + return new VnfcDependencyModel(dependencies); + } + + private Map prepareParams() { + Map params = new HashMap<>(); + params.put(Constants.DEPENDENCY_TYPE,"RESOURCE"); + params.put(Constants.FLOW_STRATEGY,"FORWARD"); + + params.put(Constants.VNF_TYPE,"vSCP"); + params.put(Constants.VNF_VERION,"1.00"); + return params; + } + + private SvcLogicContext prepareContext() { + SvcLogicContext context = new SvcLogicContext(); + context.setAttribute("input.action-identifiers.vnf-id","1"); + context.setAttribute("vnf.type","vSCP"); + context.setAttribute("vnf.vnfcCount","3"); + + context.setAttribute("vnf.vnfc[0].name","SMPname"); + context.setAttribute("vnf.vnfc[0].type","SMP"); + context.setAttribute("vnf.vnfc[0].vm_count","2"); + context.setAttribute("vnf.vnfc[0].vm[0].url","SMP_URL1"); + context.setAttribute("vnf.vnfc[0].vm[1].url","SMP_URL2"); + + context.setAttribute("vnf.vnfc[1].name","BEname"); + context.setAttribute("vnf.vnfc[1].type","BE"); + context.setAttribute("vnf.vnfc[1].vm_count","5"); + context.setAttribute("vnf.vnfc[1].vm[0].url","BE_URL1"); + context.setAttribute("vnf.vnfc[1].vm[1].url","BE_URL2"); + context.setAttribute("vnf.vnfc[1].vm[2].url","BE_URL3"); + context.setAttribute("vnf.vnfc[1].vm[3].url","BE_URL4"); + context.setAttribute("vnf.vnfc[1].vm[4].url","BE_URL5"); + + context.setAttribute("vnf.vnfc[2].name","FEname"); + context.setAttribute("vnf.vnfc[2].type","FE"); + context.setAttribute("vnf.vnfc[2].vm_count","2"); + context.setAttribute("vnf.vnfc[2].vm[0].url","FE_URL1"); + context.setAttribute("vnf.vnfc[2].vm[1].url","FE_URL2"); + + return context; + } + + @Test(expected = RuntimeException.class) + public void testMissingVnfcTypeInDependencyModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + context.setAttribute("vnf.vnfc[3].name","XEname"); + context.setAttribute("vnf.vnfc[3].type","XE"); + context.setAttribute("vnf.vnfc[3].vm_count","2"); + context.setAttribute("vnf.vnfc[3].vm[0].url","XE_URL1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","XE_URL2"); + context.setAttribute("vnf.vnfcCount","4"); + + VnfcDependencyModel dependencyModel = readDependencyModel(); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test(expected = RuntimeException.class) + public void testMissingMandatoryVnfcTypeInInventoryModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, true); + Node xeNode = new Node(xe); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testMissingOptionalVnfcTypeInInventoryModel() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, false); + Node xeNode = new Node(xe); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } + + @Test + public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild() throws DependencyModelNotFound { + Map params = prepareParams(); + SvcLogicContext context = prepareContext(); + context.setAttribute("vnf.vnfc[3].name","YEname"); + context.setAttribute("vnf.vnfc[3].type","YE"); + context.setAttribute("vnf.vnfc[3].vm_count","2"); + context.setAttribute("vnf.vnfc[3].vm[0].url","YE_URL1"); + context.setAttribute("vnf.vnfc[3].vm[1].url","YE_URL2"); + context.setAttribute("vnf.vnfcCount","4"); + + VnfcDependencyModel dependencyModel = readDependencyModel(); + + Vnfc xe = new Vnfc("XE","Active-Active",null, false); + Vnfc ye = new Vnfc("YE","Active-Active",null, true); + Node xeNode = new Node(xe); + Node yeNode = new Node(ye); + yeNode.addParent(xe); + + dependencyModel.getDependencies().add(yeNode); + dependencyModel.getDependencies().add(xeNode); + + PowerMockito.mockStatic(DependencyModelFactory.class); + DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); + + PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); + PowerMockito.when(dependencyManager.getVnfcDependencyModel(( + DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) + .thenReturn(dependencyModel); + + VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); + vnfExecutionFlow.getVnfExecutionFlowData(params,context); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java deleted file mode 100644 index 7c36360f8..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/DCAEReporterPluginImplTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.*; -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.util.HashMap; -import java.util.Map; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({DCAEReporterPluginImpl.class, FrameworkUtil.class}) -public class DCAEReporterPluginImplTest { - private SvcLogicContext ctx; - private Map params; - - private final BundleContext bundleContext = Mockito.mock(BundleContext.class); - private final Bundle bundleService = Mockito.mock(Bundle.class); - private final ServiceReference sref = Mockito.mock(ServiceReference.class); - - @InjectMocks - private DCAEReporterPluginImpl dcaeReporterPlugin; - @Spy - private EventSenderMock eventSender = new EventSenderMock(); - - private String apiVer = "2.0.0"; - private String requestId = "123"; - private String error = "test-error"; - - @SuppressWarnings("unchecked") - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(Matchers.any(Class.class))).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(eventSender); - } - - @Test - public void testReportErrorDescriptionNullBwcModeFalse() throws Exception { - ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("output.status.message", null); - ctx.setAttribute("input.common-header.api-ver", apiVer); - ctx.setAttribute("input.common-header.request-id", requestId); - - errorReasonNullAssert(); - } - - @Test - public void testReportBwcFalse() throws Exception { - ctx = new SvcLogicContext(); - params = new HashMap<>(); - ctx.setAttribute("isBwcMode", "false"); - params.put("output.status.message", error); - ctx.setAttribute("input.common-header.api-ver", apiVer); - ctx.setAttribute("input.common-header.request-id", requestId); - - positiveAssert(); - } - - private void errorReasonNullAssert() throws APPCException { - dcaeReporterPlugin.report(params, ctx); - MessageDestination destination = eventSender.getDestination(); - EventMessage msg = eventSender.getMsg(); - Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); - Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); - Assert.assertEquals("wrong error message", "Unknown", msg.getEventStatus().getReason()); - Assert.assertEquals("wrong destination", destination.name(), "DCAE"); - } - - private void positiveAssert() throws APPCException { - dcaeReporterPlugin.report(params, ctx); - MessageDestination destination = eventSender.getDestination(); - EventMessage msg = eventSender.getMsg(); - Assert.assertEquals("wrong API version", apiVer, msg.getEventHeader().getApiVer()); - Assert.assertEquals("wrong requestId", requestId, msg.getEventHeader().getEventId()); - Assert.assertEquals("wrong error message", error, msg.getEventStatus().getReason()); - Assert.assertEquals("wrong destination", destination.name(), "DCAE"); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java deleted file mode 100644 index cc30d3aea..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/EventSenderMock.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import java.util.Map; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class EventSenderMock implements EventSender { - EventMessage msg; - MessageDestination destination; - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg) { - if (destination != null && msg != null){ - this.msg = msg; - this.destination = destination; - return true; - } - else{ - return false; - } - } - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { - return false; - } - - @Override - public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { - return false; - } - - public EventMessage getMsg() { - return msg; - } - - public MessageDestination getDestination() { - return destination; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java deleted file mode 100644 index 6f5a0f13d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/JsonDgUtilImplTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import ch.qos.logback.core.Appender; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.dg.common.impl.JsonDgUtilImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.mock; - -public class JsonDgUtilImplTest { - - private final Appender appender = mock(Appender.class); - - - @Test - public void testFlatAndAddToContext() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, payload); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); - Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); - - - - } - - - @Test - public void testFlatAndAddToContextNegativeWrongPayload() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, payload); - try { - jsonDgUtil.flatAndAddToContext(params, ctx); - - } catch (APPCException e) { - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - Assert.assertNotNull(ctx.getAttribute("error-message")); - } - - - } - - - @Test - public void testFlatAndAddToContextPayloadFromContext() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueValue = "test-value"; - String testValueKey2 = "test-key2"; - String testValueValue2 = "test-value2"; - String payload = "{\"" + testValueKey + "\": \"" + testValueValue + "\",\""+testValueKey2+"\": \""+testValueValue2+"\"}"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, ""); - ctx.setAttribute("input.payload", payload); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertEquals(ctx.getAttribute(testValueKey), testValueValue); - Assert.assertEquals(ctx.getAttribute(testValueKey2), testValueValue2); - } - - @Test - public void testFlatAndAddToContextNegativeNullPayload() throws Exception { - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String testValueKey = "test-key"; - String testValueKey2 = "test-key2"; - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - jsonDgUtil.flatAndAddToContext(params, ctx); - - - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - } - - - @Test - public void testFlatAndAddToContextNegativeEmptyPayload() throws Exception { - - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "payload"; - String testValueKey = "test-key"; - String testValueKey2 = "test-key2"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - params.put(key, ""); - jsonDgUtil.flatAndAddToContext(params, ctx); - - Assert.assertNull(ctx.getAttribute(testValueKey)); - Assert.assertNull(ctx.getAttribute(testValueKey2)); - } - - - @Test - public void testGenerateOutputPayloadFromContext() throws Exception { - - JsonDgUtilImpl jsonDgUtil = new JsonDgUtilImpl(); - String key = "output.payload"; - String key1 = "output.payload.test-key[0]"; - String key2 = "output.payload.test-key[1]"; - String testValueKey1 = "value1"; - String testValueKey2 = "value2"; - - String key3 = "output.payload.test-key3"; - String testValueKey3 = "value3"; - - SvcLogicContext ctx = new SvcLogicContext(); - Map params = new HashMap<>(); - ctx.setAttribute(key1, testValueKey1); - ctx.setAttribute(key2, testValueKey2); - ctx.setAttribute(key3, testValueKey3); - jsonDgUtil.generateOutputPayloadFromContext(params, ctx); - - Assert.assertNotNull(ctx.getAttribute(key)); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java deleted file mode 100644 index ca3e7f5e2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVNFConfiguratorImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import org.onap.appc.dg.common.VNFConfigurator; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.impl.MDSALStoreFactory; -import org.onap.appc.mdsal.impl.MDSALStoreImpl; -import org.onap.appc.mdsal.objects.BundleInfo; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MDSALStoreImpl.class,MDSALStoreFactory.class}) -public class TestVNFConfiguratorImpl { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVNFConfiguratorImpl.class); - - @Before - public void setUp() { - logger.setLevel(EELFLogger.Level.DEBUG); - } - - @Test(expected = APPCException.class) - public void testValidations() throws APPCException { - VNFConfigurator configurator = new VNFConfiguratorImpl(); - Map params = new HashMap(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - configurator.storeConfig(params,new SvcLogicContext()); - } - - @Test - public void testYangPresentScenario() throws APPCException { - - VNFConfigurator configurator = new VNFConfiguratorImpl(); - PowerMockito.mockStatic(MDSALStoreFactory.class); - MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); - PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); - PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(true); - - Map params = new HashMap(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - params.put("requestId","requestId"); - configurator.storeConfig(params,new SvcLogicContext()); - } - - @Test - public void testYangAbsentScenario() throws Exception { - - VNFConfigurator configurator = new VNFConfiguratorImpl(); - PowerMockito.mockStatic(MDSALStoreFactory.class); - - MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class); - - PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore); - - PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(false); - - PowerMockito.doNothing().when(mdsalStore).storeYangModule(Matchers.anyString(),(BundleInfo)Matchers.anyObject()); - - Map params = new HashMap<>(); - params.put("uniqueId","uniqueId"); - params.put("yang","yang"); - params.put("configJSON","configJSON"); - params.put("requestId","requestId"); - configurator.storeConfig(params,new SvcLogicContext()); - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java b/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java deleted file mode 100644 index bad862030..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-common/src/test/java/org/openecomp/appc/dg/common/impl/TestVnfExecutionFlowImpl.java +++ /dev/null @@ -1,420 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.common.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.onap.appc.dg.common.VnfExecutionFlow; -import org.onap.appc.dg.common.impl.Constants; -import org.onap.appc.dg.common.impl.VnfExecutionFlowImpl; -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.impl.DependencyModelFactory; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import org.osgi.framework.FrameworkUtil; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({TestVnfExecutionFlowImpl.class, FrameworkUtil.class,DependencyManager.class,DependencyModelFactory.class}) -public class TestVnfExecutionFlowImpl { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVnfExecutionFlowImpl.class); - - @Before - public void setUp() { - logger.setLevel(EELFLogger.Level.DEBUG); - } - - @Test - public void testPositiveFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testComplexFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContextForComplexDependency(); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test(expected = InvalidDependencyModel.class) - public void testCycleFlow() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContextForComplexDependency(); - VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - private VnfcDependencyModel readCyclicDependencyModel() { - - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - cNode.addParent(b); - - bNode.addParent(d); - dNode.addParent(c); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - - } - - private SvcLogicContext prepareContextForComplexDependency() { - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("input.action-identifiers.vnf-id","1"); - context.setAttribute("vnf.type","vSCP"); - context.setAttribute("vnf.vnfcCount","7"); - - context.setAttribute("vnf.vnfc[0].name","A"); - context.setAttribute("vnf.vnfc[0].type","A"); - context.setAttribute("vnf.vnfc[0].vm_count","2"); - context.setAttribute("vnf.vnfc[0].vm[0].url","A1"); - context.setAttribute("vnf.vnfc[0].vm[1].url","A2"); - - context.setAttribute("vnf.vnfc[1].name","B"); - context.setAttribute("vnf.vnfc[1].type","B"); - context.setAttribute("vnf.vnfc[1].vm_count","5"); - context.setAttribute("vnf.vnfc[1].vm[0].url","B1"); - context.setAttribute("vnf.vnfc[1].vm[1].url","B2"); - context.setAttribute("vnf.vnfc[1].vm[2].url","B3"); - context.setAttribute("vnf.vnfc[1].vm[3].url","B4"); - context.setAttribute("vnf.vnfc[1].vm[4].url","B5"); - - context.setAttribute("vnf.vnfc[2].name","C"); - context.setAttribute("vnf.vnfc[2].type","C"); - context.setAttribute("vnf.vnfc[2].vm_count","4"); - context.setAttribute("vnf.vnfc[2].vm[0].url","C1"); - context.setAttribute("vnf.vnfc[2].vm[1].url","C2"); - context.setAttribute("vnf.vnfc[2].vm[2].url","C3"); - context.setAttribute("vnf.vnfc[2].vm[3].url","C4"); - - context.setAttribute("vnf.vnfc[3].name","D"); - context.setAttribute("vnf.vnfc[3].type","D"); - context.setAttribute("vnf.vnfc[3].vm_count","3"); - context.setAttribute("vnf.vnfc[3].vm[0].url","D1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","D2"); - context.setAttribute("vnf.vnfc[3].vm[2].url","D3"); - - context.setAttribute("vnf.vnfc[4].name","E"); - context.setAttribute("vnf.vnfc[4].type","E"); - context.setAttribute("vnf.vnfc[4].vm_count","2"); - context.setAttribute("vnf.vnfc[4].vm[0].url","E1"); - context.setAttribute("vnf.vnfc[4].vm[1].url","E2"); - - context.setAttribute("vnf.vnfc[5].name","F"); - context.setAttribute("vnf.vnfc[5].type","F"); - context.setAttribute("vnf.vnfc[5].vm_count","1"); - context.setAttribute("vnf.vnfc[5].vm[0].url","F1"); - - context.setAttribute("vnf.vnfc[6].name","G"); - context.setAttribute("vnf.vnfc[6].type","G"); - context.setAttribute("vnf.vnfc[6].vm_count","1"); - context.setAttribute("vnf.vnfc[6].vm[0].url","G1"); - - - return context; - } - - private VnfcDependencyModel readComplexDependencyModel() { - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - - dNode.addParent(b); - eNode.addParent(b); - gNode.addParent(b); - - fNode.addParent(c); - - gNode.addParent(f); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - } - - private VnfcDependencyModel readDependencyModel() { - - Vnfc smp = new Vnfc("SMP","Active-Passive",null); - Vnfc be = new Vnfc("BE","Active-Active",null); - Vnfc fe = new Vnfc("FE","Active-Active",null); - - - Node smpNode = new Node(smp); - Node beNode = new Node(be); - Node feNode = new Node(fe); - - beNode.addParent(smp); - feNode.addParent(be); -// smpNode.addParent(fe); - - Set> dependencies = new HashSet<>(); - dependencies.add(smpNode); - dependencies.add(feNode); - dependencies.add(beNode); - - return new VnfcDependencyModel(dependencies); - } - - private Map prepareParams() { - Map params = new HashMap<>(); - params.put(Constants.DEPENDENCY_TYPE,"RESOURCE"); - params.put(Constants.FLOW_STRATEGY,"FORWARD"); - - params.put(Constants.VNF_TYPE,"vSCP"); - params.put(Constants.VNF_VERION,"1.00"); - return params; - } - - private SvcLogicContext prepareContext() { - SvcLogicContext context = new SvcLogicContext(); - context.setAttribute("input.action-identifiers.vnf-id","1"); - context.setAttribute("vnf.type","vSCP"); - context.setAttribute("vnf.vnfcCount","3"); - - context.setAttribute("vnf.vnfc[0].name","SMPname"); - context.setAttribute("vnf.vnfc[0].type","SMP"); - context.setAttribute("vnf.vnfc[0].vm_count","2"); - context.setAttribute("vnf.vnfc[0].vm[0].url","SMP_URL1"); - context.setAttribute("vnf.vnfc[0].vm[1].url","SMP_URL2"); - - context.setAttribute("vnf.vnfc[1].name","BEname"); - context.setAttribute("vnf.vnfc[1].type","BE"); - context.setAttribute("vnf.vnfc[1].vm_count","5"); - context.setAttribute("vnf.vnfc[1].vm[0].url","BE_URL1"); - context.setAttribute("vnf.vnfc[1].vm[1].url","BE_URL2"); - context.setAttribute("vnf.vnfc[1].vm[2].url","BE_URL3"); - context.setAttribute("vnf.vnfc[1].vm[3].url","BE_URL4"); - context.setAttribute("vnf.vnfc[1].vm[4].url","BE_URL5"); - - context.setAttribute("vnf.vnfc[2].name","FEname"); - context.setAttribute("vnf.vnfc[2].type","FE"); - context.setAttribute("vnf.vnfc[2].vm_count","2"); - context.setAttribute("vnf.vnfc[2].vm[0].url","FE_URL1"); - context.setAttribute("vnf.vnfc[2].vm[1].url","FE_URL2"); - - return context; - } - - @Test(expected = RuntimeException.class) - public void testMissingVnfcTypeInDependencyModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - context.setAttribute("vnf.vnfc[3].name","XEname"); - context.setAttribute("vnf.vnfc[3].type","XE"); - context.setAttribute("vnf.vnfc[3].vm_count","2"); - context.setAttribute("vnf.vnfc[3].vm[0].url","XE_URL1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","XE_URL2"); - context.setAttribute("vnf.vnfcCount","4"); - - VnfcDependencyModel dependencyModel = readDependencyModel(); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test(expected = RuntimeException.class) - public void testMissingMandatoryVnfcTypeInInventoryModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, true); - Node xeNode = new Node(xe); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testMissingOptionalVnfcTypeInInventoryModel() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, false); - Node xeNode = new Node(xe); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } - - @Test - public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild() throws DependencyModelNotFound { - Map params = prepareParams(); - SvcLogicContext context = prepareContext(); - context.setAttribute("vnf.vnfc[3].name","YEname"); - context.setAttribute("vnf.vnfc[3].type","YE"); - context.setAttribute("vnf.vnfc[3].vm_count","2"); - context.setAttribute("vnf.vnfc[3].vm[0].url","YE_URL1"); - context.setAttribute("vnf.vnfc[3].vm[1].url","YE_URL2"); - context.setAttribute("vnf.vnfcCount","4"); - - VnfcDependencyModel dependencyModel = readDependencyModel(); - - Vnfc xe = new Vnfc("XE","Active-Active",null, false); - Vnfc ye = new Vnfc("YE","Active-Active",null, true); - Node xeNode = new Node(xe); - Node yeNode = new Node(ye); - yeNode.addParent(xe); - - dependencyModel.getDependencies().add(yeNode); - dependencyModel.getDependencies().add(xeNode); - - PowerMockito.mockStatic(DependencyModelFactory.class); - DependencyManager dependencyManager = PowerMockito.mock(DependencyManager.class); - - PowerMockito.when(DependencyModelFactory.createDependencyManager()).thenReturn(dependencyManager); - PowerMockito.when(dependencyManager.getVnfcDependencyModel(( - DependencyModelIdentifier) Matchers.any(),(DependencyTypes) Matchers.any())) - .thenReturn(dependencyModel); - - VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl(); - vnfExecutionFlow.getVnfExecutionFlowData(params,context); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java new file mode 100644 index 000000000..8d04cea11 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyManager.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager; + +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public interface DependencyManager { + VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier, DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java new file mode 100644 index 000000000..15717f06b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/DependencyType.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager; + +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.metadata.objects.DependencyModelIdentifier; + +public interface DependencyType { + VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java new file mode 100644 index 000000000..ffb6182cd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/exception/DependencyModelNotFound.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.exception; + + +public class DependencyModelNotFound extends Exception { + public DependencyModelNotFound(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java new file mode 100644 index 000000000..187020028 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/helper/DependencyModelParser.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.helper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.Node; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + +import java.io.IOException; +import java.util.*; + + +public class DependencyModelParser { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelParser.class); + private static Map dependencyMap; + private static final String PROPERTIES = "properties"; + private static final String ACTIVE_ACTIVE = "Active-Active"; + private static final String ACTIVE_PASSIVE = "Active-Passive"; + private static final String HIGH_AVAILABLITY = "high_availablity"; + private static final String MANDATORY = "mandatory"; + private static final String TOPOLOGY_TEMPLATE = "topology_template"; + + static { + Map dependencyTypeMappingMap =new HashMap<>(); + dependencyTypeMappingMap.put("geo-activeactive", ACTIVE_ACTIVE); + dependencyTypeMappingMap.put("geo-activestandby", ACTIVE_PASSIVE); + dependencyTypeMappingMap.put("local-activeactive", ACTIVE_ACTIVE); + dependencyTypeMappingMap.put("local-activestandby", ACTIVE_PASSIVE); + dependencyMap = Collections.unmodifiableMap(dependencyTypeMappingMap); + } + + public VnfcDependencyModel generateDependencyModel(String vnfModel,String vnfType) { + Set> dependencies = new HashSet<>(); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + boolean mandatory; + String resilienceType; + String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes."; + try { + ObjectNode root = (ObjectNode) mapper.readTree(vnfModel); + + if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) { + throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or 'node_templates' elements"); + } + + JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE); + JsonNode nodeTemplateNode = topologyTemplateNode.get("node_templates"); + Iterator> itretor = nodeTemplateNode.fields(); + for (JsonNode yamlNode : nodeTemplateNode) { + logger.debug("Processing node: " + yamlNode); + String fullvnfcType = itretor.next().getValue().get("type").textValue(); + String vnfcType= getQualifiedVnfcType(fullvnfcType); + String type = yamlNode.get("type").textValue(); + type = type.substring(0,type.lastIndexOf(".")+1); + if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) { + + if(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null || yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) { + resilienceType = ACTIVE_ACTIVE; + }else { + resilienceType = dependencyMap.get(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).textValue()); + } + + if(yamlNode.get(PROPERTIES).findValue(MANDATORY) == null || yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty()) { + mandatory = false; + }else { + mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue(); + } + String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode); + Node vnfcNode = getNode(dependencies, vnfcType); + if (vnfcNode != null) { + logger.debug("Dependency node already exists for vnfc Type: " + vnfcType); + if (StringUtils.isEmpty(vnfcNode.getChild().getResilienceType())) { + logger.debug("Updating resilience type, dependencies and mandatory attribute for VNFC type: " + vnfcType); + vnfcNode.getChild().setResilienceType(resilienceType); + if (parentList != null && parentList.length > 0) { + addDependencies(dependencies, vnfcNode, parentList); + } + vnfcNode.getChild().setMandatory(mandatory); + } + + } else { + logger.debug("Creating dependency node for : " + vnfcType); + vnfcNode = new Node<>(new Vnfc(vnfcType, resilienceType, null, mandatory)); + if (parentList != null && parentList.length > 0) + addDependencies(dependencies, vnfcNode, parentList); + logger.debug("Adding VNFC to dependency model : " + vnfcNode); + dependencies.add(vnfcNode); + } + } + } + } catch (IOException e) { + logger.error("Error parsing dependency model : " + vnfModel); + logger.error("Error message : " + e); + throw new InvalidDependencyModel("Error parsing dependency model. " + e.getMessage()); + } + return new VnfcDependencyModel(dependencies); + } + + private String getQualifiedVnfcType(String fullvnfcType) { + return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length()); + } + + private void addDependencies(Set> nodes, Node node, String[] parentList) { + for (String type : parentList) { + String parentType = getVnfcType(type); + Node parentNode = getNode(nodes, parentType); + if (parentNode != null) { + logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list "); + node.addParent(parentNode.getChild()); + } else { + logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC "); + parentNode = new Node<>(new Vnfc(parentType, null)); + node.addParent(parentNode.getChild()); + logger.debug("Adding VNFC to dependency model : " + parentNode); + nodes.add(parentNode); + } + } + } + + private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) { + JsonNode requirementsNode = node.get("requirements"); + List dependencyList = new ArrayList(); + if(requirementsNode!=null) { + for (JsonNode internalNode : requirementsNode) { + //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team + if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) + && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) { + if(internalNode.findValue("node") != null) { + String nodeName = internalNode.findValue("node").asText(); + String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText(); + dependencyList.add(getQualifiedVnfcType(fullVnfcName)); + }else{ + throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type")); + } + } + } + return dependencyList.toArray(new String[0]); + }else{ + return new String[0]; + } + } + + private boolean nodeNullCheck(JsonNode internalNode) { + return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null; + } + + private Node getNode(Set> nodes, String vnfcType) { + Iterator itr = nodes.iterator(); + Node node; + while (itr.hasNext()) { + node = (Node) itr.next(); + if (node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)) { + return node; + } + } + return null; + } + + private String getVnfcType(String type) { + return type.substring(type.lastIndexOf('.') + 1, type.length()); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java new file mode 100644 index 000000000..31ea46cc6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyManagerImpl.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.dg.dependencymanager.DependencyManager; +import org.onap.appc.dg.dependencymanager.DependencyType; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.DependencyTypes; +import org.onap.appc.dg.objects.VnfcDependencyModel; + +import org.onap.appc.cache.MetadataCache; +import org.onap.appc.cache.impl.MetadataCacheFactory; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class DependencyManagerImpl implements DependencyManager { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyManagerImpl.class); + + MetadataCache cache; + + DependencyManagerImpl(){ + cache = MetadataCacheFactory.getInstance().getMetadataCache(); + } + + public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier + + " , DependencyTypes = " + dependencyType); + } + VnfcDependencyModel dependencyModel = cache.getObject(modelIdentifier); + if(dependencyModel == null){ + logger.debug("Dependency model not found in cache, creating strategy for reading it"); + DependencyType strategy = getStrategy(dependencyType); + dependencyModel = strategy.getVnfcDependencyModel(modelIdentifier); + } + if (logger.isTraceEnabled()) { + logger.trace("Returning getVnfcDependencyModel with dependency model = "+ dependencyModel); + } + return dependencyModel; + } + + private DependencyType getStrategy(DependencyTypes dependencyType) { + switch (dependencyType){ + case RESOURCE: + return new ResourceDependency(); + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java new file mode 100644 index 000000000..a3fd36937 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/DependencyModelFactory.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.dg.dependencymanager.DependencyManager; + + +public class DependencyModelFactory { + + private static class ReferenceHolder{ + private static final DependencyManagerImpl INSTANCE = new DependencyManagerImpl(); + } + + public static DependencyManager createDependencyManager(){ + return ReferenceHolder.INSTANCE; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java new file mode 100644 index 000000000..73792d3ad --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/dependencymanager/impl/ResourceDependency.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.dependencymanager.impl; + +import org.onap.appc.metadata.MetadataService; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.appc.dg.dependencymanager.DependencyType; +import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; +import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + + +public class ResourceDependency implements DependencyType{ + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDependency.class); + + + private MetadataService metadataService; + + public ResourceDependency(){ + getMetadataServiceRef(); + } + + private void getMetadataServiceRef() { + BundleContext bctx = FrameworkUtil.getBundle(MetadataService.class).getBundleContext(); + // Get MetadataService reference + ServiceReference sref = bctx.getServiceReference(MetadataService.class.getName()); + if (sref != null) { + logger.info("MetadataService from bundlecontext"); + metadataService = (MetadataService) bctx.getService(sref); + + } else { + logger.info("MetadataService error from bundlecontext"); + logger.warn("Cannot find service reference for org.onap.appc.metadata.MetadataService"); + } + } + + public void setMetadataService(MetadataService metadataService) { + this.metadataService = metadataService; + } + + public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier); + } + String vnfModel = metadataService.getVnfModel(modelIdentifier); + if(vnfModel ==null){ + logger.debug("Vnf model not found from metadata service"); + throw new DependencyModelNotFound("Invalid or Empty VNF Model"); + } + if (logger.isTraceEnabled()) { + logger.trace("Building dependency model for Vnf Model : " + vnfModel); + } + DependencyModelParser modelParser = new DependencyModelParser(); + return modelParser.generateDependencyModel(vnfModel,modelIdentifier.getVnfType()); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java new file mode 100644 index 000000000..78dacd105 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowBuilder.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + + +public interface FlowBuilder { + VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel,InventoryModel inventoryModel); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java new file mode 100644 index 000000000..e2c292776 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/FlowStrategy.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + + +public interface FlowStrategy { + + VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel); +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java new file mode 100644 index 000000000..9f4cfed93 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/exception/InvalidDependencyModel.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.exception; + + +public class InvalidDependencyModel extends RuntimeException { + public InvalidDependencyModel(String message){ + super(message); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java new file mode 100644 index 000000000..95e0b6675 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/helper/Graph.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.helper; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; + + +public class Graph { + private int size; + private List vertexList; + + private int[][] dependencyMatrix; + + public Graph(int size){ + this.size =size; + vertexList = new ArrayList<>(); + dependencyMatrix = new int[size][size]; + } + + public void addVertex(T vertex){ + vertexList.add(vertex); + } + + public int getIndex(T vertex){ + return vertexList.indexOf(vertex); + } + + public void addEdge(T vertex1,T vertex2){ + dependencyMatrix[vertexList.indexOf(vertex1)][vertexList.indexOf(vertex2)] = 1; + } + + public int[][] getDependencyMatrix() { + return dependencyMatrix; + } + + public int getSize() { + return size; + } + + public List getVertexList() { + return vertexList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java new file mode 100644 index 000000000..fbb2d5d67 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.onap.appc.dg.flowbuilder.FlowStrategy; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.helper.Graph; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnfc; + + +public abstract class AbstractFlowStrategy implements FlowStrategy { + + protected Graph graph; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractFlowStrategy.class); + + public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + if(logger.isTraceEnabled()){ + logger.trace("Entering into buildFlowModel with dependency model = " + dependencyModel + + "inventory model = " +inventoryModel); + } + + if(dependencyModel == null + || dependencyModel.getDependencies() ==null + || dependencyModel.getDependencies().size() ==0){ + logger.debug("Dependency model not available, building flow model with sequence"); + throw new InvalidDependencyModel("Dependency model either null or does not contain any dependency"); + } + + VnfcFlowModel flowModel = buildFlowModel(dependencyModel); + if(logger.isDebugEnabled()){ + logger.debug("Flow Model without instance data: \n" + flowModel); + } + + logger.info("Populating flow model with A&AI data"); + populateFlowModel(flowModel,inventoryModel); + if(logger.isDebugEnabled()){ + logger.debug("Flow Model with instance data: \n" + flowModel); + } + + return flowModel; + } + + private void populateFlowModel(VnfcFlowModel flowModel, InventoryModel inventoryModel) { + Iterator> flowIterator = null; + + for(Vnfc vnfcFromInventory:inventoryModel.getVnf().getVnfcs()){ + flowIterator = flowModel.getModelIterator(); + String vnfcType = vnfcFromInventory.getVnfcType(); + while (flowIterator.hasNext()){ + for(Vnfc vnfcFromFlowModel:flowIterator.next() ){ + if(vnfcType.equalsIgnoreCase(vnfcFromFlowModel.getVnfcType())){ + vnfcFromFlowModel.setVnfcName(vnfcFromInventory.getVnfcName()); + vnfcFromFlowModel.addVms(vnfcFromInventory.getVserverList()); + } + } + } + + } + + } + + private VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel) throws InvalidDependencyModel { + Set> dependencies = dependencyModel.getDependencies(); + graph = new Graph(dependencies.size()); + + for(Node node:dependencies){ + graph.addVertex(node.getChild()); + } + + for(Node node:dependencies){ + Vnfc child = (Vnfc)node.getChild(); + List parents = node.getParents(); + for(Vnfc parent:parents){ + graph.addEdge(child,parent); + } + } + List> dependencyList = orderDependencies(); + + VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); + int count=0; + int flowModelSize = 0; + for(List vnfcList:dependencyList){ + builder.addMetadata(count,vnfcList); + flowModelSize += vnfcList.size(); + count++; + } + if(flowModelSize != dependencies.size()){ + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + + return builder.build(); + } + + protected abstract List> orderDependencies(); + + /*private VnfcFlowModel buildFlowModelWithoutSequence(InventoryModel inventoryModel) { + VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); + + for(Vnfc vnfc:inventoryModel.getVnf().getVnfcs()){ + builder = builder.addMetadata(0,vnfc); + } + + return builder.build(); + }*/ +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java new file mode 100644 index 000000000..ac5e35b89 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderFactory.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.objects.FlowStrategies; + + +public class FlowBuilderFactory { + private static class ReferenceHolder{ + private static final FlowBuilderFactory FACTORY = new FlowBuilderFactory(); + } + + public static FlowBuilderFactory getInstance(){ + return ReferenceHolder.FACTORY; + } + + public FlowBuilder getFlowBuilder(FlowStrategies flowStrategy){ + + switch (flowStrategy){ + case FORWARD: + return new FlowBuilderImpl(new ForwardFlowStrategy()); + case REVERSE: + return new FlowBuilderImpl(new ReverseFlowStrategy()); + } + return null; + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java new file mode 100644 index 000000000..59d1e4bf9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/FlowBuilderImpl.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.FlowStrategy; +import org.onap.appc.dg.objects.InventoryModel; +import org.onap.appc.dg.objects.VnfcDependencyModel; +import org.onap.appc.dg.objects.VnfcFlowModel; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class FlowBuilderImpl implements FlowBuilder { + + + + private FlowStrategy strategy; + + FlowBuilderImpl(FlowStrategy strategy){ + this.strategy = strategy; + } + + public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { + return strategy.buildFlowModel(dependencyModel, inventoryModel); + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java new file mode 100644 index 000000000..9c5aae64f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + + +public class ForwardFlowStrategy extends AbstractFlowStrategy { + @Override + protected List> orderDependencies() { + ArrayList> arrayList = new ArrayList<>(); + + Queue queue1 = new LinkedList(); + Set queue2 = new LinkedHashSet<>(); + + Set uniqueElementSet = new HashSet<>(); + Set duplicateElementSet = new HashSet<>(); + + // identifying independent nodes in queue1 + for(int rowIndex=0;rowIndex)queue1); + queue1 = new LinkedList<>(queue1); + + boolean flag = true; + + while(flag){ + // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 + while(!queue1.isEmpty()){ + Vnfc listItem = queue1.remove(); + Integer colIndex = graph.getIndex(listItem); + for(Integer index =0;index(queue2)); + if(arrayList.size()>graph.getSize()){ + // dependency list cannot be larger than total number of nodes + // if it happens indicates cycle in the dependency + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + queue1.addAll(queue2); + queue2 = new LinkedHashSet<>(); + } + } + // If any node depends on multiple nodes present in different execution sequence, + // its execution should happen on the higher order, removing its presence on lower execution sequence + if(!duplicateElementSet.isEmpty()){ + for(Vnfc vnfc:duplicateElementSet){ + boolean firstOccurrence= true; + for(int i=arrayList.size()-1;i>=0;i--){ + List list = arrayList.get(i); + if(list.contains(vnfc)){ + if(firstOccurrence){ + firstOccurrence =false; + continue; + } + else{ + list.remove(vnfc); + } + } + + } + } + } + return arrayList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java new file mode 100644 index 000000000..79cd4420c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder.impl; + +import java.util.*; + +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.domainmodel.Vnfc; + + +public class ReverseFlowStrategy extends AbstractFlowStrategy { + + @Override + protected List> orderDependencies() { + ArrayList> arrayList = new ArrayList<>(); + + Queue queue1 = new LinkedList(); + Set queue2 = new LinkedHashSet<>(); + + Set uniqueElementSet = new HashSet<>(); + Set duplicateElementSet = new HashSet<>(); + + // identifying independent nodes in queue1 + for(int colIndex=0;colIndex)queue1); + queue1 = new LinkedList<>(queue1); + + boolean flag = true; + + while(flag){ + // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 + while(!queue1.isEmpty()){ + Vnfc listItem = queue1.remove(); + Integer rowIndex = graph.getIndex(listItem); + for(Integer index =0;index(queue2)); + if(arrayList.size()>graph.getSize()){ + // dependency list cannot be larger than total number of nodes + // if it happens indicates cycle in the dependency + throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); + } + queue1.addAll(queue2); + queue2 = new LinkedHashSet<>(); + } + } + // If any node depends on multiple nodes present in different execution sequence, + // its execution should happen on the higher order, removing its presence on lower execution sequence + if(!duplicateElementSet.isEmpty()){ + for(Vnfc vnfc:duplicateElementSet){ + boolean firstOccurrence= true; + for(int i=0;i list = arrayList.get(i); + if(list.contains(vnfc)){ + if(firstOccurrence){ + firstOccurrence =false; + list.remove(vnfc); + } + else{ + continue; + } + } + + } + } + } + return arrayList; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java new file mode 100644 index 000000000..b74ea7965 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/DependencyTypes.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + + +public enum DependencyTypes { + RESOURCE; + + public static DependencyTypes findByString(String dependencyTypeStr){ + for(DependencyTypes dependencyType : DependencyTypes.values()){ + if(dependencyType.name().equalsIgnoreCase(dependencyTypeStr)){ + return dependencyType; + } + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java new file mode 100644 index 000000000..857d802c2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/FlowStrategies.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + + +public enum FlowStrategies { + FORWARD,REVERSE; + + public static FlowStrategies findByString(String flowStrategyStr){ + for(FlowStrategies flowStrategy:FlowStrategies.values()){ + if(flowStrategy.name().equalsIgnoreCase(flowStrategyStr)){ + return flowStrategy; + } + } + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java new file mode 100644 index 000000000..e9156a8d9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/InventoryModel.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import org.onap.appc.domainmodel.Vnf; + + +public class InventoryModel { + + private Vnf vnf; + + public InventoryModel(Vnf vnf){ + this.vnf= vnf; + } + + public Vnf getVnf() { + return vnf; + } + + @Override + public String toString() { + return "InventoryModel = " + vnf.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java new file mode 100644 index 000000000..586ce7deb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/Node.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.LinkedList; +import java.util.List; + + +public class Node { + T child; + List parents; + + @Override + public int hashCode(){ + return child.hashCode(); + } + + @Override + public boolean equals(Object object){ + if(object == null){ + return false; + } + if(!(object instanceof Node)){ + return false; + } + Node node = (Node)object; + return this.child.equals(node.getChild()); + } + + public Node(T child){ + this.child = child; + this.parents = new LinkedList<>(); + } + + public T getChild() { + return child; + } + + public List getParents() { + return parents; + } + + public void addParent(T parent){ + this.parents.add(parent); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Node : child = " + child + " , parents = "); + for(T parent:parents){ + stringBuilder.append(parent).append(","); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java new file mode 100644 index 000000000..278d6fcaa --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcDependencyModel.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.Set; + +import org.onap.appc.domainmodel.Vnfc; + + +public class VnfcDependencyModel { + private Set> dependencies; + + public VnfcDependencyModel(Set> dependencies){ + this.dependencies = dependencies; + } + + public Set> getDependencies() { + return dependencies; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("dependencies = "); + for(Node node:dependencies){ + stringBuilder.append(node.toString()).append(", "); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java new file mode 100644 index 000000000..1100e42cb --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/onap/appc/dg/objects/VnfcFlowModel.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.objects; + +import java.util.*; + +import org.onap.appc.domainmodel.Vnfc; + + +public class VnfcFlowModel { + private Map> flowModelMap; + + private VnfcFlowModel(VnfcFlowModelBuilder builder){ + this.flowModelMap = builder.map; + + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Flow Model : "); + Iterator> iterator = getModelIterator(); + while(iterator.hasNext()){ + for(Vnfc vnfc:iterator.next()){ + stringBuilder.append(vnfc.toString()).append(", \n"); + } + } + + return stringBuilder.toString(); + } + + public Iterator> getModelIterator(){ + return flowModelMap.values().iterator(); + } + + public static class VnfcFlowModelBuilder{ + + Map> map; + + public VnfcFlowModelBuilder(){ + map = new HashMap<>(); + } + + public VnfcFlowModelBuilder addMetadata(Integer index,Vnfc vnfc){ + List vnfcList = this.map.get(index); + if(vnfcList == null){ + vnfcList = new LinkedList<>(); + map.put(index,vnfcList); + } + vnfcList.add(vnfc); + return this; + } + + public VnfcFlowModelBuilder addMetadata(Integer index,List vnfcs){ + List vnfcList = this.map.get(index); + if(vnfcList == null){ + vnfcList = new LinkedList<>(); + map.put(index,vnfcList); + } + vnfcList.addAll(vnfcs); + return this; + } + + public VnfcFlowModel build(){ + return new VnfcFlowModel(this); + } + + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java deleted file mode 100644 index 8d04cea11..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager; - -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public interface DependencyManager { - VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier, DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java deleted file mode 100644 index 15717f06b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/DependencyType.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager; - -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.metadata.objects.DependencyModelIdentifier; - -public interface DependencyType { - VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java deleted file mode 100644 index ffb6182cd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/exception/DependencyModelNotFound.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.exception; - - -public class DependencyModelNotFound extends Exception { - public DependencyModelNotFound(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java deleted file mode 100644 index 187020028..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.helper; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.Node; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - -import java.io.IOException; -import java.util.*; - - -public class DependencyModelParser { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelParser.class); - private static Map dependencyMap; - private static final String PROPERTIES = "properties"; - private static final String ACTIVE_ACTIVE = "Active-Active"; - private static final String ACTIVE_PASSIVE = "Active-Passive"; - private static final String HIGH_AVAILABLITY = "high_availablity"; - private static final String MANDATORY = "mandatory"; - private static final String TOPOLOGY_TEMPLATE = "topology_template"; - - static { - Map dependencyTypeMappingMap =new HashMap<>(); - dependencyTypeMappingMap.put("geo-activeactive", ACTIVE_ACTIVE); - dependencyTypeMappingMap.put("geo-activestandby", ACTIVE_PASSIVE); - dependencyTypeMappingMap.put("local-activeactive", ACTIVE_ACTIVE); - dependencyTypeMappingMap.put("local-activestandby", ACTIVE_PASSIVE); - dependencyMap = Collections.unmodifiableMap(dependencyTypeMappingMap); - } - - public VnfcDependencyModel generateDependencyModel(String vnfModel,String vnfType) { - Set> dependencies = new HashSet<>(); - ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); - boolean mandatory; - String resilienceType; - String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes."; - try { - ObjectNode root = (ObjectNode) mapper.readTree(vnfModel); - - if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) { - throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or 'node_templates' elements"); - } - - JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE); - JsonNode nodeTemplateNode = topologyTemplateNode.get("node_templates"); - Iterator> itretor = nodeTemplateNode.fields(); - for (JsonNode yamlNode : nodeTemplateNode) { - logger.debug("Processing node: " + yamlNode); - String fullvnfcType = itretor.next().getValue().get("type").textValue(); - String vnfcType= getQualifiedVnfcType(fullvnfcType); - String type = yamlNode.get("type").textValue(); - type = type.substring(0,type.lastIndexOf(".")+1); - if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) { - - if(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null || yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) { - resilienceType = ACTIVE_ACTIVE; - }else { - resilienceType = dependencyMap.get(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).textValue()); - } - - if(yamlNode.get(PROPERTIES).findValue(MANDATORY) == null || yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty()) { - mandatory = false; - }else { - mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue(); - } - String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode); - Node vnfcNode = getNode(dependencies, vnfcType); - if (vnfcNode != null) { - logger.debug("Dependency node already exists for vnfc Type: " + vnfcType); - if (StringUtils.isEmpty(vnfcNode.getChild().getResilienceType())) { - logger.debug("Updating resilience type, dependencies and mandatory attribute for VNFC type: " + vnfcType); - vnfcNode.getChild().setResilienceType(resilienceType); - if (parentList != null && parentList.length > 0) { - addDependencies(dependencies, vnfcNode, parentList); - } - vnfcNode.getChild().setMandatory(mandatory); - } - - } else { - logger.debug("Creating dependency node for : " + vnfcType); - vnfcNode = new Node<>(new Vnfc(vnfcType, resilienceType, null, mandatory)); - if (parentList != null && parentList.length > 0) - addDependencies(dependencies, vnfcNode, parentList); - logger.debug("Adding VNFC to dependency model : " + vnfcNode); - dependencies.add(vnfcNode); - } - } - } - } catch (IOException e) { - logger.error("Error parsing dependency model : " + vnfModel); - logger.error("Error message : " + e); - throw new InvalidDependencyModel("Error parsing dependency model. " + e.getMessage()); - } - return new VnfcDependencyModel(dependencies); - } - - private String getQualifiedVnfcType(String fullvnfcType) { - return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length()); - } - - private void addDependencies(Set> nodes, Node node, String[] parentList) { - for (String type : parentList) { - String parentType = getVnfcType(type); - Node parentNode = getNode(nodes, parentType); - if (parentNode != null) { - logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list "); - node.addParent(parentNode.getChild()); - } else { - logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC "); - parentNode = new Node<>(new Vnfc(parentType, null)); - node.addParent(parentNode.getChild()); - logger.debug("Adding VNFC to dependency model : " + parentNode); - nodes.add(parentNode); - } - } - } - - private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) { - JsonNode requirementsNode = node.get("requirements"); - List dependencyList = new ArrayList(); - if(requirementsNode!=null) { - for (JsonNode internalNode : requirementsNode) { - //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team - if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) - && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) { - if(internalNode.findValue("node") != null) { - String nodeName = internalNode.findValue("node").asText(); - String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText(); - dependencyList.add(getQualifiedVnfcType(fullVnfcName)); - }else{ - throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type")); - } - } - } - return dependencyList.toArray(new String[0]); - }else{ - return new String[0]; - } - } - - private boolean nodeNullCheck(JsonNode internalNode) { - return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null; - } - - private Node getNode(Set> nodes, String vnfcType) { - Iterator itr = nodes.iterator(); - Node node; - while (itr.hasNext()) { - node = (Node) itr.next(); - if (node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)) { - return node; - } - } - return null; - } - - private String getVnfcType(String type) { - return type.substring(type.lastIndexOf('.') + 1, type.length()); - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java deleted file mode 100644 index 31ea46cc6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyManagerImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.dg.dependencymanager.DependencyManager; -import org.onap.appc.dg.dependencymanager.DependencyType; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.DependencyTypes; -import org.onap.appc.dg.objects.VnfcDependencyModel; - -import org.onap.appc.cache.MetadataCache; -import org.onap.appc.cache.impl.MetadataCacheFactory; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class DependencyManagerImpl implements DependencyManager { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyManagerImpl.class); - - MetadataCache cache; - - DependencyManagerImpl(){ - cache = MetadataCacheFactory.getInstance().getMetadataCache(); - } - - public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,DependencyTypes dependencyType) throws InvalidDependencyModel, DependencyModelNotFound { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier - + " , DependencyTypes = " + dependencyType); - } - VnfcDependencyModel dependencyModel = cache.getObject(modelIdentifier); - if(dependencyModel == null){ - logger.debug("Dependency model not found in cache, creating strategy for reading it"); - DependencyType strategy = getStrategy(dependencyType); - dependencyModel = strategy.getVnfcDependencyModel(modelIdentifier); - } - if (logger.isTraceEnabled()) { - logger.trace("Returning getVnfcDependencyModel with dependency model = "+ dependencyModel); - } - return dependencyModel; - } - - private DependencyType getStrategy(DependencyTypes dependencyType) { - switch (dependencyType){ - case RESOURCE: - return new ResourceDependency(); - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java deleted file mode 100644 index a3fd36937..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/DependencyModelFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.dg.dependencymanager.DependencyManager; - - -public class DependencyModelFactory { - - private static class ReferenceHolder{ - private static final DependencyManagerImpl INSTANCE = new DependencyManagerImpl(); - } - - public static DependencyManager createDependencyManager(){ - return ReferenceHolder.INSTANCE; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java deleted file mode 100644 index 73792d3ad..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/impl/ResourceDependency.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.dependencymanager.impl; - -import org.onap.appc.metadata.MetadataService; -import org.onap.appc.metadata.objects.DependencyModelIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.appc.dg.dependencymanager.DependencyType; -import org.onap.appc.dg.dependencymanager.exception.DependencyModelNotFound; -import org.onap.appc.dg.dependencymanager.helper.DependencyModelParser; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - - -public class ResourceDependency implements DependencyType{ - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDependency.class); - - - private MetadataService metadataService; - - public ResourceDependency(){ - getMetadataServiceRef(); - } - - private void getMetadataServiceRef() { - BundleContext bctx = FrameworkUtil.getBundle(MetadataService.class).getBundleContext(); - // Get MetadataService reference - ServiceReference sref = bctx.getServiceReference(MetadataService.class.getName()); - if (sref != null) { - logger.info("MetadataService from bundlecontext"); - metadataService = (MetadataService) bctx.getService(sref); - - } else { - logger.info("MetadataService error from bundlecontext"); - logger.warn("Cannot find service reference for org.onap.appc.metadata.MetadataService"); - } - } - - public void setMetadataService(MetadataService metadataService) { - this.metadataService = metadataService; - } - - public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModel, DependencyModelNotFound { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier); - } - String vnfModel = metadataService.getVnfModel(modelIdentifier); - if(vnfModel ==null){ - logger.debug("Vnf model not found from metadata service"); - throw new DependencyModelNotFound("Invalid or Empty VNF Model"); - } - if (logger.isTraceEnabled()) { - logger.trace("Building dependency model for Vnf Model : " + vnfModel); - } - DependencyModelParser modelParser = new DependencyModelParser(); - return modelParser.generateDependencyModel(vnfModel,modelIdentifier.getVnfType()); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java deleted file mode 100644 index 78dacd105..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - - -public interface FlowBuilder { - VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel,InventoryModel inventoryModel); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java deleted file mode 100644 index e2c292776..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/FlowStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - - -public interface FlowStrategy { - - VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel); -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java deleted file mode 100644 index 9f4cfed93..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/exception/InvalidDependencyModel.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.exception; - - -public class InvalidDependencyModel extends RuntimeException { - public InvalidDependencyModel(String message){ - super(message); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java deleted file mode 100644 index 95e0b6675..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/helper/Graph.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.helper; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; - - -public class Graph { - private int size; - private List vertexList; - - private int[][] dependencyMatrix; - - public Graph(int size){ - this.size =size; - vertexList = new ArrayList<>(); - dependencyMatrix = new int[size][size]; - } - - public void addVertex(T vertex){ - vertexList.add(vertex); - } - - public int getIndex(T vertex){ - return vertexList.indexOf(vertex); - } - - public void addEdge(T vertex1,T vertex2){ - dependencyMatrix[vertexList.indexOf(vertex1)][vertexList.indexOf(vertex2)] = 1; - } - - public int[][] getDependencyMatrix() { - return dependencyMatrix; - } - - public int getSize() { - return size; - } - - public List getVertexList() { - return vertexList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java deleted file mode 100644 index fbb2d5d67..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/AbstractFlowStrategy.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.onap.appc.dg.flowbuilder.FlowStrategy; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.helper.Graph; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnfc; - - -public abstract class AbstractFlowStrategy implements FlowStrategy { - - protected Graph graph; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractFlowStrategy.class); - - public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - if(logger.isTraceEnabled()){ - logger.trace("Entering into buildFlowModel with dependency model = " + dependencyModel - + "inventory model = " +inventoryModel); - } - - if(dependencyModel == null - || dependencyModel.getDependencies() ==null - || dependencyModel.getDependencies().size() ==0){ - logger.debug("Dependency model not available, building flow model with sequence"); - throw new InvalidDependencyModel("Dependency model either null or does not contain any dependency"); - } - - VnfcFlowModel flowModel = buildFlowModel(dependencyModel); - if(logger.isDebugEnabled()){ - logger.debug("Flow Model without instance data: \n" + flowModel); - } - - logger.info("Populating flow model with A&AI data"); - populateFlowModel(flowModel,inventoryModel); - if(logger.isDebugEnabled()){ - logger.debug("Flow Model with instance data: \n" + flowModel); - } - - return flowModel; - } - - private void populateFlowModel(VnfcFlowModel flowModel, InventoryModel inventoryModel) { - Iterator> flowIterator = null; - - for(Vnfc vnfcFromInventory:inventoryModel.getVnf().getVnfcs()){ - flowIterator = flowModel.getModelIterator(); - String vnfcType = vnfcFromInventory.getVnfcType(); - while (flowIterator.hasNext()){ - for(Vnfc vnfcFromFlowModel:flowIterator.next() ){ - if(vnfcType.equalsIgnoreCase(vnfcFromFlowModel.getVnfcType())){ - vnfcFromFlowModel.setVnfcName(vnfcFromInventory.getVnfcName()); - vnfcFromFlowModel.addVms(vnfcFromInventory.getVserverList()); - } - } - } - - } - - } - - private VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel) throws InvalidDependencyModel { - Set> dependencies = dependencyModel.getDependencies(); - graph = new Graph(dependencies.size()); - - for(Node node:dependencies){ - graph.addVertex(node.getChild()); - } - - for(Node node:dependencies){ - Vnfc child = (Vnfc)node.getChild(); - List parents = node.getParents(); - for(Vnfc parent:parents){ - graph.addEdge(child,parent); - } - } - List> dependencyList = orderDependencies(); - - VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); - int count=0; - int flowModelSize = 0; - for(List vnfcList:dependencyList){ - builder.addMetadata(count,vnfcList); - flowModelSize += vnfcList.size(); - count++; - } - if(flowModelSize != dependencies.size()){ - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - - return builder.build(); - } - - protected abstract List> orderDependencies(); - - /*private VnfcFlowModel buildFlowModelWithoutSequence(InventoryModel inventoryModel) { - VnfcFlowModel.VnfcFlowModelBuilder builder = new VnfcFlowModel.VnfcFlowModelBuilder(); - - for(Vnfc vnfc:inventoryModel.getVnf().getVnfcs()){ - builder = builder.addMetadata(0,vnfc); - } - - return builder.build(); - }*/ -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java deleted file mode 100644 index ac5e35b89..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.objects.FlowStrategies; - - -public class FlowBuilderFactory { - private static class ReferenceHolder{ - private static final FlowBuilderFactory FACTORY = new FlowBuilderFactory(); - } - - public static FlowBuilderFactory getInstance(){ - return ReferenceHolder.FACTORY; - } - - public FlowBuilder getFlowBuilder(FlowStrategies flowStrategy){ - - switch (flowStrategy){ - case FORWARD: - return new FlowBuilderImpl(new ForwardFlowStrategy()); - case REVERSE: - return new FlowBuilderImpl(new ReverseFlowStrategy()); - } - return null; - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java deleted file mode 100644 index 59d1e4bf9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/FlowBuilderImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.FlowStrategy; -import org.onap.appc.dg.objects.InventoryModel; -import org.onap.appc.dg.objects.VnfcDependencyModel; -import org.onap.appc.dg.objects.VnfcFlowModel; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class FlowBuilderImpl implements FlowBuilder { - - - - private FlowStrategy strategy; - - FlowBuilderImpl(FlowStrategy strategy){ - this.strategy = strategy; - } - - public VnfcFlowModel buildFlowModel(VnfcDependencyModel dependencyModel, InventoryModel inventoryModel) { - return strategy.buildFlowModel(dependencyModel, inventoryModel); - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java deleted file mode 100644 index 9c5aae64f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ForwardFlowStrategy.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - - -public class ForwardFlowStrategy extends AbstractFlowStrategy { - @Override - protected List> orderDependencies() { - ArrayList> arrayList = new ArrayList<>(); - - Queue queue1 = new LinkedList(); - Set queue2 = new LinkedHashSet<>(); - - Set uniqueElementSet = new HashSet<>(); - Set duplicateElementSet = new HashSet<>(); - - // identifying independent nodes in queue1 - for(int rowIndex=0;rowIndex)queue1); - queue1 = new LinkedList<>(queue1); - - boolean flag = true; - - while(flag){ - // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 - while(!queue1.isEmpty()){ - Vnfc listItem = queue1.remove(); - Integer colIndex = graph.getIndex(listItem); - for(Integer index =0;index(queue2)); - if(arrayList.size()>graph.getSize()){ - // dependency list cannot be larger than total number of nodes - // if it happens indicates cycle in the dependency - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - queue1.addAll(queue2); - queue2 = new LinkedHashSet<>(); - } - } - // If any node depends on multiple nodes present in different execution sequence, - // its execution should happen on the higher order, removing its presence on lower execution sequence - if(!duplicateElementSet.isEmpty()){ - for(Vnfc vnfc:duplicateElementSet){ - boolean firstOccurrence= true; - for(int i=arrayList.size()-1;i>=0;i--){ - List list = arrayList.get(i); - if(list.contains(vnfc)){ - if(firstOccurrence){ - firstOccurrence =false; - continue; - } - else{ - list.remove(vnfc); - } - } - - } - } - } - return arrayList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java deleted file mode 100644 index 79cd4420c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/flowbuilder/impl/ReverseFlowStrategy.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder.impl; - -import java.util.*; - -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.domainmodel.Vnfc; - - -public class ReverseFlowStrategy extends AbstractFlowStrategy { - - @Override - protected List> orderDependencies() { - ArrayList> arrayList = new ArrayList<>(); - - Queue queue1 = new LinkedList(); - Set queue2 = new LinkedHashSet<>(); - - Set uniqueElementSet = new HashSet<>(); - Set duplicateElementSet = new HashSet<>(); - - // identifying independent nodes in queue1 - for(int colIndex=0;colIndex)queue1); - queue1 = new LinkedList<>(queue1); - - boolean flag = true; - - while(flag){ - // iterating over queue1 and for each node in it finding all dependent nodes and putting them on queue2 - while(!queue1.isEmpty()){ - Vnfc listItem = queue1.remove(); - Integer rowIndex = graph.getIndex(listItem); - for(Integer index =0;index(queue2)); - if(arrayList.size()>graph.getSize()){ - // dependency list cannot be larger than total number of nodes - // if it happens indicates cycle in the dependency - throw new InvalidDependencyModel("Cycle detected in the VNFC dependencies"); - } - queue1.addAll(queue2); - queue2 = new LinkedHashSet<>(); - } - } - // If any node depends on multiple nodes present in different execution sequence, - // its execution should happen on the higher order, removing its presence on lower execution sequence - if(!duplicateElementSet.isEmpty()){ - for(Vnfc vnfc:duplicateElementSet){ - boolean firstOccurrence= true; - for(int i=0;i list = arrayList.get(i); - if(list.contains(vnfc)){ - if(firstOccurrence){ - firstOccurrence =false; - list.remove(vnfc); - } - else{ - continue; - } - } - - } - } - } - return arrayList; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java deleted file mode 100644 index b74ea7965..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/DependencyTypes.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - - -public enum DependencyTypes { - RESOURCE; - - public static DependencyTypes findByString(String dependencyTypeStr){ - for(DependencyTypes dependencyType : DependencyTypes.values()){ - if(dependencyType.name().equalsIgnoreCase(dependencyTypeStr)){ - return dependencyType; - } - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java deleted file mode 100644 index 857d802c2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/FlowStrategies.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - - -public enum FlowStrategies { - FORWARD,REVERSE; - - public static FlowStrategies findByString(String flowStrategyStr){ - for(FlowStrategies flowStrategy:FlowStrategies.values()){ - if(flowStrategy.name().equalsIgnoreCase(flowStrategyStr)){ - return flowStrategy; - } - } - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java deleted file mode 100644 index e9156a8d9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/InventoryModel.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import org.onap.appc.domainmodel.Vnf; - - -public class InventoryModel { - - private Vnf vnf; - - public InventoryModel(Vnf vnf){ - this.vnf= vnf; - } - - public Vnf getVnf() { - return vnf; - } - - @Override - public String toString() { - return "InventoryModel = " + vnf.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java deleted file mode 100644 index 586ce7deb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/Node.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.LinkedList; -import java.util.List; - - -public class Node { - T child; - List parents; - - @Override - public int hashCode(){ - return child.hashCode(); - } - - @Override - public boolean equals(Object object){ - if(object == null){ - return false; - } - if(!(object instanceof Node)){ - return false; - } - Node node = (Node)object; - return this.child.equals(node.getChild()); - } - - public Node(T child){ - this.child = child; - this.parents = new LinkedList<>(); - } - - public T getChild() { - return child; - } - - public List getParents() { - return parents; - } - - public void addParent(T parent){ - this.parents.add(parent); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Node : child = " + child + " , parents = "); - for(T parent:parents){ - stringBuilder.append(parent).append(","); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java deleted file mode 100644 index 278d6fcaa..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.Set; - -import org.onap.appc.domainmodel.Vnfc; - - -public class VnfcDependencyModel { - private Set> dependencies; - - public VnfcDependencyModel(Set> dependencies){ - this.dependencies = dependencies; - } - - public Set> getDependencies() { - return dependencies; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("dependencies = "); - for(Node node:dependencies){ - stringBuilder.append(node.toString()).append(", "); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java deleted file mode 100644 index 1100e42cb..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcFlowModel.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.objects; - -import java.util.*; - -import org.onap.appc.domainmodel.Vnfc; - - -public class VnfcFlowModel { - private Map> flowModelMap; - - private VnfcFlowModel(VnfcFlowModelBuilder builder){ - this.flowModelMap = builder.map; - - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Flow Model : "); - Iterator> iterator = getModelIterator(); - while(iterator.hasNext()){ - for(Vnfc vnfc:iterator.next()){ - stringBuilder.append(vnfc.toString()).append(", \n"); - } - } - - return stringBuilder.toString(); - } - - public Iterator> getModelIterator(){ - return flowModelMap.values().iterator(); - } - - public static class VnfcFlowModelBuilder{ - - Map> map; - - public VnfcFlowModelBuilder(){ - map = new HashMap<>(); - } - - public VnfcFlowModelBuilder addMetadata(Integer index,Vnfc vnfc){ - List vnfcList = this.map.get(index); - if(vnfcList == null){ - vnfcList = new LinkedList<>(); - map.put(index,vnfcList); - } - vnfcList.add(vnfc); - return this; - } - - public VnfcFlowModelBuilder addMetadata(Integer index,List vnfcs){ - List vnfcList = this.map.get(index); - if(vnfcList == null){ - vnfcList = new LinkedList<>(); - map.put(index,vnfcList); - } - vnfcList.addAll(vnfcs); - return this; - } - - public VnfcFlowModel build(){ - return new VnfcFlowModel(this); - } - - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java new file mode 100644 index 000000000..009515378 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/onap/appc/dg/flowbuilder/TestFlowBuilder.java @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.flowbuilder; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.dg.flowbuilder.FlowBuilder; +import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; +import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; +import org.onap.appc.dg.objects.*; +import org.onap.appc.domainmodel.Vnf; +import org.onap.appc.domainmodel.Vnfc; +import org.onap.appc.domainmodel.Vserver; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + + +public class TestFlowBuilder { + + @Test + public void testForwardFlowBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); + } + + @Test + public void testReverseFlowBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); + VnfcDependencyModel dependencyModel = readDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); + } + + @Test + public void testComplexFlowBuilderForward(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + InventoryModel inventoryModel = readComplexInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); + Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); + Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); + Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); + + } + + @Test + public void testComplexFlowBuilderReverse(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); + VnfcDependencyModel dependencyModel = readComplexDependencyModel(); + InventoryModel inventoryModel = readComplexInventoryModel(); + VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); + Iterator> itr = flowModel.getModelIterator(); + + List list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); + + Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); + Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); + + list = itr.next(); + Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); + Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); + + } + + @Test(expected = InvalidDependencyModel.class) + public void testCyclicBuilder(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); + InventoryModel inventoryModel = readInventoryModel(); + builder.buildFlowModel(dependencyModel,inventoryModel); + } + + @Test(expected = InvalidDependencyModel.class) + public void testCyclicBuilderWithRootNode(){ + FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); + VnfcDependencyModel dependencyModel = readCyclicDependencyModelWithRootNode(); + InventoryModel inventoryModel = readInventoryModel(); + builder.buildFlowModel(dependencyModel,inventoryModel); + } + + private VnfcDependencyModel readCyclicDependencyModelWithRootNode() { + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + + bNode.addParent(c); + cNode.addParent(b); + + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + + return new VnfcDependencyModel(dependencies); + } + + private InventoryModel readComplexInventoryModel() { + Vnf vnf = new Vnf("vnf_1","vABCD","1"); + + Vnfc vnfcA = new Vnfc("A","Active-Active","A_Name"); + Vnfc vnfcB = new Vnfc("B","Active-Active","B_Name"); + Vnfc vnfcC = new Vnfc("C","Active-Active","C_Name"); + Vnfc vnfcD = new Vnfc("D","Active-Active","D_Name"); + Vnfc vnfcE = new Vnfc("E","Active-Active","E_Name"); + Vnfc vnfcF = new Vnfc("F","Active-Active","F_Name"); + Vnfc vnfcG = new Vnfc("G","Active-Active","G_Name"); + + vnfcA.addVm(new Vserver("VM_URL_A1")); + vnfcB.addVm(new Vserver("VM_URL_B1")); + vnfcC.addVm(new Vserver("VM_URL_C1")); + vnfcD.addVm(new Vserver("VM_URL_D1")); + vnfcE.addVm(new Vserver("VM_URL_E1")); + vnfcF.addVm(new Vserver("VM_URL_F1")); + vnfcG.addVm(new Vserver("VM_URL_G1")); + + vnf.addVnfc(vnfcA); + vnf.addVnfc(vnfcB); + vnf.addVnfc(vnfcC); + vnf.addVnfc(vnfcD); + vnf.addVnfc(vnfcE); + vnf.addVnfc(vnfcF); + vnf.addVnfc(vnfcG); + + return new InventoryModel(vnf); + } + + private VnfcDependencyModel readComplexDependencyModel() { + Vnfc a = new Vnfc("A","Active-Active",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + Vnfc e = new Vnfc("E","Active-Active",null); + Vnfc f = new Vnfc("F","Active-Active",null); + Vnfc g = new Vnfc("G","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + Node eNode = new Node(e); + Node fNode = new Node(f); + Node gNode = new Node(g); + + bNode.addParent(a); + cNode.addParent(a); + + bNode.addParent(e); + cNode.addParent(e); + + dNode.addParent(b); + gNode.addParent(b); + + fNode.addParent(c); + + gNode.addParent(f); + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + dependencies.add(eNode); + dependencies.add(fNode); + dependencies.add(gNode); + + return new VnfcDependencyModel(dependencies); + } + + private VnfcDependencyModel readCyclicDependencyModel() { + + Vnfc a = new Vnfc("A","Active-Passive",null); + Vnfc b = new Vnfc("B","Active-Active",null); + Vnfc c = new Vnfc("C","Active-Active",null); + Vnfc d = new Vnfc("D","Active-Active",null); + + + Node aNode = new Node(a); + Node bNode = new Node(b); + Node cNode = new Node(c); + Node dNode = new Node(d); + + bNode.addParent(a); + + bNode.addParent(d); + dNode.addParent(c); + cNode.addParent(b); + + + Set> dependencies = new HashSet<>(); + dependencies.add(aNode); + dependencies.add(bNode); + dependencies.add(cNode); + dependencies.add(dNode); + + return new VnfcDependencyModel(dependencies); + + } + + private InventoryModel readInventoryModel() { + Vnf vnf = new Vnf("vnf_1","vSCP","1"); + + Vnfc smp = new Vnfc("SMP",null,"SMP_Name"); + Vserver smpVm1 = new Vserver("SMP_URL1"); + Vserver smpVm2 = new Vserver("SMP_URL2"); + + smp.addVm(smpVm1); + smp.addVm(smpVm2); + + Vnfc be = new Vnfc("BE",null,"BE_Name"); + + Vserver beVm1 = new Vserver("BE_URL1"); + Vserver beVm2 = new Vserver("BE_URL2"); + Vserver beVm3 = new Vserver("BE_URL3"); + Vserver beVm4 = new Vserver("BE_URL4"); + Vserver beVm5 = new Vserver("BE_URL5"); + + be.addVm(beVm1); + be.addVm(beVm2); + be.addVm(beVm3); + be.addVm(beVm4); + be.addVm(beVm5); + + Vnfc fe = new Vnfc("FE",null,"FE_Name"); + + Vserver feVm1 = new Vserver("FE_URL1"); + Vserver feVm2 = new Vserver("FE_URL2"); + + fe.addVm(feVm1); + fe.addVm(feVm2); + + vnf.addVnfc(smp); + vnf.addVnfc(be); + vnf.addVnfc(fe); + + return new InventoryModel(vnf); + } + + private VnfcDependencyModel readDependencyModel() { + Vnfc smp = new Vnfc("SMP","Active-Passive",null); + Vnfc be = new Vnfc("BE","Active-Active",null); + Vnfc fe = new Vnfc("FE","Active-Active",null); + + + Node smpNode = new Node(smp); + Node beNode = new Node(be); + Node feNode = new Node(fe); + + beNode.addParent(smp); + feNode.addParent(be); + + Set> dependencies = new HashSet<>(); + dependencies.add(smpNode); + dependencies.add(feNode); + dependencies.add(beNode); + + return new VnfcDependencyModel(dependencies); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java b/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java deleted file mode 100644 index 009515378..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-dependency-model/src/test/java/org/openecomp/appc/dg/flowbuilder/TestFlowBuilder.java +++ /dev/null @@ -1,332 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.flowbuilder; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.dg.flowbuilder.FlowBuilder; -import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModel; -import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory; -import org.onap.appc.dg.objects.*; -import org.onap.appc.domainmodel.Vnf; -import org.onap.appc.domainmodel.Vnfc; -import org.onap.appc.domainmodel.Vserver; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - - -public class TestFlowBuilder { - - @Test - public void testForwardFlowBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); - } - - @Test - public void testReverseFlowBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); - VnfcDependencyModel dependencyModel = readDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("FE","Active-Active","FE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("BE","Active-Active","BE_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("SMP","Active-Passive","SMP_Name"))); - } - - @Test - public void testComplexFlowBuilderForward(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - InventoryModel inventoryModel = readComplexInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); - Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); - Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); - Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); - - } - - @Test - public void testComplexFlowBuilderReverse(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE); - VnfcDependencyModel dependencyModel = readComplexDependencyModel(); - InventoryModel inventoryModel = readComplexInventoryModel(); - VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel); - Iterator> itr = flowModel.getModelIterator(); - - List list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("D","Active-Active","D_Name"))); - - Assert.assertTrue(list.contains(new Vnfc("G","Active-Active","G_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("B","Active-Active","B_Name"))); - Assert.assertTrue(list.contains(new Vnfc("F","Active-Active","F_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("C","Active-Active","C_Name"))); - - list = itr.next(); - Assert.assertTrue(list.contains(new Vnfc("E","Active-Active","E_Name"))); - Assert.assertTrue(list.contains(new Vnfc("A","Active-Active","A_Name"))); - - } - - @Test(expected = InvalidDependencyModel.class) - public void testCyclicBuilder(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readCyclicDependencyModel(); - InventoryModel inventoryModel = readInventoryModel(); - builder.buildFlowModel(dependencyModel,inventoryModel); - } - - @Test(expected = InvalidDependencyModel.class) - public void testCyclicBuilderWithRootNode(){ - FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD); - VnfcDependencyModel dependencyModel = readCyclicDependencyModelWithRootNode(); - InventoryModel inventoryModel = readInventoryModel(); - builder.buildFlowModel(dependencyModel,inventoryModel); - } - - private VnfcDependencyModel readCyclicDependencyModelWithRootNode() { - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - - bNode.addParent(c); - cNode.addParent(b); - - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - - return new VnfcDependencyModel(dependencies); - } - - private InventoryModel readComplexInventoryModel() { - Vnf vnf = new Vnf("vnf_1","vABCD","1"); - - Vnfc vnfcA = new Vnfc("A","Active-Active","A_Name"); - Vnfc vnfcB = new Vnfc("B","Active-Active","B_Name"); - Vnfc vnfcC = new Vnfc("C","Active-Active","C_Name"); - Vnfc vnfcD = new Vnfc("D","Active-Active","D_Name"); - Vnfc vnfcE = new Vnfc("E","Active-Active","E_Name"); - Vnfc vnfcF = new Vnfc("F","Active-Active","F_Name"); - Vnfc vnfcG = new Vnfc("G","Active-Active","G_Name"); - - vnfcA.addVm(new Vserver("VM_URL_A1")); - vnfcB.addVm(new Vserver("VM_URL_B1")); - vnfcC.addVm(new Vserver("VM_URL_C1")); - vnfcD.addVm(new Vserver("VM_URL_D1")); - vnfcE.addVm(new Vserver("VM_URL_E1")); - vnfcF.addVm(new Vserver("VM_URL_F1")); - vnfcG.addVm(new Vserver("VM_URL_G1")); - - vnf.addVnfc(vnfcA); - vnf.addVnfc(vnfcB); - vnf.addVnfc(vnfcC); - vnf.addVnfc(vnfcD); - vnf.addVnfc(vnfcE); - vnf.addVnfc(vnfcF); - vnf.addVnfc(vnfcG); - - return new InventoryModel(vnf); - } - - private VnfcDependencyModel readComplexDependencyModel() { - Vnfc a = new Vnfc("A","Active-Active",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - Vnfc e = new Vnfc("E","Active-Active",null); - Vnfc f = new Vnfc("F","Active-Active",null); - Vnfc g = new Vnfc("G","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - Node eNode = new Node(e); - Node fNode = new Node(f); - Node gNode = new Node(g); - - bNode.addParent(a); - cNode.addParent(a); - - bNode.addParent(e); - cNode.addParent(e); - - dNode.addParent(b); - gNode.addParent(b); - - fNode.addParent(c); - - gNode.addParent(f); - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - dependencies.add(eNode); - dependencies.add(fNode); - dependencies.add(gNode); - - return new VnfcDependencyModel(dependencies); - } - - private VnfcDependencyModel readCyclicDependencyModel() { - - Vnfc a = new Vnfc("A","Active-Passive",null); - Vnfc b = new Vnfc("B","Active-Active",null); - Vnfc c = new Vnfc("C","Active-Active",null); - Vnfc d = new Vnfc("D","Active-Active",null); - - - Node aNode = new Node(a); - Node bNode = new Node(b); - Node cNode = new Node(c); - Node dNode = new Node(d); - - bNode.addParent(a); - - bNode.addParent(d); - dNode.addParent(c); - cNode.addParent(b); - - - Set> dependencies = new HashSet<>(); - dependencies.add(aNode); - dependencies.add(bNode); - dependencies.add(cNode); - dependencies.add(dNode); - - return new VnfcDependencyModel(dependencies); - - } - - private InventoryModel readInventoryModel() { - Vnf vnf = new Vnf("vnf_1","vSCP","1"); - - Vnfc smp = new Vnfc("SMP",null,"SMP_Name"); - Vserver smpVm1 = new Vserver("SMP_URL1"); - Vserver smpVm2 = new Vserver("SMP_URL2"); - - smp.addVm(smpVm1); - smp.addVm(smpVm2); - - Vnfc be = new Vnfc("BE",null,"BE_Name"); - - Vserver beVm1 = new Vserver("BE_URL1"); - Vserver beVm2 = new Vserver("BE_URL2"); - Vserver beVm3 = new Vserver("BE_URL3"); - Vserver beVm4 = new Vserver("BE_URL4"); - Vserver beVm5 = new Vserver("BE_URL5"); - - be.addVm(beVm1); - be.addVm(beVm2); - be.addVm(beVm3); - be.addVm(beVm4); - be.addVm(beVm5); - - Vnfc fe = new Vnfc("FE",null,"FE_Name"); - - Vserver feVm1 = new Vserver("FE_URL1"); - Vserver feVm2 = new Vserver("FE_URL2"); - - fe.addVm(feVm1); - fe.addVm(feVm2); - - vnf.addVnfc(smp); - vnf.addVnfc(be); - vnf.addVnfc(fe); - - return new InventoryModel(vnf); - } - - private VnfcDependencyModel readDependencyModel() { - Vnfc smp = new Vnfc("SMP","Active-Passive",null); - Vnfc be = new Vnfc("BE","Active-Active",null); - Vnfc fe = new Vnfc("FE","Active-Active",null); - - - Node smpNode = new Node(smp); - Node beNode = new Node(be); - Node feNode = new Node(fe); - - beNode.addParent(smp); - feNode.addParent(be); - - Set> dependencies = new HashSet<>(); - dependencies.add(smpNode); - dependencies.add(feNode); - dependencies.add(beNode); - - return new VnfcDependencyModel(dependencies); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java new file mode 100644 index 000000000..9f75779cd --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnf.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + +import java.util.LinkedList; +import java.util.List; + +public class Vnf { + private String vnfId; + private String vnfType; + private String vnfVersion; + + private List vnfcs; + + public Vnf(String vnfId,String vnfType,String vnfVersion){ + this.vnfId = vnfId; + this.vnfType = vnfType; + this.vnfVersion = vnfVersion; + this.vnfcs = new LinkedList<>(); + } + + public String getVnfVersion() { + return vnfVersion; + } + + public String getVnfId() { + return vnfId; + } + + public String getVnfType() { + return vnfType; + } + + public void addVnfc(Vnfc vnfc){ + this.vnfcs.add(vnfc); + } + + public List getVnfcs() { + return vnfcs; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Vnf : vnfId = " + vnfId +" , vnfType = " + vnfType); + for(Vnfc vnfc:vnfcs){ + stringBuilder.append(vnfc.toString()).append(","); + } + return stringBuilder.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java new file mode 100644 index 000000000..de075f085 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vnfc.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + +import java.util.LinkedList; +import java.util.List; + + +public class Vnfc { + + private String vnfcType; + + public void setResilienceType(String resilienceType) { + this.resilienceType = resilienceType; + } + + private String resilienceType; + private boolean mandatory; + private String vnfcName; + private List vserverList; + + public Vnfc(String vnfcType,String resilienceType){ + this(vnfcType,resilienceType,null, false); + } + + public Vnfc(String vnfcType,String resilienceType,String vnfcName){ + this(vnfcType,resilienceType,vnfcName, false); + } + + public Vnfc(String vnfcType,String resilienceType,String vnfcName, boolean mandatory){ + this.vnfcName = vnfcName; + this.vnfcType = vnfcType; + this.resilienceType = resilienceType; + this.mandatory = mandatory; + this.vserverList = new LinkedList<>(); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("Vnfc : vnfcType = " + vnfcType + ", vnfcName = " +vnfcName + ", resilienceType = " + resilienceType+", mandatory = " + mandatory); + for(Vserver vserver:vserverList){ + stringBuilder.append(vserver.toString()).append(", \n"); + } + return stringBuilder.toString(); + } + + @Override + public int hashCode(){ + final int prime = 31; + int result = 1; + result = result * prime + (this.vnfcType == null ? 0 :this.vnfcType.hashCode()); + result = result * prime + (this.resilienceType == null ? 0 :this.resilienceType.hashCode()); + result = result * prime + (this.vnfcName == null ? 0 :this.vnfcName.hashCode()); + result = result * prime + (Boolean.valueOf(this.mandatory).hashCode()); + return result; + } + @Override + public boolean equals(Object object){ + if(object == null){ + return false; + } + if(!(object instanceof Vnfc)){ + return false; + } + Vnfc vnfc = (Vnfc)object; + + if(this.vnfcType == null){ + if(vnfc.vnfcType !=null) + return false; + } + else if(!this.vnfcType.equals(vnfc.vnfcType)) + return false; + + if(this.resilienceType == null){ + if(vnfc.resilienceType !=null) + return false; + } + else if(!this.resilienceType.equals(vnfc.resilienceType)) + return false; + + if(this.vnfcName == null){ + if(vnfc.vnfcName !=null) + return false; + } + else if(!this.vnfcName.equals(vnfc.vnfcName)) + return false; + if (this.mandatory != vnfc.mandatory) + return false; + return true; + } + + public void addVm(Vserver vserver){ + this.vserverList.add(vserver); + } + public void addVms(List vserverList){ + this.vserverList.addAll(vserverList); + } + + public void setVnfcName(String vnfcName) { + this.vnfcName = vnfcName; + } + + public String getVnfcType() { + return vnfcType; + } + + public String getResilienceType() { + return resilienceType; + } + + public String getVnfcName() { + return vnfcName; + } + + public List getVserverList() { + return vserverList; + } + + public boolean isMandatory() { + return mandatory; + } + + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java new file mode 100644 index 000000000..0840bd91e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/onap/appc/domainmodel/Vserver.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.domainmodel; + + +public class Vserver { + + private String url; + + private String tenantId; + private String id; + private String relatedLink; + private String name; + + public Vserver(String url){ + this(url,null,null,null,null); + } + + public Vserver(String url, + String tenantId, + String id, + String relatedLink, + String name){ + this.url = url; + this.tenantId =tenantId; + this.id = id; + this.relatedLink =relatedLink; + this.name = name; + + } + + public String getUrl() { + return url; + } + + @Override + public String toString() { + return "Vserver : url = " +url + ", tenantId = " +tenantId +", id = " +id + " ,relatedLink = " +relatedLink +" , name = "+name; + } + + public String getTenantId() { + return tenantId; + } + + public String getId() { + return id; + } + + public String getRelatedLink() { + return relatedLink; + } + + public String getName() { + return name; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java deleted file mode 100644 index 9f75779cd..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnf.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - -import java.util.LinkedList; -import java.util.List; - -public class Vnf { - private String vnfId; - private String vnfType; - private String vnfVersion; - - private List vnfcs; - - public Vnf(String vnfId,String vnfType,String vnfVersion){ - this.vnfId = vnfId; - this.vnfType = vnfType; - this.vnfVersion = vnfVersion; - this.vnfcs = new LinkedList<>(); - } - - public String getVnfVersion() { - return vnfVersion; - } - - public String getVnfId() { - return vnfId; - } - - public String getVnfType() { - return vnfType; - } - - public void addVnfc(Vnfc vnfc){ - this.vnfcs.add(vnfc); - } - - public List getVnfcs() { - return vnfcs; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Vnf : vnfId = " + vnfId +" , vnfType = " + vnfType); - for(Vnfc vnfc:vnfcs){ - stringBuilder.append(vnfc.toString()).append(","); - } - return stringBuilder.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java deleted file mode 100644 index de075f085..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vnfc.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - -import java.util.LinkedList; -import java.util.List; - - -public class Vnfc { - - private String vnfcType; - - public void setResilienceType(String resilienceType) { - this.resilienceType = resilienceType; - } - - private String resilienceType; - private boolean mandatory; - private String vnfcName; - private List vserverList; - - public Vnfc(String vnfcType,String resilienceType){ - this(vnfcType,resilienceType,null, false); - } - - public Vnfc(String vnfcType,String resilienceType,String vnfcName){ - this(vnfcType,resilienceType,vnfcName, false); - } - - public Vnfc(String vnfcType,String resilienceType,String vnfcName, boolean mandatory){ - this.vnfcName = vnfcName; - this.vnfcType = vnfcType; - this.resilienceType = resilienceType; - this.mandatory = mandatory; - this.vserverList = new LinkedList<>(); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("Vnfc : vnfcType = " + vnfcType + ", vnfcName = " +vnfcName + ", resilienceType = " + resilienceType+", mandatory = " + mandatory); - for(Vserver vserver:vserverList){ - stringBuilder.append(vserver.toString()).append(", \n"); - } - return stringBuilder.toString(); - } - - @Override - public int hashCode(){ - final int prime = 31; - int result = 1; - result = result * prime + (this.vnfcType == null ? 0 :this.vnfcType.hashCode()); - result = result * prime + (this.resilienceType == null ? 0 :this.resilienceType.hashCode()); - result = result * prime + (this.vnfcName == null ? 0 :this.vnfcName.hashCode()); - result = result * prime + (Boolean.valueOf(this.mandatory).hashCode()); - return result; - } - @Override - public boolean equals(Object object){ - if(object == null){ - return false; - } - if(!(object instanceof Vnfc)){ - return false; - } - Vnfc vnfc = (Vnfc)object; - - if(this.vnfcType == null){ - if(vnfc.vnfcType !=null) - return false; - } - else if(!this.vnfcType.equals(vnfc.vnfcType)) - return false; - - if(this.resilienceType == null){ - if(vnfc.resilienceType !=null) - return false; - } - else if(!this.resilienceType.equals(vnfc.resilienceType)) - return false; - - if(this.vnfcName == null){ - if(vnfc.vnfcName !=null) - return false; - } - else if(!this.vnfcName.equals(vnfc.vnfcName)) - return false; - if (this.mandatory != vnfc.mandatory) - return false; - return true; - } - - public void addVm(Vserver vserver){ - this.vserverList.add(vserver); - } - public void addVms(List vserverList){ - this.vserverList.addAll(vserverList); - } - - public void setVnfcName(String vnfcName) { - this.vnfcName = vnfcName; - } - - public String getVnfcType() { - return vnfcType; - } - - public String getResilienceType() { - return resilienceType; - } - - public String getVnfcName() { - return vnfcName; - } - - public List getVserverList() { - return vserverList; - } - - public boolean isMandatory() { - return mandatory; - } - - public void setMandatory(boolean mandatory) { - this.mandatory = mandatory; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java b/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java deleted file mode 100644 index 0840bd91e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/Vserver.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.domainmodel; - - -public class Vserver { - - private String url; - - private String tenantId; - private String id; - private String relatedLink; - private String name; - - public Vserver(String url){ - this(url,null,null,null,null); - } - - public Vserver(String url, - String tenantId, - String id, - String relatedLink, - String name){ - this.url = url; - this.tenantId =tenantId; - this.id = id; - this.relatedLink =relatedLink; - this.name = name; - - } - - public String getUrl() { - return url; - } - - @Override - public String toString() { - return "Vserver : url = " +url + ", tenantId = " +tenantId +", id = " +id + " ,relatedLink = " +relatedLink +" , name = "+name; - } - - public String getTenantId() { - return tenantId; - } - - public String getId() { - return id; - } - - public String getRelatedLink() { - return relatedLink; - } - - public String getName() { - return name; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java new file mode 100644 index 000000000..cfe263ff9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/LicenseManagerPlugin.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.licmgr; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface LicenseManagerPlugin extends SvcLogicJavaPlugin { + /** + * Retrieves license model from APPC database and populate flags into svc context + * @param params map with parameters: + * org.onap.appc.vftype - the vnf type / service type; + * org.onap.appc.resource-version - the vnf version / service version + * @param ctx service logic context + * 1. supposed properties already in context: + * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI + * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI + * 2. properties and flags stored in context after bean execution: + * model.entitlement.pool.uuid - entitlement-group-uuid from license model + * model.license.key.uuid - license-key-uuid from license model + * is.acquire-entitlement.require + * is.release-entitlement.require + * is.acquire-license.require + * is.release-license.require + * + * @throws APPCException throws in case of any error + */ + void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java new file mode 100644 index 000000000..4a72c2358 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/onap/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.licmgr.impl; + +import java.util.Map; + +import org.onap.appc.dg.licmgr.LicenseManagerPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.licmgr.Constants; +import org.onap.appc.licmgr.LicenseManager; +import org.onap.appc.licmgr.exception.DataAccessException; +import org.onap.appc.licmgr.objects.LicenseModel; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class LicenseManagerPluginImpl implements LicenseManagerPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + // populated by blueprint framework + private LicenseManager licenseManager; + + public void setLicenseManager(LicenseManager licenseManager) { + this.licenseManager = licenseManager; + } + + /** + * Retrieves license model from APPC database and populate flags into svc context + * @param params map with parameters: + * org.onap.appc.vftype - the vnf type / service type; + * org.onap.appc.resource-version - the vnf version / service version + * @param ctx service logic context + * 1. supposed properties already in context: + * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI + * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI + * 2. properties and flags stored in context after bean execution: + * model.entitlement.pool.uuid - entitlement-group-uuid from license model + * model.license.key.uuid - license-key-uuid from license model + * is.acquire-entitlement.require + * is.release-entitlement.require + * is.acquire-license.require + * is.release-license.require + * is.aai-entitlement-update.require + * is.aai-license-update.require + * + * @throws APPCException throws in case of any error + */ + @Override + public void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException { + + try { + + LicenseModel licenseModel = licenseManager.retrieveLicenseModel(params.get(Constants.VNF_TYPE_FIELD_NAME), params.get(Constants.VNF_RESOURCE_VERSION_FIELD_NAME)); + + String modelEntitlementPoolUuid = licenseModel.getEntitlementPoolUuid(); if (null == modelEntitlementPoolUuid) modelEntitlementPoolUuid = ""; + String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; + boolean isAcquireEntitlementRequire = !modelEntitlementPoolUuid.isEmpty() && !modelEntitlementPoolUuid.equals(aaiEntitlementPoolUuid); + boolean isReleaseEntitlementRequire = !aaiEntitlementPoolUuid.isEmpty() && (isAcquireEntitlementRequire || modelEntitlementPoolUuid.isEmpty()); + boolean isAAIEntitlementUpdateRequire = isAcquireEntitlementRequire || isReleaseEntitlementRequire; + ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, modelEntitlementPoolUuid); + ctx.setAttribute(Constants.IS_ACQUIRE_ENTITLEMENT_REQUIRE, Boolean.toString(isAcquireEntitlementRequire)); + ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(isReleaseEntitlementRequire)); + ctx.setAttribute(Constants.IS_AAI_ENTITLEMENT_UPDATE_REQUIRE, Boolean.toString(isAAIEntitlementUpdateRequire)); + + + String modelLicenseKeyGroupUuid = licenseModel.getLicenseKeyGroupUuid(); if (null == modelLicenseKeyGroupUuid) modelLicenseKeyGroupUuid = ""; + String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; + String aaiLicenseKeyValue = ctx.getAttribute(Constants.AAI_LICENSE_KEY_VALUE); if (null == aaiLicenseKeyValue) aaiLicenseKeyValue = ""; + boolean isAcquireLicenseRequire = !modelLicenseKeyGroupUuid.isEmpty() && !modelLicenseKeyGroupUuid.equals(aaiLicenseKeyGroupUuid); + boolean isReleaseLicenseRequire = !aaiLicenseKeyGroupUuid.isEmpty() && (isAcquireLicenseRequire || modelLicenseKeyGroupUuid.isEmpty()); + boolean isAAILicenseUpdateRequire = isAcquireLicenseRequire || isReleaseLicenseRequire; + ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, modelLicenseKeyGroupUuid); + ctx.setAttribute(Constants.IS_ACQUIRE_LICENSE_REQUIRE, Boolean.toString(isAcquireLicenseRequire)); + ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(isReleaseLicenseRequire)); + ctx.setAttribute(Constants.IS_AAI_LICENSE_UPDATE_REQUIRE, Boolean.toString(isAAILicenseUpdateRequire)); + + ctx.setAttribute("license-key", aaiLicenseKeyValue); + + } catch (DataAccessException le) { + logger.error("Error " + le.getMessage()); + ctx.setAttribute("output.status.message", le.getMessage()); + throw new APPCException(le); + } + + } + + + + //////// code uses jaxb license model, should be fixed + /* + final VfLicenseModel.FeatureGroupList featureGroupList = licenseModel.getFeatureGroupList(); + if (null != featureGroupList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup featureGroup = featureGroupList.getFeatureGroup(); + if (null != featureGroup) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList + entitlementPoolList = featureGroup.getEntitlementPoolList(); + if (null != entitlementPoolList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList.EntitlementPool + entitlementPool = entitlementPoolList.getEntitlementPool(); + if (null != entitlementPool) { + final String entitlementPoolUuid = entitlementPool.getEntitlementPoolUuid(); + // add entitlementPoolUuid into context + ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, entitlementPoolUuid); + } + } + + final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList + licenseKeyGroupList = featureGroup.getLicenseKeyGroupList(); + if (null != licenseKeyGroupList) { + final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList.LicenseKeyGroup + licenseKeyGroup = licenseKeyGroupList.getLicenseKeyGroup(); + if (null != licenseKeyGroup) { + final String licenseKeyGroupUuid = licenseKeyGroup.getLicenseKeyGroupUuid(); + // add licenseKeyGroupUuid into context + ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, licenseKeyGroupUuid); + } + } + } + } + */ + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java deleted file mode 100644 index cfe263ff9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/LicenseManagerPlugin.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.licmgr; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface LicenseManagerPlugin extends SvcLogicJavaPlugin { - /** - * Retrieves license model from APPC database and populate flags into svc context - * @param params map with parameters: - * org.onap.appc.vftype - the vnf type / service type; - * org.onap.appc.resource-version - the vnf version / service version - * @param ctx service logic context - * 1. supposed properties already in context: - * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI - * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI - * 2. properties and flags stored in context after bean execution: - * model.entitlement.pool.uuid - entitlement-group-uuid from license model - * model.license.key.uuid - license-key-uuid from license model - * is.acquire-entitlement.require - * is.release-entitlement.require - * is.acquire-license.require - * is.release-license.require - * - * @throws APPCException throws in case of any error - */ - void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java deleted file mode 100644 index 4a72c2358..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-license-manager/src/main/java/org/openecomp/appc/dg/licmgr/impl/LicenseManagerPluginImpl.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.licmgr.impl; - -import java.util.Map; - -import org.onap.appc.dg.licmgr.LicenseManagerPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.licmgr.Constants; -import org.onap.appc.licmgr.LicenseManager; -import org.onap.appc.licmgr.exception.DataAccessException; -import org.onap.appc.licmgr.objects.LicenseModel; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class LicenseManagerPluginImpl implements LicenseManagerPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - // populated by blueprint framework - private LicenseManager licenseManager; - - public void setLicenseManager(LicenseManager licenseManager) { - this.licenseManager = licenseManager; - } - - /** - * Retrieves license model from APPC database and populate flags into svc context - * @param params map with parameters: - * org.onap.appc.vftype - the vnf type / service type; - * org.onap.appc.resource-version - the vnf version / service version - * @param ctx service logic context - * 1. supposed properties already in context: - * aai.input.data.entitlement-assignment-group-uuid - entitlement-group-uuid asset tag already stored in AAI - * aai.input.data.license-assignment-group-uuid - license-key-uuid asset tag already stored in AAI - * 2. properties and flags stored in context after bean execution: - * model.entitlement.pool.uuid - entitlement-group-uuid from license model - * model.license.key.uuid - license-key-uuid from license model - * is.acquire-entitlement.require - * is.release-entitlement.require - * is.acquire-license.require - * is.release-license.require - * is.aai-entitlement-update.require - * is.aai-license-update.require - * - * @throws APPCException throws in case of any error - */ - @Override - public void retrieveLicenseModel(Map params, SvcLogicContext ctx) throws APPCException { - - try { - - LicenseModel licenseModel = licenseManager.retrieveLicenseModel(params.get(Constants.VNF_TYPE_FIELD_NAME), params.get(Constants.VNF_RESOURCE_VERSION_FIELD_NAME)); - - String modelEntitlementPoolUuid = licenseModel.getEntitlementPoolUuid(); if (null == modelEntitlementPoolUuid) modelEntitlementPoolUuid = ""; - String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME); if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = ""; - boolean isAcquireEntitlementRequire = !modelEntitlementPoolUuid.isEmpty() && !modelEntitlementPoolUuid.equals(aaiEntitlementPoolUuid); - boolean isReleaseEntitlementRequire = !aaiEntitlementPoolUuid.isEmpty() && (isAcquireEntitlementRequire || modelEntitlementPoolUuid.isEmpty()); - boolean isAAIEntitlementUpdateRequire = isAcquireEntitlementRequire || isReleaseEntitlementRequire; - ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, modelEntitlementPoolUuid); - ctx.setAttribute(Constants.IS_ACQUIRE_ENTITLEMENT_REQUIRE, Boolean.toString(isAcquireEntitlementRequire)); - ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(isReleaseEntitlementRequire)); - ctx.setAttribute(Constants.IS_AAI_ENTITLEMENT_UPDATE_REQUIRE, Boolean.toString(isAAIEntitlementUpdateRequire)); - - - String modelLicenseKeyGroupUuid = licenseModel.getLicenseKeyGroupUuid(); if (null == modelLicenseKeyGroupUuid) modelLicenseKeyGroupUuid = ""; - String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME); if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = ""; - String aaiLicenseKeyValue = ctx.getAttribute(Constants.AAI_LICENSE_KEY_VALUE); if (null == aaiLicenseKeyValue) aaiLicenseKeyValue = ""; - boolean isAcquireLicenseRequire = !modelLicenseKeyGroupUuid.isEmpty() && !modelLicenseKeyGroupUuid.equals(aaiLicenseKeyGroupUuid); - boolean isReleaseLicenseRequire = !aaiLicenseKeyGroupUuid.isEmpty() && (isAcquireLicenseRequire || modelLicenseKeyGroupUuid.isEmpty()); - boolean isAAILicenseUpdateRequire = isAcquireLicenseRequire || isReleaseLicenseRequire; - ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, modelLicenseKeyGroupUuid); - ctx.setAttribute(Constants.IS_ACQUIRE_LICENSE_REQUIRE, Boolean.toString(isAcquireLicenseRequire)); - ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(isReleaseLicenseRequire)); - ctx.setAttribute(Constants.IS_AAI_LICENSE_UPDATE_REQUIRE, Boolean.toString(isAAILicenseUpdateRequire)); - - ctx.setAttribute("license-key", aaiLicenseKeyValue); - - } catch (DataAccessException le) { - logger.error("Error " + le.getMessage()); - ctx.setAttribute("output.status.message", le.getMessage()); - throw new APPCException(le); - } - - } - - - - //////// code uses jaxb license model, should be fixed - /* - final VfLicenseModel.FeatureGroupList featureGroupList = licenseModel.getFeatureGroupList(); - if (null != featureGroupList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup featureGroup = featureGroupList.getFeatureGroup(); - if (null != featureGroup) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList - entitlementPoolList = featureGroup.getEntitlementPoolList(); - if (null != entitlementPoolList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.EntitlementPoolList.EntitlementPool - entitlementPool = entitlementPoolList.getEntitlementPool(); - if (null != entitlementPool) { - final String entitlementPoolUuid = entitlementPool.getEntitlementPoolUuid(); - // add entitlementPoolUuid into context - ctx.setAttribute(Constants.MODEL_ENTITLMENT_POOL_UUID_NAME, entitlementPoolUuid); - } - } - - final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList - licenseKeyGroupList = featureGroup.getLicenseKeyGroupList(); - if (null != licenseKeyGroupList) { - final VfLicenseModel.FeatureGroupList.FeatureGroup.LicenseKeyGroupList.LicenseKeyGroup - licenseKeyGroup = licenseKeyGroupList.getLicenseKeyGroup(); - if (null != licenseKeyGroup) { - final String licenseKeyGroupUuid = licenseKeyGroup.getLicenseKeyGroupUuid(); - // add licenseKeyGroupUuid into context - ctx.setAttribute(Constants.MODEL_LICENSE_KEY_UUID_NAME, licenseKeyGroupUuid); - } - } - } - } - */ - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java new file mode 100644 index 000000000..eba364a10 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/MDSALStore.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal; + +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.objects.BundleInfo; + +import java.util.Date; + +/** + * Provides APIs for interacting with MD-SAL store + */ +public interface MDSALStore { + + /** + * Checks the presence of any yang module in the MD-SAL store, + * Due to limitation of SchemaContext interface of ODL that it does not + * contain the information about dynamically loaded yang modules, it + * checks the presence of OSGI bundle + * @param moduleName Name of the Module + * @param revision revision of the Module + * @return returns true- module is present, false - module is absent + */ + boolean isModulePresent(String moduleName, Date revision); + + /** + * This method will be used to store yang module to MD-SAL store + * @param yang - yang module that need to be stored. In String format + * @param bundleInfo - Bundle Information that contains name , description, version , location. These parameters used to create bundle which will push yang to MD-SAL store. + * @throws MDSALStoreException + */ + void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException; + + /** + * This method is used to store configuration JSON to MD-SAL store. It invokes store configuration Operation with required parameters + * @param moduleName - Yang module name where JSON need to be posted + * @param requestId - Request ID which is used as unique key for configuration JSON + * @param configJSON - String value of configuration JSON that needs to be stored in MD-SAl store + * @throws MDSALStoreException + */ + void storeJson(String moduleName , String requestId , String configJSON ) throws MDSALStoreException; + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java new file mode 100644 index 000000000..2bb30b1c2 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/exception/MDSALStoreException.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.exception; + +/** + * This is custom exception type defined for MD-SAL store. All exceptions thrown by mdsal store module need to be wrapped in this class. +*/ + public class MDSALStoreException extends Exception { + + private static final long serialVersionUID = 1L; + + public MDSALStoreException(){ + } + + /** + * Create MDSALStoreException using only message. + * @param message -- message to the caller. + */ + public MDSALStoreException (String message){ + super(message); + } + + /** + * Create MDSALStoreException using orignal cause + * @param cause - cause that is being wrapped / suppressed. + */ + public MDSALStoreException (Throwable cause){ + super(cause); + } + + /** + * + * @param message - message to the caller. + * @param cause - cause that is being wrapped / suppressed . + */ + public MDSALStoreException(String message , Throwable cause){ + super(message , cause); + } + + /** + * + * @param message - message to the caller. + * @param cause - cause that is being wrapped / suppressed . + * @param enableSuppression - Indicates if suppression is enabled. + * @param writableStackTrace - Indicates if writable stacktrace is supported + */ + public MDSALStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java new file mode 100644 index 000000000..bb847477f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/Constants.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; +/** + * This class contains the definitions of all constant values used in the appc-dg-mdsal-store + * These properties are used for creating osgi bundle zip file. It also defines contents for Blueprint.xml file of bundle + */ +public class Constants { + + private Constants(){} + /** + * Manifest attribute for OSGI Bundle Name + */ + public static final String MANIFEST_ATTR_BUNDLE_NAME= "Bundle-Name"; + + /** + * Manifest attribute for OSGI Bundle Symbolic Name + */ + public static final String MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME= "Bundle-SymbolicName"; + + /** + * Manifest attribute for OSGI Bundle Description + */ + public static final String MANIFEST_ATTR_BUNDLE_DESCRIPTION= "Bundle-Description"; + + /** + * Manifest attribute for OSGI Bundle Manifest version + */ + public static final String MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION= "Bundle-ManifestVersion"; + + /** + * Manifest attribute for OSGI Bundle Version + */ + public static final String MANIFEST_ATTR_BUNDLE_VERSION= "Bundle-Version"; + + /** + * Manifest attribute for OSGI Bundle Blueprint + */ + public static final String MANIFEST_ATTR_BUNDLE_BLUEPRINT= "Bundle-Blueprint"; + + /** + * Manifest value for Mainfest Version + */ + public static final String MANIFEST_VALUE_VERSION= "1.0"; + + /** + * Manifest value for OSGI Bundle Vesion + */ + public static final String MANIFEST_VALUE_BUNDLE_MAN_VERSION= "2"; + + /** + * Manifest value for OSGI Bundle Blueprint location + */ + public static final String MANIFEST_VALUE_BUNDLE_BLUEPRINT= "OSGI-INF/blueprint/blueprint.xml"; + + /** + * Base URL for config actions exposed by RESTCONF API + */ + + public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config"; + + public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url"; + + public static final String CONFIG_PATH = "/restconf/config"; + + /** + * Restconf authentication user property name + */ + public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user"; + + /** + * Restconf authentication password property name + */ + public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass"; + + /** + * Content for blueprint.xml used while creation of OSGI bundle. + */ + public static final String BLUEPRINT = "\n" + + "\n" + + "\n" + + "\n" + + ""; + + /** + * HTTP Header attribute for Content type - JSON + */ + public static final String OPERATION_APPLICATION_JSON= " application/json"; + + /** + * HTTP protocol used for config operations + */ + public static final String OPERATION_HTTPS= "https"; + + /** + * Constant for backslash to be used while formatting URL + */ + public static final String URL_BACKSLASH ="/"; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java new file mode 100644 index 000000000..bc951d926 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreFactory.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; + +import org.onap.appc.mdsal.MDSALStore; + +/* + * Factory class to create/get instance of MDSALStore + */ +public class MDSALStoreFactory { + private static class ReferenceHolder{ + private static MDSALStore store = new MDSALStoreImpl(); + private ReferenceHolder(){} + } + private MDSALStoreFactory(){ + + } + + /** + * Method for creating MDSALStore instance, It creates an instance of + * MDSALStoreImpl once and returns the same instance everytime it is invoked. + * @return + */ + public static MDSALStore createMDSALStore (){ + return ReferenceHolder.store; + } +} + diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java new file mode 100644 index 000000000..c9e083557 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/impl/MDSALStoreImpl.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.impl; + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.MDSALStore; +import org.onap.appc.mdsal.exception.MDSALStoreException; +import org.onap.appc.mdsal.objects.BundleInfo; +import org.onap.appc.mdsal.operation.ConfigOperation; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Date; +import java.util.Properties; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +/** + * Implementation of MDSALStore + */ +public class MDSALStoreImpl implements MDSALStore{ + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class); + + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + MDSALStoreImpl(){ + String configUrl = null; + String user =null; + String password = null; + Properties properties = configuration.getProperties(); + if (properties != null) { + configUrl= properties.getProperty( Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT); + user = properties.getProperty(Constants.CONFIG_USER_PROPERTY); + password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY); + } + ConfigOperation.setUrl(configUrl); + ConfigOperation.setAuthentication(user,password); + } + + + @Override + public boolean isModulePresent(String moduleName, Date revision) { + + if(logger.isDebugEnabled()){ + logger.debug("isModulePresent invoked with moduleName = " +moduleName + " , revision = " +revision); + } + + BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + /** + * SchemaContext interface of ODL provides APIs for querying details of yang modules + * loaded into MD-SAL store, but its limitation is, it only returns information about + * static yang modules loaded on server start up, it does not return information about + * the yang modules loaded dynamically. Due to this limitation, we are checking the + * presence of OSGI bundle instead of yang module. (Note: Assuming OSGI bundle is named + * with the yang module name). + */ + + Bundle bundle = bundleContext.getBundle(moduleName); + if(logger.isDebugEnabled()){ + logger.debug("isModulePresent returned = " + (bundle != null)); + } + return bundle != null; + } + + @Override + public void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException { + + BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + byte[] byteArray = createBundleJar(yang, Constants.BLUEPRINT, bundleInfo); + + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray)){ + Bundle bundle = bundleContext.installBundle(bundleInfo.getLocation(), inputStream); + bundle.start(); + } catch (Exception e) { + logger.error("Error storing yang module: " + yang + ". Error message: " + e.getMessage()); + throw new MDSALStoreException("Error storing yang module: " + yang + " " + e.getMessage(), e); + } + } + + @Override + public void storeJson( String module , String requestId ,String configJSON) throws MDSALStoreException { + + try { + ConfigOperation.storeConfig(configJSON , module , org.onap.appc.Constants.YANG_BASE_CONTAINER, org.onap.appc.Constants.YANG_VNF_CONFIG_LIST,requestId,org.onap.appc.Constants.YANG_VNF_CONFIG); + } catch (APPCException e) { + throw new MDSALStoreException("Exception while storing config json to MDSAL store." +e.getMessage(), e); + } + } + + private byte[] createBundleJar(String yang, String blueprint, BundleInfo bundleInfo) throws MDSALStoreException { + + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, Constants.MANIFEST_VALUE_VERSION); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME), bundleInfo.getName()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME), bundleInfo.getName()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION), bundleInfo.getDescription()); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION), Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION), String.valueOf(bundleInfo.getVersion())); + manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT), Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT); + + byte[] retunValue; + + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) { + jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/")); + jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/"+bundleInfo.getName()+".yang")); + jarOutputStream.write(yang.getBytes()); + jarOutputStream.closeEntry(); + + jarOutputStream.putNextEntry(new JarEntry("OSGI-INF/blueprint/")); + jarOutputStream.putNextEntry(new JarEntry(Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT)); + jarOutputStream.write(blueprint.getBytes()); + jarOutputStream.closeEntry(); + jarOutputStream.close(); + retunValue = outputStream.toByteArray(); + } catch (Exception e) { + logger.error("Error creating bundle jar: " + bundleInfo.getName() + ". Error message: " + e.getMessage()); + throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(), e); + } + return retunValue; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java new file mode 100644 index 000000000..b6d65447d --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/objects/BundleInfo.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.objects; +/** + * Holds bundle information which includes name , description , version and location. This information will be used to create osgi bundle. + */ + public class BundleInfo { + + private String name; + private String description; + private Integer version; + private String location; + + /** + * Creates an object of BundleInfo with version initialized to 1 + */ + public BundleInfo(){ + version =1; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java new file mode 100644 index 000000000..1dcf1c6b0 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.impl.Constants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.io.IOUtils; + +/** + * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. + */ +public class ConfigOperation { + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); + + private static URL url; + private static String basicAuth; + + ConfigOperation(){} + + private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input + * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store + * @param module - Module name that contains yang Schema + * @param containerName - yang container name which will be used as base container. + * @param subModules - Sub modules list if any. Order of sub module is top to bottom. + * @throws APPCException + */ + public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { + if (configJson == null) { + throw new APPCException("Provided message was null"); + } + LOG.debug("Config JSON: " + configJson +"\n" + +"module" + module +"\n" + +"containerName" + containerName +"\n" + +"subModules length : " + subModules.length ); + + int httpCode; + String respBody ; + try { + String path = requestFormatter.buildPath(module, containerName, subModules); + LOG.debug("Configuration Path : " + path); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + HttpResponse response = doPut(serviceUrl , configJson); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + LOG.error("Error while storing configuration json "+e.getMessage(), e); + throw new APPCException(e); + } + + if (httpCode < 200 || httpCode >= 300 ) { + try { + LOG.debug("Config operation Error response code: " + httpCode); + ArrayList errorMessage = new ArrayList<>(); + JsonNode responseJson = toJsonNodeFromJsonString(respBody); + if(responseJson!=null && responseJson.get("errors")!=null) { + JsonNode errors = responseJson.get("errors").get("error"); + for (Iterator i = errors.elements();i.hasNext();){ + JsonNode error = i.next(); + errorMessage.add(error.get("error-message").textValue()); + } + } + throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); + } catch (Exception e) { + LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); + throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); + } + }else{ + LOG.debug("Config operation successful. Response code: " + httpCode); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param url - Destination URL for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException + */ + public static HttpResponse doPut (URL url, String body) throws APPCException { + HttpPut put; + try { + put = new HttpPut(url.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(Constants.OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + LOG.error("Malformed URL " +newUrl + e.getMessage(), e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basicAuth = null; + } + return basicAuth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client." , e); + client = new DefaultHttpClient(); + } + } else if ("http".equals(url.getProtocol())) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + private static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge new file mode 100644 index 000000000..36f471853 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperation.java~ccmerge @@ -0,0 +1,295 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.mdsal.impl.Constants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.io.IOUtils; + +/** + * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. +*/ +public class ConfigOperation { + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); + + private static URL url; + private static String basicAuth; + + ConfigOperation(){} + + private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input + * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store + * @param module - Module name that contains yang Schema + * @param containerName - yang container name which will be used as base container. + * @param subModules - Sub modules list if any. Order of sub module is top to bottom. + * @throws APPCException + */ + public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { + if (configJson == null) { + throw new APPCException("Provided message was null"); + } + LOG.debug("Config JSON: " + configJson +"\n" + +"module" + module +"\n" + +"containerName" + containerName +"\n" + +"subModules length : " + subModules.length ); + + int httpCode; + String respBody ; + try { + String path = requestFormatter.buildPath(url, module, containerName, subModules); + LOG.debug("Configuration Path : " + path); + URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + HttpResponse response = doPut(serviceUrl , configJson); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + } catch (IOException e) { + LOG.error("Error while storing configuration json "+e.getMessage(), e); + throw new APPCException(e); + } + + if (httpCode < 200 || httpCode >= 300 ) { + try { + LOG.debug("Config operation Error response code: " + httpCode); + ArrayList errorMessage = new ArrayList<>(); + JsonNode responseJson = toJsonNodeFromJsonString(respBody); + if(responseJson!=null && responseJson.get("errors")!=null) { + JsonNode errors = responseJson.get("errors").get("error"); + for (Iterator i = errors.elements();i.hasNext();){ + JsonNode error = i.next(); + errorMessage.add(error.get("error-message").textValue()); + } + } + throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); + } catch (Exception e) { + LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); + throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); + } + }else{ + LOG.debug("Config operation successful. Response code: " + httpCode); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param url - Destination URL for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException + */ + public static HttpResponse doPut (URL url, String body) throws APPCException { + HttpPut put; + try { + put = new HttpPut(url.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(Constants.OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + + } + + /** + * Updates the static var URL and returns the value; + * + * @return The new value of URL + */ + public static String getUrl() { + return url.toExternalForm(); + } + + public static void setUrl(String newUrl) { + try { + url = new URL(newUrl); + } catch (MalformedURLException e) { + LOG.error("Malformed URL " +newUrl + e.getMessage(), e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basicAuth = null; + } + return basicAuth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient() throws APPCException { + HttpClient client; + if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client." , e); + client = new DefaultHttpClient(); + } + } else if ("http".equals(url.getProtocol())) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + + private static JsonNode toJsonNodeFromJsonString(String jsonStr) { + JsonNode jsonNode = null; + if(jsonStr != null) { + try { + jsonNode = mapper.readTree(jsonStr); + } catch (IOException e) { + LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); + } + } + return jsonNode; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java new file mode 100644 index 000000000..b2ada2ecc --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/onap/appc/mdsal/operation/ConfigOperationRequestFormatter.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.mdsal.operation; + +import org.onap.appc.mdsal.impl.Constants; + +import java.net.URL; +/** + * Creates request url path for config actions based on parameter like module name , container-name and sub modules if any. + */ + +public class ConfigOperationRequestFormatter { + /** + * Build a request url path for config actions + * @param module - yang module name + * @param containerName - yang container name + * @param subModules - sub module /container names as string in varargs ( String ) format + * @return - resultant path in String format + */ + public String buildPath(String module, String containerName , String... subModules ) { + + StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); + if(subModules.length >0){ + for(String subModule : subModules){ + path.append(subModule); + path.append("/"); + } + } + return path.toString(); + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java deleted file mode 100644 index eba364a10..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/MDSALStore.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal; - -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.objects.BundleInfo; - -import java.util.Date; - -/** - * Provides APIs for interacting with MD-SAL store - */ -public interface MDSALStore { - - /** - * Checks the presence of any yang module in the MD-SAL store, - * Due to limitation of SchemaContext interface of ODL that it does not - * contain the information about dynamically loaded yang modules, it - * checks the presence of OSGI bundle - * @param moduleName Name of the Module - * @param revision revision of the Module - * @return returns true- module is present, false - module is absent - */ - boolean isModulePresent(String moduleName, Date revision); - - /** - * This method will be used to store yang module to MD-SAL store - * @param yang - yang module that need to be stored. In String format - * @param bundleInfo - Bundle Information that contains name , description, version , location. These parameters used to create bundle which will push yang to MD-SAL store. - * @throws MDSALStoreException - */ - void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException; - - /** - * This method is used to store configuration JSON to MD-SAL store. It invokes store configuration Operation with required parameters - * @param moduleName - Yang module name where JSON need to be posted - * @param requestId - Request ID which is used as unique key for configuration JSON - * @param configJSON - String value of configuration JSON that needs to be stored in MD-SAl store - * @throws MDSALStoreException - */ - void storeJson(String moduleName , String requestId , String configJSON ) throws MDSALStoreException; - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java deleted file mode 100644 index 2bb30b1c2..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/exception/MDSALStoreException.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.exception; - -/** - * This is custom exception type defined for MD-SAL store. All exceptions thrown by mdsal store module need to be wrapped in this class. -*/ - public class MDSALStoreException extends Exception { - - private static final long serialVersionUID = 1L; - - public MDSALStoreException(){ - } - - /** - * Create MDSALStoreException using only message. - * @param message -- message to the caller. - */ - public MDSALStoreException (String message){ - super(message); - } - - /** - * Create MDSALStoreException using orignal cause - * @param cause - cause that is being wrapped / suppressed. - */ - public MDSALStoreException (Throwable cause){ - super(cause); - } - - /** - * - * @param message - message to the caller. - * @param cause - cause that is being wrapped / suppressed . - */ - public MDSALStoreException(String message , Throwable cause){ - super(message , cause); - } - - /** - * - * @param message - message to the caller. - * @param cause - cause that is being wrapped / suppressed . - * @param enableSuppression - Indicates if suppression is enabled. - * @param writableStackTrace - Indicates if writable stacktrace is supported - */ - public MDSALStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java deleted file mode 100644 index bb847477f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; -/** - * This class contains the definitions of all constant values used in the appc-dg-mdsal-store - * These properties are used for creating osgi bundle zip file. It also defines contents for Blueprint.xml file of bundle - */ -public class Constants { - - private Constants(){} - /** - * Manifest attribute for OSGI Bundle Name - */ - public static final String MANIFEST_ATTR_BUNDLE_NAME= "Bundle-Name"; - - /** - * Manifest attribute for OSGI Bundle Symbolic Name - */ - public static final String MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME= "Bundle-SymbolicName"; - - /** - * Manifest attribute for OSGI Bundle Description - */ - public static final String MANIFEST_ATTR_BUNDLE_DESCRIPTION= "Bundle-Description"; - - /** - * Manifest attribute for OSGI Bundle Manifest version - */ - public static final String MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION= "Bundle-ManifestVersion"; - - /** - * Manifest attribute for OSGI Bundle Version - */ - public static final String MANIFEST_ATTR_BUNDLE_VERSION= "Bundle-Version"; - - /** - * Manifest attribute for OSGI Bundle Blueprint - */ - public static final String MANIFEST_ATTR_BUNDLE_BLUEPRINT= "Bundle-Blueprint"; - - /** - * Manifest value for Mainfest Version - */ - public static final String MANIFEST_VALUE_VERSION= "1.0"; - - /** - * Manifest value for OSGI Bundle Vesion - */ - public static final String MANIFEST_VALUE_BUNDLE_MAN_VERSION= "2"; - - /** - * Manifest value for OSGI Bundle Blueprint location - */ - public static final String MANIFEST_VALUE_BUNDLE_BLUEPRINT= "OSGI-INF/blueprint/blueprint.xml"; - - /** - * Base URL for config actions exposed by RESTCONF API - */ - - public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config"; - - public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url"; - - public static final String CONFIG_PATH = "/restconf/config"; - - /** - * Restconf authentication user property name - */ - public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user"; - - /** - * Restconf authentication password property name - */ - public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass"; - - /** - * Content for blueprint.xml used while creation of OSGI bundle. - */ - public static final String BLUEPRINT = "\n" + - "\n" + - "\n" + - "\n" + - ""; - - /** - * HTTP Header attribute for Content type - JSON - */ - public static final String OPERATION_APPLICATION_JSON= " application/json"; - - /** - * HTTP protocol used for config operations - */ - public static final String OPERATION_HTTPS= "https"; - - /** - * Constant for backslash to be used while formatting URL - */ - public static final String URL_BACKSLASH ="/"; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java deleted file mode 100644 index bc951d926..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; - -import org.onap.appc.mdsal.MDSALStore; - -/* - * Factory class to create/get instance of MDSALStore - */ -public class MDSALStoreFactory { - private static class ReferenceHolder{ - private static MDSALStore store = new MDSALStoreImpl(); - private ReferenceHolder(){} - } - private MDSALStoreFactory(){ - - } - - /** - * Method for creating MDSALStore instance, It creates an instance of - * MDSALStoreImpl once and returns the same instance everytime it is invoked. - * @return - */ - public static MDSALStore createMDSALStore (){ - return ReferenceHolder.store; - } -} - diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java deleted file mode 100644 index c9e083557..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.impl; - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.MDSALStore; -import org.onap.appc.mdsal.exception.MDSALStoreException; -import org.onap.appc.mdsal.objects.BundleInfo; -import org.onap.appc.mdsal.operation.ConfigOperation; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.Date; -import java.util.Properties; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; - -/** - * Implementation of MDSALStore - */ -public class MDSALStoreImpl implements MDSALStore{ - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class); - - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - MDSALStoreImpl(){ - String configUrl = null; - String user =null; - String password = null; - Properties properties = configuration.getProperties(); - if (properties != null) { - configUrl= properties.getProperty( Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT); - user = properties.getProperty(Constants.CONFIG_USER_PROPERTY); - password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY); - } - ConfigOperation.setUrl(configUrl); - ConfigOperation.setAuthentication(user,password); - } - - - @Override - public boolean isModulePresent(String moduleName, Date revision) { - - if(logger.isDebugEnabled()){ - logger.debug("isModulePresent invoked with moduleName = " +moduleName + " , revision = " +revision); - } - - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - /** - * SchemaContext interface of ODL provides APIs for querying details of yang modules - * loaded into MD-SAL store, but its limitation is, it only returns information about - * static yang modules loaded on server start up, it does not return information about - * the yang modules loaded dynamically. Due to this limitation, we are checking the - * presence of OSGI bundle instead of yang module. (Note: Assuming OSGI bundle is named - * with the yang module name). - */ - - Bundle bundle = bundleContext.getBundle(moduleName); - if(logger.isDebugEnabled()){ - logger.debug("isModulePresent returned = " + (bundle != null)); - } - return bundle != null; - } - - @Override - public void storeYangModule(String yang, BundleInfo bundleInfo) throws MDSALStoreException { - - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - byte[] byteArray = createBundleJar(yang, Constants.BLUEPRINT, bundleInfo); - - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray)){ - Bundle bundle = bundleContext.installBundle(bundleInfo.getLocation(), inputStream); - bundle.start(); - } catch (Exception e) { - logger.error("Error storing yang module: " + yang + ". Error message: " + e.getMessage()); - throw new MDSALStoreException("Error storing yang module: " + yang + " " + e.getMessage(), e); - } - } - - @Override - public void storeJson( String module , String requestId ,String configJSON) throws MDSALStoreException { - - try { - ConfigOperation.storeConfig(configJSON , module , org.onap.appc.Constants.YANG_BASE_CONTAINER, org.onap.appc.Constants.YANG_VNF_CONFIG_LIST,requestId,org.onap.appc.Constants.YANG_VNF_CONFIG); - } catch (APPCException e) { - throw new MDSALStoreException("Exception while storing config json to MDSAL store." +e.getMessage(), e); - } - } - - private byte[] createBundleJar(String yang, String blueprint, BundleInfo bundleInfo) throws MDSALStoreException { - - Manifest manifest = new Manifest(); - manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, Constants.MANIFEST_VALUE_VERSION); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME), bundleInfo.getName()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME), bundleInfo.getName()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION), bundleInfo.getDescription()); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION), Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION), String.valueOf(bundleInfo.getVersion())); - manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT), Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT); - - byte[] retunValue; - - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) { - jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/")); - jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/"+bundleInfo.getName()+".yang")); - jarOutputStream.write(yang.getBytes()); - jarOutputStream.closeEntry(); - - jarOutputStream.putNextEntry(new JarEntry("OSGI-INF/blueprint/")); - jarOutputStream.putNextEntry(new JarEntry(Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT)); - jarOutputStream.write(blueprint.getBytes()); - jarOutputStream.closeEntry(); - jarOutputStream.close(); - retunValue = outputStream.toByteArray(); - } catch (Exception e) { - logger.error("Error creating bundle jar: " + bundleInfo.getName() + ". Error message: " + e.getMessage()); - throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(), e); - } - return retunValue; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java deleted file mode 100644 index b6d65447d..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/objects/BundleInfo.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.objects; -/** - * Holds bundle information which includes name , description , version and location. This information will be used to create osgi bundle. - */ - public class BundleInfo { - - private String name; - private String description; - private Integer version; - private String location; - - /** - * Creates an object of BundleInfo with version initialized to 1 - */ - public BundleInfo(){ - version =1; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Integer getVersion() { - return version; - } - - public void setVersion(Integer version) { - this.version = version; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java deleted file mode 100644 index 1dcf1c6b0..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java +++ /dev/null @@ -1,295 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.impl.Constants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.security.*; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.commons.io.IOUtils; - -/** - * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. - */ -public class ConfigOperation { - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); - - private static URL url; - private static String basicAuth; - - ConfigOperation(){} - - private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input - * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store - * @param module - Module name that contains yang Schema - * @param containerName - yang container name which will be used as base container. - * @param subModules - Sub modules list if any. Order of sub module is top to bottom. - * @throws APPCException - */ - public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { - if (configJson == null) { - throw new APPCException("Provided message was null"); - } - LOG.debug("Config JSON: " + configJson +"\n" - +"module" + module +"\n" - +"containerName" + containerName +"\n" - +"subModules length : " + subModules.length ); - - int httpCode; - String respBody ; - try { - String path = requestFormatter.buildPath(module, containerName, subModules); - LOG.debug("Configuration Path : " + path); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - HttpResponse response = doPut(serviceUrl , configJson); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - LOG.error("Error while storing configuration json "+e.getMessage(), e); - throw new APPCException(e); - } - - if (httpCode < 200 || httpCode >= 300 ) { - try { - LOG.debug("Config operation Error response code: " + httpCode); - ArrayList errorMessage = new ArrayList<>(); - JsonNode responseJson = toJsonNodeFromJsonString(respBody); - if(responseJson!=null && responseJson.get("errors")!=null) { - JsonNode errors = responseJson.get("errors").get("error"); - for (Iterator i = errors.elements();i.hasNext();){ - JsonNode error = i.next(); - errorMessage.add(error.get("error-message").textValue()); - } - } - throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); - } catch (Exception e) { - LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); - throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); - } - }else{ - LOG.debug("Config operation successful. Response code: " + httpCode); - } - } - - /** - * This is Generic method that can be used to perform REST Put operation - * @param url - Destination URL for put - * @param body - payload for put action which will be sent as request body. - * @return - HttpResponse object which is returned from put REST call. - * @throws APPCException - */ - public static HttpResponse doPut (URL url, String body) throws APPCException { - HttpPut put; - try { - put = new HttpPut(url.toExternalForm()); - put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); - put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); - - if (basicAuth != null) { - put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); - } - - StringEntity entity = new StringEntity(body); - entity.setContentType(Constants.OPERATION_APPLICATION_JSON); - put.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - try { - return client.execute(put); - } catch (IOException e) { - throw new APPCException(e); - } - - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public static String getUrl() { - return url.toExternalForm(); - } - - public static void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - LOG.error("Malformed URL " +newUrl + e.getMessage(), e); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user The user with optional domain name (for AAF) - * @param password The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basicAuth = null; - } - return basicAuth; - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - LOG.error("Error creating HTTP Client. Creating default client." , e); - client = new DefaultHttpClient(); - } - } else if ("http".equals(url.getProtocol())) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - private static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkClientTrusted"); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkServerTrusted"); - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[1]; - } - }; - - sslContext.init(null, new TrustManager[]{ - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - private static JsonNode toJsonNodeFromJsonString(String jsonStr) { - JsonNode jsonNode = null; - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); - } - } - return jsonNode; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge deleted file mode 100644 index 36f471853..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge +++ /dev/null @@ -1,295 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.mdsal.impl.Constants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.security.*; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.commons.io.IOUtils; - -/** - * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation. -*/ -public class ConfigOperation { - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class); - - private static URL url; - private static String basicAuth; - - ConfigOperation(){} - - private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter(); - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input - * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store - * @param module - Module name that contains yang Schema - * @param containerName - yang container name which will be used as base container. - * @param subModules - Sub modules list if any. Order of sub module is top to bottom. - * @throws APPCException - */ - public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException { - if (configJson == null) { - throw new APPCException("Provided message was null"); - } - LOG.debug("Config JSON: " + configJson +"\n" - +"module" + module +"\n" - +"containerName" + containerName +"\n" - +"subModules length : " + subModules.length ); - - int httpCode; - String respBody ; - try { - String path = requestFormatter.buildPath(url, module, containerName, subModules); - LOG.debug("Configuration Path : " + path); - URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - HttpResponse response = doPut(serviceUrl , configJson); - httpCode = response.getStatusLine().getStatusCode(); - respBody = IOUtils.toString(response.getEntity().getContent()); - } catch (IOException e) { - LOG.error("Error while storing configuration json "+e.getMessage(), e); - throw new APPCException(e); - } - - if (httpCode < 200 || httpCode >= 300 ) { - try { - LOG.debug("Config operation Error response code: " + httpCode); - ArrayList errorMessage = new ArrayList<>(); - JsonNode responseJson = toJsonNodeFromJsonString(respBody); - if(responseJson!=null && responseJson.get("errors")!=null) { - JsonNode errors = responseJson.get("errors").get("error"); - for (Iterator i = errors.elements();i.hasNext();){ - JsonNode error = i.next(); - errorMessage.add(error.get("error-message").textValue()); - } - } - throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString()); - } catch (Exception e) { - LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e); - throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e); - } - }else{ - LOG.debug("Config operation successful. Response code: " + httpCode); - } - } - - /** - * This is Generic method that can be used to perform REST Put operation - * @param url - Destination URL for put - * @param body - payload for put action which will be sent as request body. - * @return - HttpResponse object which is returned from put REST call. - * @throws APPCException - */ - public static HttpResponse doPut (URL url, String body) throws APPCException { - HttpPut put; - try { - put = new HttpPut(url.toExternalForm()); - put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON); - put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON); - - if (basicAuth != null) { - put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); - } - - StringEntity entity = new StringEntity(body); - entity.setContentType(Constants.OPERATION_APPLICATION_JSON); - put.setEntity(new StringEntity(body)); - } catch (UnsupportedEncodingException e) { - throw new APPCException(e); - } - - HttpClient client = getHttpClient(); - - try { - return client.execute(put); - } catch (IOException e) { - throw new APPCException(e); - } - - } - - /** - * Updates the static var URL and returns the value; - * - * @return The new value of URL - */ - public static String getUrl() { - return url.toExternalForm(); - } - - public static void setUrl(String newUrl) { - try { - url = new URL(newUrl); - } catch (MalformedURLException e) { - LOG.error("Malformed URL " +newUrl + e.getMessage(), e); - } - } - - /** - * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth - * to null - * - * @param user The user with optional domain name (for AAF) - * @param password The password for the user - * @return The new value of the basic auth string that will be used in the request headers - */ - public static String setAuthentication(String user, String password) { - if (user != null && password != null) { - String authStr = user + ":" + password; - basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); - } else { - basicAuth = null; - } - return basicAuth; - } - - @SuppressWarnings("deprecation") - private static HttpClient getHttpClient() throws APPCException { - HttpClient client; - if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443)); - registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443)); - registry.register(new Scheme("http", sf, 8181)); - - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - client = new DefaultHttpClient(ccm, params); - } catch (Exception e) { - LOG.error("Error creating HTTP Client. Creating default client." , e); - client = new DefaultHttpClient(); - } - } else if ("http".equals(url.getProtocol())) { - client = new DefaultHttpClient(); - } else { - throw new APPCException( - "The provider.topology.url property is invalid. The url did not start with http[s]"); - } - return client; - } - - @SuppressWarnings("deprecation") - private static class MySSLSocketFactory extends SSLSocketFactory { - private SSLContext sslContext = SSLContext.getInstance("TLS"); - - private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, - KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkClientTrusted"); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - LOG.debug("Inside checkServerTrusted"); - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[1]; - } - }; - - sslContext.init(null, new TrustManager[]{ - tm - }, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - - private static JsonNode toJsonNodeFromJsonString(String jsonStr) { - JsonNode jsonNode = null; - if(jsonStr != null) { - try { - jsonNode = mapper.readTree(jsonStr); - } catch (IOException e) { - LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e); - } - } - return jsonNode; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java deleted file mode 100644 index b2ada2ecc..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.mdsal.operation; - -import org.onap.appc.mdsal.impl.Constants; - -import java.net.URL; -/** - * Creates request url path for config actions based on parameter like module name , container-name and sub modules if any. - */ - -public class ConfigOperationRequestFormatter { - /** - * Build a request url path for config actions - * @param module - yang module name - * @param containerName - yang container name - * @param subModules - sub module /container names as string in varargs ( String ) format - * @return - resultant path in String format - */ - public String buildPath(String module, String containerName , String... subModules ) { - - StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH); - if(subModules.length >0){ - for(String subModule : subModules){ - path.append(subModule); - path.append("/"); - } - } - return path.toString(); - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java new file mode 100644 index 000000000..e1c563a4b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfClientPlugin.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface NetconfClientPlugin extends SvcLogicJavaPlugin { + void configure(Map params, SvcLogicContext ctx) throws APPCException; + void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException; + void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void getConfig(Map params, SvcLogicContext ctx) throws APPCException; + void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java new file mode 100644 index 000000000..a4086a521 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/NetconfDBPlugin.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public interface NetconfDBPlugin extends SvcLogicJavaPlugin { + void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException; + void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java new file mode 100644 index 000000000..174226473 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImpl.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.netconf.*; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.NetconfClientPlugin; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; + + + +public class NetconfClientPluginImpl implements NetconfClientPlugin { + + private static final String NETCONF_CLIENT_FACTORY_NAME = "org.onap.appc.adapter.netconf.NetconfClientFactory"; + private static ObjectMapper mapper = new ObjectMapper(); + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + private NetconfDataAccessService dao; + private NetconfClientFactory clientFactory; + + public NetconfClientPluginImpl() { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference srefNetconfClientFactory = bctx.getServiceReference(NetconfClientFactory.class); + clientFactory = (NetconfClientFactory) bctx.getService(srefNetconfClientFactory); + } + + public void setDao(NetconfDataAccessService dao) { + this.dao = dao; + this.dao.setSchema(Constants.NETCONF_SCHEMA); + } + + public void configure(Map params, SvcLogicContext ctx) throws APPCException { + + try { + // by default, it uses the jsch Netconf Adapter implementation by calling GetNetconfClient(NetconfClientType.SSH). + NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + try { + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + String netconfMessage = params.get("file-content"); + client.connect(connectionDetails); + client.configure(netconfMessage); + } catch (IOException e) { + logger.error("Error " + e.getMessage()); + throw new APPCException(e); + } finally { + client.disconnect(); + } + } catch (Exception e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + logger.error("Error " + e.getMessage()); + throw e; + } + } + + @Override + public void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to operationStateValidation with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); + } + try{ + String paramName = Constants.VNF_TYPE_FIELD_NAME; + String vfType = params.get(paramName); + validateMandatoryParam(paramName, vfType); + VnfType vnfType = VnfType.getVnfType(vfType); + + paramName = Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME; + String vnfHostIpAddress = params.get(paramName); + validateMandatoryParam(paramName, vnfHostIpAddress); + + //get connectionDetails + String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME); + NetconfConnectionDetails connectionDetails = null; + if(StringUtils.isEmpty(connectionDetailsStr)){ + connectionDetails = retrieveConnectionDetails(vnfType); + connectionDetails.setHost(vnfHostIpAddress); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + }else{ + connectionDetails = mapper.readValue(connectionDetailsStr, NetconfConnectionDetails.class); + } + if(connectionDetails == null){ + throw new IllegalStateException("missing connectionDetails for VnfType:"+vnfType.name()); + } + + //get operationsStateNetconfMessage + OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType); + String configurationFileName = operationalStateValidator.getConfigurationFileName(); + String operationsStateNetconfMessage = null; + if(!StringUtils.isEmpty(configurationFileName)){ + operationsStateNetconfMessage = retrieveConfigurationFileContent(configurationFileName); + } + + //connect checK Opertaions state and dissconnect + NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + try { + client.connect(connectionDetails); + String response = null; + if(!StringUtils.isEmpty(operationsStateNetconfMessage)) { + response = client.exchangeMessage(operationsStateNetconfMessage); + } + operationalStateValidator.validateResponse(response); + } finally { + client.disconnect(); + } + } catch (APPCException e) { + logger.error(e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw e; + } + catch (Exception e) { + logger.error(e.toString()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); + throw new APPCException(e); + } + } + + @Override + public void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + this.configure(params, ctx); + } + + @Override + public void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + + NetconfClient client = null; + try { + if (logger.isDebugEnabled()) { + logger.debug("Entered backup to DEVICE_INTERFACE_LOG"); + } + + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + + //store configuration in database + dao.logDeviceInteraction(null,null,getCurrentDateTime(),configuration); + + } catch (Exception e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + } + + @Override + public void getConfig(Map params, SvcLogicContext ctx) throws APPCException { + NetconfClient client = null; + String confId=params.get("conf-id"); + if(confId.equalsIgnoreCase("current")){ + try { + if (logger.isDebugEnabled()) { + logger.debug("Entered getConfig to DEVICE_INTERFACE_LOG"); + } + //get netconf client to get configuration + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); + NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + if(configuration !=null){ + String fullConfig = ctx.getAttribute("fullConfig"); + fullConfig = fullConfig==null?"":fullConfig; + ctx.setAttribute("fullConfig",fullConfig + configuration); + + ctx.setAttribute("getConfig_Result","Success"); + String entityName=ctx.getAttribute("entity");//VM name + if(entityName!=null){ + ctx.setAttribute(entityName+".Configuration",configuration); + } + }else{ + ctx.setAttribute("getConfig_Result","failure"); + } + } catch (Exception e) { + ctx.setAttribute("getConfig_Result","failure"); + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + }else{ + logger.info("Current Conf id value is not supported"); + } + + } + + + @Override + public void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException { + NetconfClient client = null; + try { + logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG"); + //get netconf client to get configuration + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); + NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); + client = clientFactory.GetNetconfClient(NetconfClientType.SSH); + //get connection details + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(params.get("host-ip-address")); + connectionDetails.setUsername(params.get("user-name")); + connectionDetails.setPassword(params.get("password")); + connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT); + //connect the client and get configuration + client.connect(connectionDetails); + String configuration = client.getConfiguration(); + if(configuration !=null){ + // logger.info("*************************************Configuration Output*************************************"); + ctx.setAttribute("running-config", configuration); + + ctx.setAttribute("getRunningConfig_Result","Success"); + }else{ + ctx.setAttribute("getRunningConfig_Result","failure"); + } + } catch (Exception e) { + ctx.setAttribute("getRunningConfig_Result","failure"); + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } finally { + //disconnect the client + if(client != null) { + client.disconnect(); + } + } + } + + private String getCurrentDateTime() { + + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private int getPort(String s) { + int port = 830; + if((s != null) && !s.isEmpty()) { + port = Integer.parseInt(s); + } + return port; + } + + void validateMandatoryParam(String paramName, String paramValue) { + if(StringUtils.isEmpty(paramValue)){ + throw new IllegalArgumentException("input "+paramName+" param is empty"); + } + } + + public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{ + + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) { + logger.error("Missing configuration for " + vnfType.getFamilyType().name()); + throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + return connectionDetails; + } + + public String retrieveConfigurationFileContent(String configFileName){ + return dao.retrieveConfigFileName(configFileName); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java new file mode 100644 index 000000000..459ece9c1 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImpl.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.Map; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.NetconfDBPlugin; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class NetconfDBPluginImpl implements NetconfDBPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static ObjectMapper mapper = new ObjectMapper(); + + // populated by blueprint framework + private NetconfDataAccessService daoService; + + public void setDaoService(NetconfDataAccessService daoService) { + this.daoService = daoService; + this.daoService.setSchema(Constants.NETCONF_SCHEMA); + } + + public NetconfDBPluginImpl() { + } + + public void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + + try { + String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); + ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + } catch(DataAccessException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } + + getConnection(params, ctx); + } + + @Override + public void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { + logger.info("Setting entity value :" +params.get(Constants.RESOURCEKEY)); + ctx.setAttribute("entity", params.get(Constants.RESOURCEKEY)); + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + try { + if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.RESOURCEKEY), connectionDetails)) { + ctx.setAttribute("retrieveVMDSConfiguration_Result","failure"); + logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); + throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + ctx.setAttribute("retrieveVMDSConfiguration_Result","success"); + } catch(APPCException e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } catch(DataAccessException | JsonProcessingException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } + } + + @Override + public void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException { + String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); + ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + } + + public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { + getConnection(params, ctx); + } + + private void getConnection(Map params, SvcLogicContext ctx) throws APPCException { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + try { + if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.VNF_TYPE_FIELD_NAME), connectionDetails)) { + logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); + throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + } catch(APPCException e) { + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw e; + } catch(DataAccessException | JsonProcessingException e) { + logger.error("Error " + e.getMessage()); + ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); + throw new APPCException(e); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java deleted file mode 100644 index e1c563a4b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfClientPlugin.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface NetconfClientPlugin extends SvcLogicJavaPlugin { - void configure(Map params, SvcLogicContext ctx) throws APPCException; - void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException; - void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void getConfig(Map params, SvcLogicContext ctx) throws APPCException; - void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java deleted file mode 100644 index a4086a521..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/NetconfDBPlugin.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - - -public interface NetconfDBPlugin extends SvcLogicJavaPlugin { - void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException; - void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java deleted file mode 100644 index 174226473..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImpl.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.netconf.*; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.NetconfClientPlugin; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; - - - -public class NetconfClientPluginImpl implements NetconfClientPlugin { - - private static final String NETCONF_CLIENT_FACTORY_NAME = "org.onap.appc.adapter.netconf.NetconfClientFactory"; - private static ObjectMapper mapper = new ObjectMapper(); - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - private NetconfDataAccessService dao; - private NetconfClientFactory clientFactory; - - public NetconfClientPluginImpl() { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference srefNetconfClientFactory = bctx.getServiceReference(NetconfClientFactory.class); - clientFactory = (NetconfClientFactory) bctx.getService(srefNetconfClientFactory); - } - - public void setDao(NetconfDataAccessService dao) { - this.dao = dao; - this.dao.setSchema(Constants.NETCONF_SCHEMA); - } - - public void configure(Map params, SvcLogicContext ctx) throws APPCException { - - try { - // by default, it uses the jsch Netconf Adapter implementation by calling GetNetconfClient(NetconfClientType.SSH). - NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - try { - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - String netconfMessage = params.get("file-content"); - client.connect(connectionDetails); - client.configure(netconfMessage); - } catch (IOException e) { - logger.error("Error " + e.getMessage()); - throw new APPCException(e); - } finally { - client.disconnect(); - } - } catch (Exception e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - logger.error("Error " + e.getMessage()); - throw e; - } - } - - @Override - public void operationStateValidation(Map params, SvcLogicContext ctx) throws APPCException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to operationStateValidation with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx)); - } - try{ - String paramName = Constants.VNF_TYPE_FIELD_NAME; - String vfType = params.get(paramName); - validateMandatoryParam(paramName, vfType); - VnfType vnfType = VnfType.getVnfType(vfType); - - paramName = Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME; - String vnfHostIpAddress = params.get(paramName); - validateMandatoryParam(paramName, vnfHostIpAddress); - - //get connectionDetails - String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME); - NetconfConnectionDetails connectionDetails = null; - if(StringUtils.isEmpty(connectionDetailsStr)){ - connectionDetails = retrieveConnectionDetails(vnfType); - connectionDetails.setHost(vnfHostIpAddress); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - }else{ - connectionDetails = mapper.readValue(connectionDetailsStr, NetconfConnectionDetails.class); - } - if(connectionDetails == null){ - throw new IllegalStateException("missing connectionDetails for VnfType:"+vnfType.name()); - } - - //get operationsStateNetconfMessage - OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory.getOperationalStateValidator(vnfType); - String configurationFileName = operationalStateValidator.getConfigurationFileName(); - String operationsStateNetconfMessage = null; - if(!StringUtils.isEmpty(configurationFileName)){ - operationsStateNetconfMessage = retrieveConfigurationFileContent(configurationFileName); - } - - //connect checK Opertaions state and dissconnect - NetconfClient client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - try { - client.connect(connectionDetails); - String response = null; - if(!StringUtils.isEmpty(operationsStateNetconfMessage)) { - response = client.exchangeMessage(operationsStateNetconfMessage); - } - operationalStateValidator.validateResponse(response); - } finally { - client.disconnect(); - } - } catch (APPCException e) { - logger.error(e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw e; - } - catch (Exception e) { - logger.error(e.toString()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString()); - throw new APPCException(e); - } - } - - @Override - public void modifyConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - this.configure(params, ctx); - } - - @Override - public void backupConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - - NetconfClient client = null; - try { - if (logger.isDebugEnabled()) { - logger.debug("Entered backup to DEVICE_INTERFACE_LOG"); - } - - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - - //store configuration in database - dao.logDeviceInteraction(null,null,getCurrentDateTime(),configuration); - - } catch (Exception e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - } - - @Override - public void getConfig(Map params, SvcLogicContext ctx) throws APPCException { - NetconfClient client = null; - String confId=params.get("conf-id"); - if(confId.equalsIgnoreCase("current")){ - try { - if (logger.isDebugEnabled()) { - logger.debug("Entered getConfig to DEVICE_INTERFACE_LOG"); - } - //get netconf client to get configuration - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); - NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = mapper.readValue(params.get("connection-details"), NetconfConnectionDetails.class); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - if(configuration !=null){ - String fullConfig = ctx.getAttribute("fullConfig"); - fullConfig = fullConfig==null?"":fullConfig; - ctx.setAttribute("fullConfig",fullConfig + configuration); - - ctx.setAttribute("getConfig_Result","Success"); - String entityName=ctx.getAttribute("entity");//VM name - if(entityName!=null){ - ctx.setAttribute(entityName+".Configuration",configuration); - } - }else{ - ctx.setAttribute("getConfig_Result","failure"); - } - } catch (Exception e) { - ctx.setAttribute("getConfig_Result","failure"); - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - }else{ - logger.info("Current Conf id value is not supported"); - } - - } - - - @Override - public void getRunningConfig(Map params, SvcLogicContext ctx) throws APPCException { - NetconfClient client = null; - try { - logger.info("Entered getRunningConfig to DEVICE_INTERFACE_LOG"); - //get netconf client to get configuration - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(NETCONF_CLIENT_FACTORY_NAME); - NetconfClientFactory clientFactory = (NetconfClientFactory) bctx.getService(sref); - client = clientFactory.GetNetconfClient(NetconfClientType.SSH); - //get connection details - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(params.get("host-ip-address")); - connectionDetails.setUsername(params.get("user-name")); - connectionDetails.setPassword(params.get("password")); - connectionDetails.setPort(!("".equalsIgnoreCase(params.get("port-number")))?Integer.parseInt(params.get("port-number")):NetconfConnectionDetails.DEFAULT_PORT); - //connect the client and get configuration - client.connect(connectionDetails); - String configuration = client.getConfiguration(); - if(configuration !=null){ - // logger.info("*************************************Configuration Output*************************************"); - ctx.setAttribute("running-config", configuration); - - ctx.setAttribute("getRunningConfig_Result","Success"); - }else{ - ctx.setAttribute("getRunningConfig_Result","failure"); - } - } catch (Exception e) { - ctx.setAttribute("getRunningConfig_Result","failure"); - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } finally { - //disconnect the client - if(client != null) { - client.disconnect(); - } - } - } - - private String getCurrentDateTime() { - - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); - return dateFormat.format(date); - } - - private int getPort(String s) { - int port = 830; - if((s != null) && !s.isEmpty()) { - port = Integer.parseInt(s); - } - return port; - } - - void validateMandatoryParam(String paramName, String paramValue) { - if(StringUtils.isEmpty(paramValue)){ - throw new IllegalArgumentException("input "+paramName+" param is empty"); - } - } - - public NetconfConnectionDetails retrieveConnectionDetails( VnfType vnfType) throws APPCException{ - - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) { - logger.error("Missing configuration for " + vnfType.getFamilyType().name()); - throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - return connectionDetails; - } - - public String retrieveConfigurationFileContent(String configFileName){ - return dao.retrieveConfigFileName(configFileName); - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java deleted file mode 100644 index 459ece9c1..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/main/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImpl.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.Map; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.NetconfDBPlugin; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class NetconfDBPluginImpl implements NetconfDBPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static ObjectMapper mapper = new ObjectMapper(); - - // populated by blueprint framework - private NetconfDataAccessService daoService; - - public void setDaoService(NetconfDataAccessService daoService) { - this.daoService = daoService; - this.daoService.setSchema(Constants.NETCONF_SCHEMA); - } - - public NetconfDBPluginImpl() { - } - - public void retrieveDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - - try { - String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); - ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - } catch(DataAccessException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } - - getConnection(params, ctx); - } - - @Override - public void retrieveVMDSConfiguration(Map params, SvcLogicContext ctx) throws APPCException { - logger.info("Setting entity value :" +params.get(Constants.RESOURCEKEY)); - ctx.setAttribute("entity", params.get(Constants.RESOURCEKEY)); - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - try { - if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.RESOURCEKEY), connectionDetails)) { - ctx.setAttribute("retrieveVMDSConfiguration_Result","failure"); - logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); - throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - ctx.setAttribute("retrieveVMDSConfiguration_Result","success"); - } catch(APPCException e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } catch(DataAccessException | JsonProcessingException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } - } - - @Override - public void retrieveConfigFile(Map params, SvcLogicContext ctx) throws APPCException { - String fileContent = daoService.retrieveConfigFileName(params.get(Constants.CONFIGURATION_FILE_FIELD_NAME)); - ctx.setAttribute(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - } - - public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { - getConnection(params, ctx); - } - - private void getConnection(Map params, SvcLogicContext ctx) throws APPCException { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - try { - if (!daoService.retrieveNetconfConnectionDetails(params.get(Constants.VNF_TYPE_FIELD_NAME), connectionDetails)) { - logger.error("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME)); - throw new APPCException("Missing configuration for " + params.get(Constants.VNF_TYPE_FIELD_NAME) + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - } catch(APPCException e) { - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw e; - } catch(DataAccessException | JsonProcessingException e) { - logger.error("Error " + e.getMessage()); - ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.getMessage()); - throw new APPCException(e); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java new file mode 100644 index 000000000..379e164b5 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/DAOServiceMock.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import java.util.HashMap; + +import org.onap.appc.adapter.netconf.ConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +class DAOServiceMock implements NetconfDataAccessService { + + private String configFile; + private ConnectionDetails connection; + private HashMap backupConf; + + @Override + public void setSchema(String schema) { + } + + @Override + public void setDbLibService(DbLibService dbLibService) { + } + + void setConfigFile(String configFile) { + this.configFile = configFile; + } + + public HashMap getBackupConf() { + return backupConf; + } + + public void setConnection(ConnectionDetails connection) { + this.connection = connection; + } + + @Override + public String retrieveConfigFileName(String xmlID) throws DataAccessException { + if (!xmlID.equals("wrong")) { + return configFile; + } else { + throw new DataAccessException(); + } + } + + @Override + public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws + DataAccessException { + return false; + } + + @Override + public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws + DataAccessException { + if (vnfType.equals("VNF")) { + connectionDetails.setHost(connection.getHost()); + connectionDetails.setPassword(connection.getPassword()); + connectionDetails.setPort(connection.getPort()); + connectionDetails.setUsername(connection.getUsername()); + + return true; + } else { + return false; + } + } + + @Override + public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws + DataAccessException { + this.backupConf = new HashMap<>(); + backupConf.put("creationDate", creationDate); + backupConf.put("logText", logText); + return true; + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java new file mode 100644 index 000000000..802fe15e0 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.OperationalStateValidator; +import org.onap.appc.adapter.netconf.VnfType; +import org.onap.appc.exceptions.APPCException; + + +public class MockOperationalStateValidatorImpl implements OperationalStateValidator { + + private boolean validated; + private String configurationFileName; + + public boolean isValidated() { + return validated; + } + + @Override + public VnfType getVnfType() { + return null; + } + + @Override + public String getConfigurationFileName() { + return configurationFileName; + } + + @Override + public void validateResponse(String response) throws APPCException { + if (response.equals("wrong")) { + throw new APPCException(); + } else { + this.validated = true; + } + + } + + public void setConfigurationFileName(String configurationFileName) { + this.configurationFileName = configurationFileName; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java new file mode 100644 index 000000000..f61d188d9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientFactoryMock.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfClientFactory; +import org.onap.appc.adapter.netconf.NetconfClientType; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; + + +public class NetconfClientFactoryMock extends NetconfClientFactory { + + private final NetconfClientJschMock jschClient = new NetconfClientJschMock(); + + @Override + public NetconfClient GetNetconfClient(NetconfClientType type){ + + return jschClient; + + } +} + + diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java new file mode 100644 index 000000000..82361a95e --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientJschMock.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.exceptions.APPCException; + + +public class NetconfClientJschMock implements NetconfClient { + + private boolean connection; + private String lastMessage; + private String answer = "answer"; + private String configuration; + private NetconfConnectionDetails lastConnectionDetails; + + public boolean isConnection() { + return connection; + } + + public String getLastMessage() { + return lastMessage; + } + + public String getAnswer() { + return answer; + } + + public String getConf() { + return configuration; + } + + public void setConf(String configuration) { + this.configuration = configuration; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public NetconfConnectionDetails getLastConnectionDetails() { + return lastConnectionDetails; + } + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { + this.connection = true; + this.lastConnectionDetails = connectionDetails; + + } + + @Override + public String exchangeMessage(String message) throws APPCException { + if (connection) { + this.lastMessage = message; + return answer; + } else return null; + } + + @Override + public void configure(String configuration) throws APPCException { + if (connection) { + this.configuration = configuration; + } + + } + + @Override + public String getConfiguration() throws APPCException { + if (connection) { + return configuration; + } else return null; + } + + @Override + public void disconnect() throws APPCException { + this.connection = false; + + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java new file mode 100644 index 000000000..0becff701 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfClientPluginImplTest.java @@ -0,0 +1,681 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.onap.appc.exceptions.APPCException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.netconf.*; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.dg.netconf.impl.NetconfClientPluginImpl; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.lang.reflect.Field; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.powermock.api.mockito.PowerMockito.when; + + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class}) + +public class NetconfClientPluginImplTest { + private NetconfClientPluginImpl netconfClientPlugin; + private NetconfDataAccessService dao; + private NetconfClientFactory clientFactory; + private Map params; + + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref1 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref2 = Mockito.mock(ServiceReference.class); + private final ServiceReference sref3 = Mockito.mock(ServiceReference.class); + private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + + String host = "http://www.test.com"; + String host1 = "http://www.test1.com"; + String vnfType = "VNF"; + int port = 8080; + String username = "test"; + String password = "test"; + String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}"; + String fileContent = "\n" + + "\n" + + "\t\n" + + "\t\t\n" + + "\t\t\t\n" + + "\t\t \n" + + "\t\n" + + "'"; + String operationalState = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + + @Before + public void setUp() throws NoSuchFieldException, IllegalAccessException { + clientFactory = new NetconfClientFactoryMock(); + + } + + + @Test + public void testConfigure() throws Exception { + + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + + netconfClientPlugin.configure(params, ctx); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + try { + Assert.assertEquals("wrong configuration", fileContent, client.getConf()); + Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost()); + Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort()); + Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername()); + Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword()); + Assert.assertFalse(client.isConnection()); + } catch (Exception e) { + Assert.fail("failed with because of " + e.getCause()); + } + + + } + + + @Test + public void testConfigureNegativeIOException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + + + try { + netconfClientPlugin.configure(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(client.getLastConnectionDetails()); + Assert.assertNull(client.getConf()); + } + + } + + @Test + public void testOperationStateValidation() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + substituteMapper(true); + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + substituteMapper(false); + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse(validatorMock.isValidated()); + Assert.assertNull(client.getLastMessage()); + } + } + + @Test + public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class); + final NetconfConnectionDetails netconfConnectionDetails = null; + when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidationNegativeAppcException() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer("wrong"); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + + try { + netconfClientPlugin.operationStateValidation(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + Assert.assertFalse("validation process failed", validatorMock.isValidated()); + + } + } + + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, ""); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + @Test + public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setAnswer(operationalState); + ((DAOServiceMock) dao).setConnection(getConnectionDetails()); + + + params = new HashMap<>(); + params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); + params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); + MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); + validatorMock.setConfigurationFileName("VnfGetRunningConfig"); + + PowerMockito.mockStatic(OperationalStateValidatorFactory.class); + when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); + + netconfClientPlugin.operationStateValidation(params, ctx); + + Assert.assertTrue("validation process failed", validatorMock.isValidated()); + Assert.assertEquals(fileContent, client.getLastMessage()); + } + + + @Test + public void testBackupConfiguration() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + netconfClientPlugin.backupConfiguration(params, ctx); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); + Date date = new Date(); + String creationDateExpected = dateFormat.format(date); + String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10); + + + Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText")); + Assert.assertEquals(creationDateExpected, creationDateActual); + + + } + + + @Test + public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception { + shortInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + try { + netconfClientPlugin.backupConfiguration(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + + DAOServiceMock mockdao = (DAOServiceMock) dao; + Assert.assertNull(mockdao.getBackupConf()); + } + + } + + @Test + public void testGetConfig() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig")); + Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeConfigurationNull() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + + @Test + public void testGetConfigNegativeNotSupportedConfId() throws Exception { + fullInit(); + String entity = "123"; + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current1"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); + + + netconfClientPlugin.getConfig(params, ctx); + + Assert.assertNull(ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + } + + @Test + public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception { + fullInit(); + String entity = "123"; + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("entity", entity); + + params = new HashMap<>(); + params.put("conf-id", "current"); + params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); + + + try { + netconfClientPlugin.getConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); + Assert.assertNull(ctx.getAttribute("fullConfig")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfig() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertEquals(fileContent, ctx.getAttribute("running-config")); + Assert.assertEquals("success", ctx.getStatus()); + } + + @Test + public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + + NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); + client.setConf(fileContent); + + try { + netconfClientPlugin.getRunningConfig(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + + } + + @Test + public void testGetRunningConfigNegativeConfigurationNull() throws Exception { + fullInit(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("host-ip-address", host); + params.put("user-name", username); + params.put("password", password); + params.put("port-number", String.valueOf(port)); + + netconfClientPlugin.getRunningConfig(params, ctx); + + Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); + Assert.assertNull(ctx.getAttribute("running-config")); + } + + @Test + public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception { + shortInit(); + String paramName = "test"; + String paramValue = ""; + + try { + netconfClientPlugin.validateMandatoryParam(paramName, paramValue); + Assert.assertTrue(false); + } catch (Exception e) { + Assert.assertTrue(true); + } + } + + @Test + public void testRetrieveConnectionDetails() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF); + + + Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost()); + Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword()); + Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort()); + Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername()); + } + + + @Test + public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { + shortInit(); + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + ConnectionDetails connectionDetails1 = getConnectionDetails(); + daoServiceMock.setConnection(connectionDetails1); + + NetconfConnectionDetails connectionDetailsActual = null; + try { + connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(connectionDetailsActual); + } + + + } + + @Test + public void testRetrieveConfigurationFileContent() throws Exception { + shortInit(); + + DAOServiceMock daoServiceMock = (DAOServiceMock) dao; + daoServiceMock.setConfigFile(fileContent); + + Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig")); + } + + private ConnectionDetails getConnectionDetails() { + + ConnectionDetails connectionDetails = new ConnectionDetails(); + connectionDetails.setPassword(password); + connectionDetails.setPort(port); + connectionDetails.setUsername(username); + connectionDetails.setHost(host); + return connectionDetails; + } + + + private void initDao() throws NoSuchFieldException, IllegalAccessException { + dao = new DAOServiceMock(); + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1); + when(bundleContext.getService(sref1)).thenReturn(dao); + + + } + + private void fullInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initClientFactory2(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void shortInit() throws NoSuchFieldException, IllegalAccessException { + initClientFactory(); + initDao(); + netconfClientPlugin = new NetconfClientPluginImpl(); + netconfClientPlugin.setDao(this.dao); + } + + private void initClientFactory() throws NoSuchFieldException, IllegalAccessException { + + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2); + when(bundleContext.getService(sref2)).thenReturn(clientFactory); + + } + + private void initClientFactory2() { + PowerMockito.mockStatic(FrameworkUtil.class); + when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); + when(bundleService.getBundleContext()).thenReturn(bundleContext); + when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3); + when(bundleContext.getService(sref3)).thenReturn(clientFactory); + } + + private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { + ObjectMapper mapper = new ObjectMapperMock(); + ObjectMapper mapper2 = new ObjectMapper(); + Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper"); + field.setAccessible(true); + if (command) { + field.set(netconfClientPlugin, mapper); + } else { + field.set(netconfClientPlugin, mapper2); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java new file mode 100644 index 000000000..5137b904b --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/NetconfDBPluginImplTest.java @@ -0,0 +1,253 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.*; +import org.onap.appc.adapter.netconf.ConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.appc.dg.netconf.impl.NetconfDBPluginImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import static org.powermock.api.support.SuppressCode.suppressConstructor; + +public class NetconfDBPluginImplTest { + private NetconfDBPluginImpl netconfDBPlugin; + private NetconfDataAccessService daoService; + private DAOServiceMock daoMock; + private Map params; + private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + String host = "http://www.test.com"; + String host1 = "http://www.test1.com"; + int port = 8080; + String username = "test"; + String password = "test"; + String configContent = "\n" + + "\n" + + "\t\n" + + "\t\t\n" + + "\t\t\t\n" + + "\t\t \n" + + "\t\n" + + "'"; + + + @Test + public void testRetrieveDSConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("configuration-file-name", "VnfGetRunningConfig"); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveDSConfiguration(params, ctx); + + Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); + Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); + } + + + @Test + public void testRetrieveDSConfigurationNegativeErrorFieldNameDaoException() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("configuration-file-name", "wrong"); + + try { + netconfDBPlugin.retrieveDSConfiguration(params, ctx); + } catch (DataAccessException e) { + //Assert.assertNotNull(ctx.getAttribute("org.onap.appc.dg.error")); + Assert.assertNull(ctx.getAttribute("file-content")); + } + + + } + + @Test + public void testRetrieveVMDSConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("resourceKey", "VNF"); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + + Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result", "success", ctx.getAttribute("retrieveVMDSConfiguration_Result")); + Assert.assertEquals("wrong entity", "VNF", ctx.getAttribute("entity")); + assertConnectionDetails(ctx, host); + } + + @Test + public void testRetrieveVMDSConfigurationNegativeMissingConfiguration() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("resourceKey", "MOCK"); + + try { + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + + Assert.assertEquals("failure", ctx.getAttribute("retrieveVMDSConfiguration_Result")); + } + } + + + @Test + public void testRetrieveVMDSConfigurationNegativeJsonProcessingException() throws Exception { + + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("resourceKey", "VNF"); + + init(); + substituteMapper(true); + try { + netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); + substituteMapper(false); + Assert.assertTrue(false); + + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + + } + + } + + @Test + public void testRetrieveConfigFile() throws Exception { + init(); + SvcLogicContext ctx = new SvcLogicContext(); + params = new HashMap<>(); + params.put("configuration-file-name", "VnfGetRunningConfig"); + netconfDBPlugin.retrieveConfigFile(params, ctx); + + Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); + Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); + } + + @Test + public void testRetrieveConnectionDetails() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + + assertConnectionDetails(ctx, host1); + } + + @Test + public void testRetrieveConnectionDetailsNegativeJsonProcessingException() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "MOCK"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + + try { + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + Assert.assertTrue(false); + } catch (APPCException e) { + Assert.assertNull(ctx.getAttribute("connection-details")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + } + + + @Test + public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { + init(); + params = new HashMap<>(); + params.put("org.onap.appc.vftype", "VNF"); + params.put("vnf-host-ip-address", host1); + SvcLogicContext ctx = new SvcLogicContext(); + substituteMapper(true); + + try { + netconfDBPlugin.retrieveConnectionDetails(params, ctx); + substituteMapper(false); + Assert.assertTrue(false); + } catch (APPCException e) { + substituteMapper(false); + Assert.assertNull(ctx.getAttribute("connection-details")); + Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); + } + + } + + private void assertConnectionDetails(SvcLogicContext ctx, String host) throws IOException { + String sConnectionDetails = ctx.getAttribute("connection-details"); + NetconfConnectionDetails connectionDetails = new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class); + Assert.assertEquals(host, connectionDetails.getHost()); + Assert.assertEquals(port, connectionDetails.getPort()); + Assert.assertEquals(username, connectionDetails.getUsername()); + Assert.assertEquals(password, connectionDetails.getPassword()); + Assert.assertNull(connectionDetails.getCapabilities()); + Assert.assertNull(connectionDetails.getAdditionalProperties()); + } + + private void init() { + netconfDBPlugin = new NetconfDBPluginImpl(); + daoService = new DAOServiceMock(); + netconfDBPlugin.setDaoService(daoService); + daoMock = (DAOServiceMock) daoService; + daoMock.setConfigFile(configContent); + daoMock.setConnection(getConnectionDetails()); + + } + + private ConnectionDetails getConnectionDetails() { + ConnectionDetails connectionDetails = new ConnectionDetails(); + connectionDetails.setHost(host); + connectionDetails.setUsername(username); + connectionDetails.setPort(port); + connectionDetails.setPassword(password); + return connectionDetails; + } + + private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { + ObjectMapper mapper = new ObjectMapperMock(); + ObjectMapper mapper2 = new ObjectMapper(); + Field field = NetconfDBPluginImpl.class.getDeclaredField("mapper"); + field.setAccessible(true); + if (command) { + field.set(netconfDBPlugin, mapper); + } else { + field.set(netconfDBPlugin, mapper2); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java new file mode 100644 index 000000000..cacc15eae --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/ObjectMapperMock.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; + + +public class ObjectMapperMock extends ObjectMapper { + + @Override + public String writeValueAsString(Object var1) throws JsonProcessingException { + throw new JsonProcessingException("") { + }; + + } + + @Override + public T readValue(String var1, Class var2) throws IOException, JsonParseException, JsonMappingException { + return null; + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java new file mode 100644 index 000000000..2194fc14c --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/onap/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.netconf.impl; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.appc.adapter.netconf.*; + + +public class OperationStateValidatorFactoryMock extends OperationalStateValidatorFactory { + public static OperationalStateValidator getOperationalStateValidator(String vnfType) { + VnfType vnfTypeEnum = null; + try { + vnfTypeEnum = VnfType.getVnfType(vnfType); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Illegal value in vnfType. vnfType=" + vnfType, e); + } + return getOperationalStateValidator(vnfTypeEnum); + } + + public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { + + return new MockOperationalStateValidatorImpl(); + + + } + + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java deleted file mode 100644 index 379e164b5..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/DAOServiceMock.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import java.util.HashMap; - -import org.onap.appc.adapter.netconf.ConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -class DAOServiceMock implements NetconfDataAccessService { - - private String configFile; - private ConnectionDetails connection; - private HashMap backupConf; - - @Override - public void setSchema(String schema) { - } - - @Override - public void setDbLibService(DbLibService dbLibService) { - } - - void setConfigFile(String configFile) { - this.configFile = configFile; - } - - public HashMap getBackupConf() { - return backupConf; - } - - public void setConnection(ConnectionDetails connection) { - this.connection = connection; - } - - @Override - public String retrieveConfigFileName(String xmlID) throws DataAccessException { - if (!xmlID.equals("wrong")) { - return configFile; - } else { - throw new DataAccessException(); - } - } - - @Override - public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws - DataAccessException { - return false; - } - - @Override - public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws - DataAccessException { - if (vnfType.equals("VNF")) { - connectionDetails.setHost(connection.getHost()); - connectionDetails.setPassword(connection.getPassword()); - connectionDetails.setPort(connection.getPort()); - connectionDetails.setUsername(connection.getUsername()); - - return true; - } else { - return false; - } - } - - @Override - public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws - DataAccessException { - this.backupConf = new HashMap<>(); - backupConf.put("creationDate", creationDate); - backupConf.put("logText", logText); - return true; - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java deleted file mode 100644 index 802fe15e0..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/MockOperationalStateValidatorImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.OperationalStateValidator; -import org.onap.appc.adapter.netconf.VnfType; -import org.onap.appc.exceptions.APPCException; - - -public class MockOperationalStateValidatorImpl implements OperationalStateValidator { - - private boolean validated; - private String configurationFileName; - - public boolean isValidated() { - return validated; - } - - @Override - public VnfType getVnfType() { - return null; - } - - @Override - public String getConfigurationFileName() { - return configurationFileName; - } - - @Override - public void validateResponse(String response) throws APPCException { - if (response.equals("wrong")) { - throw new APPCException(); - } else { - this.validated = true; - } - - } - - public void setConfigurationFileName(String configurationFileName) { - this.configurationFileName = configurationFileName; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java deleted file mode 100644 index f61d188d9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientFactoryMock.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfClientFactory; -import org.onap.appc.adapter.netconf.NetconfClientType; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; - - -public class NetconfClientFactoryMock extends NetconfClientFactory { - - private final NetconfClientJschMock jschClient = new NetconfClientJschMock(); - - @Override - public NetconfClient GetNetconfClient(NetconfClientType type){ - - return jschClient; - - } -} - - diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java deleted file mode 100644 index 82361a95e..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientJschMock.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.exceptions.APPCException; - - -public class NetconfClientJschMock implements NetconfClient { - - private boolean connection; - private String lastMessage; - private String answer = "answer"; - private String configuration; - private NetconfConnectionDetails lastConnectionDetails; - - public boolean isConnection() { - return connection; - } - - public String getLastMessage() { - return lastMessage; - } - - public String getAnswer() { - return answer; - } - - public String getConf() { - return configuration; - } - - public void setConf(String configuration) { - this.configuration = configuration; - } - - public void setAnswer(String answer) { - this.answer = answer; - } - - public NetconfConnectionDetails getLastConnectionDetails() { - return lastConnectionDetails; - } - - @Override - public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { - this.connection = true; - this.lastConnectionDetails = connectionDetails; - - } - - @Override - public String exchangeMessage(String message) throws APPCException { - if (connection) { - this.lastMessage = message; - return answer; - } else return null; - } - - @Override - public void configure(String configuration) throws APPCException { - if (connection) { - this.configuration = configuration; - } - - } - - @Override - public String getConfiguration() throws APPCException { - if (connection) { - return configuration; - } else return null; - } - - @Override - public void disconnect() throws APPCException { - this.connection = false; - - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java deleted file mode 100644 index 0becff701..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java +++ /dev/null @@ -1,681 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.onap.appc.exceptions.APPCException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.netconf.*; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.dg.netconf.impl.NetconfClientPluginImpl; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.lang.reflect.Field; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.when; - - - -@RunWith(PowerMockRunner.class) -@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class}) - -public class NetconfClientPluginImplTest { - private NetconfClientPluginImpl netconfClientPlugin; - private NetconfDataAccessService dao; - private NetconfClientFactory clientFactory; - private Map params; - - private final BundleContext bundleContext = Mockito.mock(BundleContext.class); - private final Bundle bundleService = Mockito.mock(Bundle.class); - private final ServiceReference sref1 = Mockito.mock(ServiceReference.class); - private final ServiceReference sref2 = Mockito.mock(ServiceReference.class); - private final ServiceReference sref3 = Mockito.mock(ServiceReference.class); - private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - - - String host = "http://www.test.com"; - String host1 = "http://www.test1.com"; - String vnfType = "VNF"; - int port = 8080; - String username = "test"; - String password = "test"; - String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}"; - String fileContent = "\n" + - "\n" + - "\t\n" + - "\t\t\n" + - "\t\t\t\n" + - "\t\t \n" + - "\t\n" + - "'"; - String operationalState = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"; - - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - clientFactory = new NetconfClientFactoryMock(); - - } - - - @Test - public void testConfigure() throws Exception { - - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - - netconfClientPlugin.configure(params, ctx); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - - try { - Assert.assertEquals("wrong configuration", fileContent, client.getConf()); - Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost()); - Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort()); - Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername()); - Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword()); - Assert.assertFalse(client.isConnection()); - } catch (Exception e) { - Assert.fail("failed with because of " + e.getCause()); - } - - - } - - - @Test - public void testConfigureNegativeIOException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - - - try { - netconfClientPlugin.configure(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(client.getLastConnectionDetails()); - Assert.assertNull(client.getConf()); - } - - } - - @Test - public void testOperationStateValidation() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - - @Test - public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - substituteMapper(true); - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - substituteMapper(false); - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse(validatorMock.isValidated()); - Assert.assertNull(client.getLastMessage()); - } - } - - @Test - public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class); - final NetconfConnectionDetails netconfConnectionDetails = null; - when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails); - - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse("validation process failed", validatorMock.isValidated()); - - } - } - - - @Test - public void testOperationStateValidationNegativeAppcException() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer("wrong"); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - - try { - netconfClientPlugin.operationStateValidation(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - Assert.assertFalse("validation process failed", validatorMock.isValidated()); - - } - } - - - @Test - public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - ((DAOServiceMock) dao).setConnection(getConnectionDetails()); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, ""); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - @Test - public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setAnswer(operationalState); - ((DAOServiceMock) dao).setConnection(getConnectionDetails()); - - - params = new HashMap<>(); - params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType); - params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null); - MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl(); - validatorMock.setConfigurationFileName("VnfGetRunningConfig"); - - PowerMockito.mockStatic(OperationalStateValidatorFactory.class); - when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock); - - netconfClientPlugin.operationStateValidation(params, ctx); - - Assert.assertTrue("validation process failed", validatorMock.isValidated()); - Assert.assertEquals(fileContent, client.getLastMessage()); - } - - - @Test - public void testBackupConfiguration() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - netconfClientPlugin.backupConfiguration(params, ctx); - - DAOServiceMock mockdao = (DAOServiceMock) dao; - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); - Date date = new Date(); - String creationDateExpected = dateFormat.format(date); - String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10); - - - Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText")); - Assert.assertEquals(creationDateExpected, creationDateActual); - - - } - - - @Test - public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception { - shortInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - try { - netconfClientPlugin.backupConfiguration(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - - DAOServiceMock mockdao = (DAOServiceMock) dao; - Assert.assertNull(mockdao.getBackupConf()); - } - - } - - @Test - public void testGetConfig() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result")); - Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig")); - Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration")); - } - - - @Test - public void testGetConfigNegativeConfigurationNull() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - } - - - @Test - public void testGetConfigNegativeNotSupportedConfId() throws Exception { - fullInit(); - String entity = "123"; - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current1"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails); - - - netconfClientPlugin.getConfig(params, ctx); - - Assert.assertNull(ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - } - - @Test - public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception { - fullInit(); - String entity = "123"; - - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("entity", entity); - - params = new HashMap<>(); - params.put("conf-id", "current"); - params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails); - - - try { - netconfClientPlugin.getConfig(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result")); - Assert.assertNull(ctx.getAttribute("fullConfig")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNull(ctx.getAttribute(entity + ".Configuration")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - - } - - @Test - public void testGetRunningConfig() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - params.put("port-number", String.valueOf(port)); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - netconfClientPlugin.getRunningConfig(params, ctx); - - Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertEquals(fileContent, ctx.getAttribute("running-config")); - Assert.assertEquals("success", ctx.getStatus()); - } - - @Test - public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - - NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH); - client.setConf(fileContent); - - try { - netconfClientPlugin.getRunningConfig(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertNull(ctx.getAttribute("running-config")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - - } - - @Test - public void testGetRunningConfigNegativeConfigurationNull() throws Exception { - fullInit(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("host-ip-address", host); - params.put("user-name", username); - params.put("password", password); - params.put("port-number", String.valueOf(port)); - - netconfClientPlugin.getRunningConfig(params, ctx); - - Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result")); - Assert.assertNull(ctx.getAttribute("running-config")); - } - - @Test - public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception { - shortInit(); - String paramName = "test"; - String paramValue = ""; - - try { - netconfClientPlugin.validateMandatoryParam(paramName, paramValue); - Assert.assertTrue(false); - } catch (Exception e) { - Assert.assertTrue(true); - } - } - - @Test - public void testRetrieveConnectionDetails() throws Exception { - shortInit(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - ConnectionDetails connectionDetails1 = getConnectionDetails(); - daoServiceMock.setConnection(connectionDetails1); - - NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF); - - - Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost()); - Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword()); - Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort()); - Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername()); - } - - - @Test - public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { - shortInit(); - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - ConnectionDetails connectionDetails1 = getConnectionDetails(); - daoServiceMock.setConnection(connectionDetails1); - - NetconfConnectionDetails connectionDetailsActual = null; - try { - connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(connectionDetailsActual); - } - - - } - - @Test - public void testRetrieveConfigurationFileContent() throws Exception { - shortInit(); - - DAOServiceMock daoServiceMock = (DAOServiceMock) dao; - daoServiceMock.setConfigFile(fileContent); - - Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig")); - } - - private ConnectionDetails getConnectionDetails() { - - ConnectionDetails connectionDetails = new ConnectionDetails(); - connectionDetails.setPassword(password); - connectionDetails.setPort(port); - connectionDetails.setUsername(username); - connectionDetails.setHost(host); - return connectionDetails; - } - - - private void initDao() throws NoSuchFieldException, IllegalAccessException { - dao = new DAOServiceMock(); - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1); - when(bundleContext.getService(sref1)).thenReturn(dao); - - - } - - private void fullInit() throws NoSuchFieldException, IllegalAccessException { - initClientFactory(); - initClientFactory2(); - initDao(); - netconfClientPlugin = new NetconfClientPluginImpl(); - netconfClientPlugin.setDao(this.dao); - } - - private void shortInit() throws NoSuchFieldException, IllegalAccessException { - initClientFactory(); - initDao(); - netconfClientPlugin = new NetconfClientPluginImpl(); - netconfClientPlugin.setDao(this.dao); - } - - private void initClientFactory() throws NoSuchFieldException, IllegalAccessException { - - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2); - when(bundleContext.getService(sref2)).thenReturn(clientFactory); - - } - - private void initClientFactory2() { - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService); - when(bundleService.getBundleContext()).thenReturn(bundleContext); - when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3); - when(bundleContext.getService(sref3)).thenReturn(clientFactory); - } - - private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { - ObjectMapper mapper = new ObjectMapperMock(); - ObjectMapper mapper2 = new ObjectMapper(); - Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper"); - field.setAccessible(true); - if (command) { - field.set(netconfClientPlugin, mapper); - } else { - field.set(netconfClientPlugin, mapper2); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java deleted file mode 100644 index 5137b904b..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfDBPluginImplTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.*; -import org.onap.appc.adapter.netconf.ConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.appc.dg.netconf.impl.NetconfDBPluginImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.support.SuppressCode.suppressConstructor; - -public class NetconfDBPluginImplTest { - private NetconfDBPluginImpl netconfDBPlugin; - private NetconfDataAccessService daoService; - private DAOServiceMock daoMock; - private Map params; - private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - String host = "http://www.test.com"; - String host1 = "http://www.test1.com"; - int port = 8080; - String username = "test"; - String password = "test"; - String configContent = "\n" + - "\n" + - "\t\n" + - "\t\t\n" + - "\t\t\t\n" + - "\t\t \n" + - "\t\n" + - "'"; - - - @Test - public void testRetrieveDSConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("configuration-file-name", "VnfGetRunningConfig"); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveDSConfiguration(params, ctx); - - Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); - Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); - } - - - @Test - public void testRetrieveDSConfigurationNegativeErrorFieldNameDaoException() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("configuration-file-name", "wrong"); - - try { - netconfDBPlugin.retrieveDSConfiguration(params, ctx); - } catch (DataAccessException e) { - //Assert.assertNotNull(ctx.getAttribute("org.onap.appc.dg.error")); - Assert.assertNull(ctx.getAttribute("file-content")); - } - - - } - - @Test - public void testRetrieveVMDSConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("resourceKey", "VNF"); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - - Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result", "success", ctx.getAttribute("retrieveVMDSConfiguration_Result")); - Assert.assertEquals("wrong entity", "VNF", ctx.getAttribute("entity")); - assertConnectionDetails(ctx, host); - } - - @Test - public void testRetrieveVMDSConfigurationNegativeMissingConfiguration() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("resourceKey", "MOCK"); - - try { - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - - Assert.assertEquals("failure", ctx.getAttribute("retrieveVMDSConfiguration_Result")); - } - } - - - @Test - public void testRetrieveVMDSConfigurationNegativeJsonProcessingException() throws Exception { - - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("resourceKey", "VNF"); - - init(); - substituteMapper(true); - try { - netconfDBPlugin.retrieveVMDSConfiguration(params, ctx); - substituteMapper(false); - Assert.assertTrue(false); - - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - - } - - } - - @Test - public void testRetrieveConfigFile() throws Exception { - init(); - SvcLogicContext ctx = new SvcLogicContext(); - params = new HashMap<>(); - params.put("configuration-file-name", "VnfGetRunningConfig"); - netconfDBPlugin.retrieveConfigFile(params, ctx); - - Assert.assertEquals("lack of success of status", "success", ctx.getStatus()); - Assert.assertEquals("wrong config file content", configContent, ctx.getAttribute("file-content")); - } - - @Test - public void testRetrieveConnectionDetails() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - - assertConnectionDetails(ctx, host1); - } - - @Test - public void testRetrieveConnectionDetailsNegativeJsonProcessingException() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "MOCK"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - - try { - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - Assert.assertTrue(false); - } catch (APPCException e) { - Assert.assertNull(ctx.getAttribute("connection-details")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - } - - - @Test - public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception { - init(); - params = new HashMap<>(); - params.put("org.onap.appc.vftype", "VNF"); - params.put("vnf-host-ip-address", host1); - SvcLogicContext ctx = new SvcLogicContext(); - substituteMapper(true); - - try { - netconfDBPlugin.retrieveConnectionDetails(params, ctx); - substituteMapper(false); - Assert.assertTrue(false); - } catch (APPCException e) { - substituteMapper(false); - Assert.assertNull(ctx.getAttribute("connection-details")); - Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE)); - } - - } - - private void assertConnectionDetails(SvcLogicContext ctx, String host) throws IOException { - String sConnectionDetails = ctx.getAttribute("connection-details"); - NetconfConnectionDetails connectionDetails = new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class); - Assert.assertEquals(host, connectionDetails.getHost()); - Assert.assertEquals(port, connectionDetails.getPort()); - Assert.assertEquals(username, connectionDetails.getUsername()); - Assert.assertEquals(password, connectionDetails.getPassword()); - Assert.assertNull(connectionDetails.getCapabilities()); - Assert.assertNull(connectionDetails.getAdditionalProperties()); - } - - private void init() { - netconfDBPlugin = new NetconfDBPluginImpl(); - daoService = new DAOServiceMock(); - netconfDBPlugin.setDaoService(daoService); - daoMock = (DAOServiceMock) daoService; - daoMock.setConfigFile(configContent); - daoMock.setConnection(getConnectionDetails()); - - } - - private ConnectionDetails getConnectionDetails() { - ConnectionDetails connectionDetails = new ConnectionDetails(); - connectionDetails.setHost(host); - connectionDetails.setUsername(username); - connectionDetails.setPort(port); - connectionDetails.setPassword(password); - return connectionDetails; - } - - private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException { - ObjectMapper mapper = new ObjectMapperMock(); - ObjectMapper mapper2 = new ObjectMapper(); - Field field = NetconfDBPluginImpl.class.getDeclaredField("mapper"); - field.setAccessible(true); - if (command) { - field.set(netconfDBPlugin, mapper); - } else { - field.set(netconfDBPlugin, mapper2); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java deleted file mode 100644 index cacc15eae..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/ObjectMapperMock.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - - -public class ObjectMapperMock extends ObjectMapper { - - @Override - public String writeValueAsString(Object var1) throws JsonProcessingException { - throw new JsonProcessingException("") { - }; - - } - - @Override - public T readValue(String var1, Class var2) throws IOException, JsonParseException, JsonMappingException { - return null; - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java deleted file mode 100644 index 2194fc14c..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/OperationStateValidatorFactoryMock.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.netconf.impl; - -import org.apache.commons.lang3.NotImplementedException; -import org.onap.appc.adapter.netconf.*; - - -public class OperationStateValidatorFactoryMock extends OperationalStateValidatorFactory { - public static OperationalStateValidator getOperationalStateValidator(String vnfType) { - VnfType vnfTypeEnum = null; - try { - vnfTypeEnum = VnfType.getVnfType(vnfType); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Illegal value in vnfType. vnfType=" + vnfType, e); - } - return getOperationalStateValidator(vnfTypeEnum); - } - - public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { - - return new MockOperationalStateValidatorImpl(); - - - } - - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java new file mode 100644 index 000000000..da5e3dfe6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshDBPlugin.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +public interface SshDBPlugin extends SvcLogicJavaPlugin { + void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java new file mode 100644 index 000000000..591e58805 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/SshService.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * Set of common methods that can be called from DG. + */ +public interface SshService extends SvcLogicJavaPlugin { + + /** + * Input parameter for SHH connection details + */ + String PARAM_IN_connection_details = "connection_details"; + + /** + * Input parameter for SSH command to be executed. + */ + String PARAM_IN_command = "command"; + + /** + * Input parameter for SSH command timeout + */ + String PARAM_IN_timeout = "timeout"; + + /** + * Output parameter - SSH command execution status. + */ + String PARAM_OUT_status = "status"; + + /** + * Output parameter - content of SSH command stdout. + */ + String PARAM_OUT_stdout = "stdout"; + + /** + * Output parameter - content of SSH command stderr. + */ + String PARAM_OUT_stderr = "stderr"; + + /** + * Default SSH connection port. + */ + int DEF_port = 22; + + /** + * Default SSH command timeout + */ + long DEF_timeout = 120000; + + /** + * Default success status. + */ + int DEF_SUCCESS_STATUS = 0; + + /** + * Execute remote command over SSH. + * + * @param params contains list of input parameters required for the implementation + * @param ctx SLI service logic context + * @throws APPCException + */ + void exec(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * Execute remote command over SSH and check return status assuming that success status is 0. + * If non-zero status is returned - fail the execution by throwing exception with content written + * by command to stderr. + * + * @param params contains list of input parameters required for the implementation + * @param ctx SLI service logic context + * @throws APPCException + */ + void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java new file mode 100644 index 000000000..c3dfc61d6 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshDBPluginImpl.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.Map; + +import org.onap.appc.adapter.ssh.Constants; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.adapter.ssh.SshDataAccessException; +import org.onap.appc.adapter.ssh.SshDataAccessService; +import org.onap.appc.dg.ssh.SshDBPlugin; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class SshDBPluginImpl implements SshDBPlugin { + + private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static ObjectMapper mapper = new ObjectMapper(); + + private SshDataAccessService dataAccessService; + + public void setDataAccessService(SshDataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { + SshConnectionDetails connectionDetails = new SshConnectionDetails(); + //String vnfType = ctx.getAttribute("aai.prefix")+"."+"vnf-type"; + String vnfType = params.get("vnf-type"); + try { + if (!dataAccessService.retrieveConnectionDetails(vnfType, connectionDetails)) { + logger.error("Missing connection details for VNF type: " + vnfType); + throw new APPCException("Missing configuration for " + vnfType + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); + } + connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); + ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); + } catch(APPCException e) { + String msg = EELFResourceManager.format(Msg.APPC_EXCEPTION, vnfType, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); + throw e; + } catch(SshDataAccessException e) { + String msg = EELFResourceManager.format(Msg.SSH_DATA_EXCEPTION, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw e; + } catch (JsonProcessingException e) { + String msg = EELFResourceManager.format(Msg.JSON_PROCESSING_EXCEPTION, e.getMessage()); + logger.error(msg); + ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + throw new APPCException(e); + } + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java new file mode 100644 index 000000000..1c584cdb9 --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/onap/appc/dg/ssh/impl/SshServiceImpl.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; + +import org.onap.appc.adapter.ssh.SshAdapter; +import org.onap.appc.adapter.ssh.SshConnection; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.dg.ssh.SshService; +import org.onap.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +public class SshServiceImpl implements SshService { + + private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static final ObjectMapper mapper = new ObjectMapper(); + + private SshAdapter sshAdapter; + + public void setSshAdapter(SshAdapter sshAdapter) { + this.sshAdapter = sshAdapter; + } + + @Override + public void exec(Map params, SvcLogicContext ctx) throws APPCException { + SshConnectionDetails connectionDetails = resolveConnectionDetails(params.get(PARAM_IN_connection_details)); + String command = params.get(PARAM_IN_command); + logger.debug("=> Connecting to SSH server..."); + SshConnection sshConnection = sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(), connectionDetails.getUsername(), connectionDetails.getPassword()); + sshConnection.connect(); + try { + logger.debug("=> Connected to SSH server..."); + logger.debug("=> Running SSH command..."); + long timeout = DEF_timeout; + String stimeout = params.get(PARAM_IN_timeout); + if ((stimeout != null && !stimeout.isEmpty())) { + timeout = Long.parseLong(stimeout); + } + sshConnection.setExecTimeout(timeout); + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + int status = sshConnection.execCommand(command, stdout, stderr); + String stdoutRes = stdout.toString(); + String stderrRes = stderr.toString(); + logger.debug("=> executed SSH command"); + ctx.setAttribute(PARAM_OUT_status, String.format("%01d", status)); + ctx.setAttribute(PARAM_OUT_stdout, stdoutRes); + ctx.setAttribute(PARAM_OUT_stderr, stderrRes); + } finally { + sshConnection.disconnect(); + } + } + + private SshConnectionDetails resolveConnectionDetails(String connectionDetailsStr) throws APPCException { + SshConnectionDetails connectionDetails = null; + try { + connectionDetails = mapper.readValue(connectionDetailsStr, SshConnectionDetails.class); + if (0 == connectionDetails.getPort()) connectionDetails.setPort(DEF_port); + } catch (IOException e) { + throw new APPCException(e); + } + return connectionDetails; + } + + @Override + public void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException { + exec(params, ctx); + int status = Integer.parseInt(ctx.getAttribute(PARAM_OUT_status)); + if(status != DEF_SUCCESS_STATUS) { + StringBuilder errmsg = new StringBuilder(); + errmsg.append("SSH command returned error status [").append(status).append(']'); + String stderr = ctx.getAttribute(PARAM_OUT_stderr); + if((stderr != null) && !stderr.isEmpty()) { + errmsg.append(". Error: [").append(stderr).append(']'); + } + throw new APPCException(errmsg.toString()); + } + } +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java deleted file mode 100644 index da5e3dfe6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshDBPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -public interface SshDBPlugin extends SvcLogicJavaPlugin { - void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java deleted file mode 100644 index 591e58805..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/SshService.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -/** - * Set of common methods that can be called from DG. - */ -public interface SshService extends SvcLogicJavaPlugin { - - /** - * Input parameter for SHH connection details - */ - String PARAM_IN_connection_details = "connection_details"; - - /** - * Input parameter for SSH command to be executed. - */ - String PARAM_IN_command = "command"; - - /** - * Input parameter for SSH command timeout - */ - String PARAM_IN_timeout = "timeout"; - - /** - * Output parameter - SSH command execution status. - */ - String PARAM_OUT_status = "status"; - - /** - * Output parameter - content of SSH command stdout. - */ - String PARAM_OUT_stdout = "stdout"; - - /** - * Output parameter - content of SSH command stderr. - */ - String PARAM_OUT_stderr = "stderr"; - - /** - * Default SSH connection port. - */ - int DEF_port = 22; - - /** - * Default SSH command timeout - */ - long DEF_timeout = 120000; - - /** - * Default success status. - */ - int DEF_SUCCESS_STATUS = 0; - - /** - * Execute remote command over SSH. - * - * @param params contains list of input parameters required for the implementation - * @param ctx SLI service logic context - * @throws APPCException - */ - void exec(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * Execute remote command over SSH and check return status assuming that success status is 0. - * If non-zero status is returned - fail the execution by throwing exception with content written - * by command to stderr. - * - * @param params contains list of input parameters required for the implementation - * @param ctx SLI service logic context - * @throws APPCException - */ - void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java deleted file mode 100644 index c3dfc61d6..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshDBPluginImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.Map; - -import org.onap.appc.adapter.ssh.Constants; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.adapter.ssh.SshDataAccessException; -import org.onap.appc.adapter.ssh.SshDataAccessService; -import org.onap.appc.dg.ssh.SshDBPlugin; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class SshDBPluginImpl implements SshDBPlugin { - - private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static ObjectMapper mapper = new ObjectMapper(); - - private SshDataAccessService dataAccessService; - - public void setDataAccessService(SshDataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public void retrieveConnectionDetails(Map params, SvcLogicContext ctx) throws APPCException { - SshConnectionDetails connectionDetails = new SshConnectionDetails(); - //String vnfType = ctx.getAttribute("aai.prefix")+"."+"vnf-type"; - String vnfType = params.get("vnf-type"); - try { - if (!dataAccessService.retrieveConnectionDetails(vnfType, connectionDetails)) { - logger.error("Missing connection details for VNF type: " + vnfType); - throw new APPCException("Missing configuration for " + vnfType + " in " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME); - } - connectionDetails.setHost(params.get(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME)); - ctx.setAttribute(Constants.CONNECTION_DETAILS_FIELD_NAME, mapper.writeValueAsString(connectionDetails)); - } catch(APPCException e) { - String msg = EELFResourceManager.format(Msg.APPC_EXCEPTION, vnfType, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE,msg); - throw e; - } catch(SshDataAccessException e) { - String msg = EELFResourceManager.format(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw e; - } catch (JsonProcessingException e) { - String msg = EELFResourceManager.format(Msg.JSON_PROCESSING_EXCEPTION, e.getMessage()); - logger.error(msg); - ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - throw new APPCException(e); - } - } - -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java deleted file mode 100644 index 1c584cdb9..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/main/java/org/openecomp/appc/dg/ssh/impl/SshServiceImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -import org.onap.appc.adapter.ssh.SshAdapter; -import org.onap.appc.adapter.ssh.SshConnection; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.dg.ssh.SshService; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -public class SshServiceImpl implements SshService { - - private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - private static final ObjectMapper mapper = new ObjectMapper(); - - private SshAdapter sshAdapter; - - public void setSshAdapter(SshAdapter sshAdapter) { - this.sshAdapter = sshAdapter; - } - - @Override - public void exec(Map params, SvcLogicContext ctx) throws APPCException { - SshConnectionDetails connectionDetails = resolveConnectionDetails(params.get(PARAM_IN_connection_details)); - String command = params.get(PARAM_IN_command); - logger.debug("=> Connecting to SSH server..."); - SshConnection sshConnection = sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(), connectionDetails.getUsername(), connectionDetails.getPassword()); - sshConnection.connect(); - try { - logger.debug("=> Connected to SSH server..."); - logger.debug("=> Running SSH command..."); - long timeout = DEF_timeout; - String stimeout = params.get(PARAM_IN_timeout); - if ((stimeout != null && !stimeout.isEmpty())) { - timeout = Long.parseLong(stimeout); - } - sshConnection.setExecTimeout(timeout); - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - int status = sshConnection.execCommand(command, stdout, stderr); - String stdoutRes = stdout.toString(); - String stderrRes = stderr.toString(); - logger.debug("=> executed SSH command"); - ctx.setAttribute(PARAM_OUT_status, String.format("%01d", status)); - ctx.setAttribute(PARAM_OUT_stdout, stdoutRes); - ctx.setAttribute(PARAM_OUT_stderr, stderrRes); - } finally { - sshConnection.disconnect(); - } - } - - private SshConnectionDetails resolveConnectionDetails(String connectionDetailsStr) throws APPCException { - SshConnectionDetails connectionDetails = null; - try { - connectionDetails = mapper.readValue(connectionDetailsStr, SshConnectionDetails.class); - if (0 == connectionDetails.getPort()) connectionDetails.setPort(DEF_port); - } catch (IOException e) { - throw new APPCException(e); - } - return connectionDetails; - } - - @Override - public void execWithStatusCheck(Map params, SvcLogicContext ctx) throws APPCException { - exec(params, ctx); - int status = Integer.parseInt(ctx.getAttribute(PARAM_OUT_status)); - if(status != DEF_SUCCESS_STATUS) { - StringBuilder errmsg = new StringBuilder(); - errmsg.append("SSH command returned error status [").append(status).append(']'); - String stderr = ctx.getAttribute(PARAM_OUT_stderr); - if((stderr != null) && !stderr.isEmpty()) { - errmsg.append(". Error: [").append(stderr).append(']'); - } - throw new APPCException(errmsg.toString()); - } - } -} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java new file mode 100644 index 000000000..bb232863f --- /dev/null +++ b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/onap/appc/dg/ssh/impl/SshServiceImplTest.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.dg.ssh.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.appc.adapter.ssh.SshAdapterMock; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.adapter.ssh.SshConnectionMock; +import org.onap.appc.dg.ssh.SshService; +import org.onap.appc.dg.ssh.impl.SshServiceImpl; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class SshServiceImplTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testExec() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshService.setSshAdapter(sshAdapterMock); + + System.out.println("=> Executing SSH command [" + command + "]..."); + + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + sshService.exec(params, svcLogicContext); + int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); + String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); + String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); + System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); + + List connectionMocks = sshAdapterMock.getConnectionMocks(); + Assert.assertEquals(1, connectionMocks.size()); + SshConnectionMock connectionMock = connectionMocks.get(0); + Assert.assertNotNull(connectionMock); + Assert.assertEquals(host, connectionMock.getHost()); + Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); + Assert.assertEquals(username, connectionMock.getUsername()); + Assert.assertEquals(password, connectionMock.getPassword()); + Assert.assertEquals(1, connectionMock.getConnectCallCount()); + Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); + List executedCommands = connectionMock.getExecutedCommands(); + Assert.assertEquals(1, executedCommands.size()); + String executedCommand = executedCommands.get(0); + Assert.assertEquals(command, executedCommand); + } + + @Test + public void testExecWithStatusCheck() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshService.setSshAdapter(sshAdapterMock); + + System.out.println("=> Executing SSH command [" + command + "]..."); + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + sshService.execWithStatusCheck(params, svcLogicContext); + int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); + String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); + String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); + System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); + + List connectionMocks = sshAdapterMock.getConnectionMocks(); + Assert.assertEquals(1, connectionMocks.size()); + SshConnectionMock connectionMock = connectionMocks.get(0); + Assert.assertNotNull(connectionMock); + Assert.assertEquals(host, connectionMock.getHost()); + Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); + Assert.assertEquals(username, connectionMock.getUsername()); + Assert.assertEquals(password, connectionMock.getPassword()); + Assert.assertEquals(1, connectionMock.getConnectCallCount()); + Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); + List executedCommands = connectionMock.getExecutedCommands(); + Assert.assertEquals(1, executedCommands.size()); + String executedCommand = executedCommands.get(0); + Assert.assertEquals(command, executedCommand); + } + + /** + * Checks that execWithStatusCheck() throws appropriate exception if execution status != 0. + * + * @throws APPCException + * @throws JsonProcessingException + */ + @Test + public void testExecWithStatusCheckFail() throws APPCException, JsonProcessingException { + String host = "testhost"; + String username = "testuser"; + String password = "testpassword"; + String command = "cat keystonerc_Test"; + + int expectedStatus = 2; + String expectedErr = "Test failure"; + + SshServiceImpl sshService = new SshServiceImpl(); + SshAdapterMock sshAdapterMock = new SshAdapterMock(); + sshAdapterMock.setReturnStatus(expectedStatus); + sshAdapterMock.setReturnStderr(expectedErr); + sshService.setSshAdapter(sshAdapterMock); + + thrown.expect(APPCException.class); + thrown.expectMessage(CoreMatchers.containsString(expectedErr)); + + System.out.println("=> Executing SSH command [" + command + "]..."); + Map params = new HashMap<>(); + params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); + params.put(SshService.PARAM_IN_command, command); + SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); + // should fail, no need to perform further assertions + sshService.execWithStatusCheck(params, svcLogicContext); + } + + private String createConnectionDetails(String host, String username, String password) throws JsonProcessingException { + SshConnectionDetails connDetails = new SshConnectionDetails(); + connDetails.setHost(host); + connDetails.setUsername(username); + connDetails.setPassword(password); + return mapper.writeValueAsString(connDetails); + } + +} diff --git a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java b/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java deleted file mode 100644 index bb232863f..000000000 --- a/appc-dg/appc-dg-shared/appc-dg-ssh/src/test/java/org/openecomp/appc/dg/ssh/impl/SshServiceImplTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.dg.ssh.impl; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.appc.adapter.ssh.SshAdapterMock; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.adapter.ssh.SshConnectionMock; -import org.onap.appc.dg.ssh.SshService; -import org.onap.appc.dg.ssh.impl.SshServiceImpl; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -public class SshServiceImplTest { - - private static final ObjectMapper mapper = new ObjectMapper(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testExec() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshService.setSshAdapter(sshAdapterMock); - - System.out.println("=> Executing SSH command [" + command + "]..."); - - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - sshService.exec(params, svcLogicContext); - int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); - String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); - String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); - System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); - - List connectionMocks = sshAdapterMock.getConnectionMocks(); - Assert.assertEquals(1, connectionMocks.size()); - SshConnectionMock connectionMock = connectionMocks.get(0); - Assert.assertNotNull(connectionMock); - Assert.assertEquals(host, connectionMock.getHost()); - Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); - Assert.assertEquals(username, connectionMock.getUsername()); - Assert.assertEquals(password, connectionMock.getPassword()); - Assert.assertEquals(1, connectionMock.getConnectCallCount()); - Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); - List executedCommands = connectionMock.getExecutedCommands(); - Assert.assertEquals(1, executedCommands.size()); - String executedCommand = executedCommands.get(0); - Assert.assertEquals(command, executedCommand); - } - - @Test - public void testExecWithStatusCheck() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshService.setSshAdapter(sshAdapterMock); - - System.out.println("=> Executing SSH command [" + command + "]..."); - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - sshService.execWithStatusCheck(params, svcLogicContext); - int status = Integer.parseInt(svcLogicContext.getAttribute(SshService.PARAM_OUT_status)); - String stdout = svcLogicContext.getAttribute(SshService.PARAM_OUT_stdout); - String stderr = svcLogicContext.getAttribute(SshService.PARAM_OUT_stderr); - System.out.println("=> SSH command [" + command + "] status is [" + status + "]. stdout is [" + stdout + "]. stderr is [" + stderr + "]"); - - List connectionMocks = sshAdapterMock.getConnectionMocks(); - Assert.assertEquals(1, connectionMocks.size()); - SshConnectionMock connectionMock = connectionMocks.get(0); - Assert.assertNotNull(connectionMock); - Assert.assertEquals(host, connectionMock.getHost()); - Assert.assertEquals(SshService.DEF_port, connectionMock.getPort()); - Assert.assertEquals(username, connectionMock.getUsername()); - Assert.assertEquals(password, connectionMock.getPassword()); - Assert.assertEquals(1, connectionMock.getConnectCallCount()); - Assert.assertEquals(1, connectionMock.getDisconnectCallCount()); - List executedCommands = connectionMock.getExecutedCommands(); - Assert.assertEquals(1, executedCommands.size()); - String executedCommand = executedCommands.get(0); - Assert.assertEquals(command, executedCommand); - } - - /** - * Checks that execWithStatusCheck() throws appropriate exception if execution status != 0. - * - * @throws APPCException - * @throws JsonProcessingException - */ - @Test - public void testExecWithStatusCheckFail() throws APPCException, JsonProcessingException { - String host = "testhost"; - String username = "testuser"; - String password = "testpassword"; - String command = "cat keystonerc_Test"; - - int expectedStatus = 2; - String expectedErr = "Test failure"; - - SshServiceImpl sshService = new SshServiceImpl(); - SshAdapterMock sshAdapterMock = new SshAdapterMock(); - sshAdapterMock.setReturnStatus(expectedStatus); - sshAdapterMock.setReturnStderr(expectedErr); - sshService.setSshAdapter(sshAdapterMock); - - thrown.expect(APPCException.class); - thrown.expectMessage(CoreMatchers.containsString(expectedErr)); - - System.out.println("=> Executing SSH command [" + command + "]..."); - Map params = new HashMap<>(); - params.put(SshService.PARAM_IN_connection_details, createConnectionDetails(host,username,password)); - params.put(SshService.PARAM_IN_command, command); - SvcLogicContext svcLogicContext = new SvcLogicContext(new Properties()); - // should fail, no need to perform further assertions - sshService.execWithStatusCheck(params, svcLogicContext); - } - - private String createConnectionDetails(String host, String username, String password) throws JsonProcessingException { - SshConnectionDetails connDetails = new SshConnectionDetails(); - connDetails.setHost(host); - connDetails.setUsername(username); - connDetails.setPassword(password); - return mapper.writeValueAsString(connDetails); - } - -} -- cgit 1.2.3-korg